0% found this document useful (0 votes)
2 views

other code

The document provides multiple Android programming examples, including displaying built-in zoom controls in a WebView, converting temperatures using a ToggleButton, implementing the Android Activity Lifecycle with Toast messages, and creating a simple UI for number input using a TableLayout. It also covers property animations, showing the current location on a map, designing an employee registration form, and creating a rectangular progress bar. Additionally, it includes examples of ListView and GridView implementations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

other code

The document provides multiple Android programming examples, including displaying built-in zoom controls in a WebView, converting temperatures using a ToggleButton, implementing the Android Activity Lifecycle with Toast messages, and creating a simple UI for number input using a TableLayout. It also covers property animations, showing the current location on a map, designing an employee registration form, and creating a rectangular progress bar. Additionally, it includes examples of ListView and GridView implementations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

 State syntax to display built in zoom control

webView.getSettings().setBuiltInZoomControls(true);

webView.getSettings().setDisplayZoomControls(false); // Optional: hides the zoom buttons

 Write a program to convert temperature from celcius to farenhite and vice versa using Toggle
button. (Design UI as per your choice. Write XML and java file)

Here's a simple Android app that converts temperature between Celsius and Fahrenheit using
a ToggleButton.
When the ToggleButton is ON, it converts from Celsius to Fahrenheit.
When it's OFF, it converts from Fahrenheit to Celsius.

✅ 1. XML Layout (activity_main.xml)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="20dp">

<EditText
android:id="@+id/editTemp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Temperature"
android:inputType="numberDecimal" />

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="C to F"
android:textOff="F to C" />

<Button
android:id="@+id/btnConvert"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Convert" />

<TextView
android:id="@+id/textResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result will show here"
android:textSize="18sp"
android:paddingTop="20dp" />
</LinearLayout>

✅ 2. Java Code (MainActivity.java)


package com.example.temperatureconverter;

import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

EditText editTemp;
ToggleButton toggleButton;
Button btnConvert;
TextView textResult;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

editTemp = findViewById(R.id.editTemp);
toggleButton = findViewById(R.id.toggleButton);
btnConvert = findViewById(R.id.btnConvert);
textResult = findViewById(R.id.textResult);

btnConvert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String input = editTemp.getText().toString();

if (input.isEmpty()) {
textResult.setText("Please enter a temperature");
return;
}

double temp = Double.parseDouble(input);


double result;

if (toggleButton.isChecked()) {
// Celsius to Fahrenheit
result = (temp * 9 / 5) + 32;
textResult.setText("Fahrenheit: " + result);
} else {
// Fahrenheit to Celsius
result = (temp - 32) * 5 / 9;
textResult.setText("Celsius: " + result);
}
}
});
}
}

Let me know if you'd like the same app using Kotlin or with custom styling!

 Write a program to implement Android Activity Life Cycle. Use toast messages to display
message through life cycle.

Here's a simple Android program that demonstrates the Android Activity Life Cycle using
Toast messages.

Whenever an activity lifecycle method like onCreate, onStart, etc. is called, a Toast message
will show.

✅ 1. Java Code (MainActivity.java)


package com.example.lifecycleexample;

import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "onCreate Called", Toast.LENGTH_SHORT).show();
}

@Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "onStart Called", Toast.LENGTH_SHORT).show();
}

@Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "onResume Called", Toast.LENGTH_SHORT).show();
}

@Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "onPause Called", Toast.LENGTH_SHORT).show();
}

@Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "onStop Called", Toast.LENGTH_SHORT).show();
}

@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(this, "onRestart Called", Toast.LENGTH_SHORT).show();
}

@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "onDestroy Called", Toast.LENGTH_SHORT).show();
}
}

✅ 2. Layout XML (activity_main.xml)

This layout can be very simple — just a basic screen.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:text="Activity Life Cycle Demo"
android:textSize="20sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

🧪 Try It

 Run the app.


 Open, minimize, reopen, and close the app.
 You'll see Toast messages for each lifecycle event.

Would you like a visual diagram of the Android lifecycle as well?

 Design UI using table layout to display buttons with 0 – 9 numbers on it. Even display submit and
clear button. When user clicks on particular buttons and later when clicks on submit button, it
should display the numbers clicked.
Sure! Here's the simplest version of the app:

✅ 1. XML Layout (activity_main.xml)


<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">

<TableRow>
<Button android:id="@+id/btn1" android:text="1"/>
<Button android:id="@+id/btn2" android:text="2"/>
<Button android:id="@+id/btn3" android:text="3"/>
</TableRow>
<TableRow>
<Button android:id="@+id/btn4" android:text="4"/>
<Button android:id="@+id/btn5" android:text="5"/>
<Button android:id="@+id/btn6" android:text="6"/>
</TableRow>
<TableRow>
<Button android:id="@+id/btn7" android:text="7"/>
<Button android:id="@+id/btn8" android:text="8"/>
<Button android:id="@+id/btn9" android:text="9"/>
</TableRow>
<TableRow>
<Button android:id="@+id/btn0" android:text="0"/>
<Button android:id="@+id/btnSubmit" android:text="Submit"/>
<Button android:id="@+id/btnClear" android:text="Clear"/>
</TableRow>
<TableRow>
<TextView
android:id="@+id/txtResult"
android:text="Clicked Numbers:"
android:textSize="18sp" />
</TableRow>
</TableLayout>

✅ 2. Java Code (MainActivity.java)


package com.example.simpleinput;

import android.os.Bundle;
import android.view.View;
import android.widget.*;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

String number = "";


TextView txtResult;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtResult = findViewById(R.id.txtResult);

int[] ids = { R.id.btn0, R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4,


R.id.btn5, R.id.btn6, R.id.btn7, R.id.btn8, R.id.btn9
};

View.OnClickListener listener = new View.OnClickListener() {


@Override
public void onClick(View v) {
Button b = (Button) v;
number += b.getText().toString();
}
};

for (int id : ids) {


findViewById(id).setOnClickListener(listener);
}

findViewById(R.id.btnSubmit).setOnClickListener(v ->
txtResult.setText("Clicked Numbers: " + number)
);

findViewById(R.id.btnClear).setOnClickListener(v -> {
number = "";
txtResult.setText("Clicked Numbers:");
});
}
}

This version is made as easy as possible for learning. Would you like me to also explain how it
works step by step?

 Explain property animation method to animate the properties of view object with example

Sure! Here's a very simple explanation with example:

✅ What is Property Animation?

It is used to change properties of a view like:

 alpha (transparency)
 rotation
 x, y position
 scale
✅ How to Use:
ObjectAnimator anim = ObjectAnimator.ofFloat(view, "property", start, end);
anim.setDuration(1000); // time in milliseconds
anim.start();

✅ Simple Example: Rotate a Button


Button btn = findViewById(R.id.myButton);

ObjectAnimator anim = ObjectAnimator.ofFloat(btn, "rotation", 0f, 360f);


anim.setDuration(1000); // rotate in 1 second
anim.start();

Let me know if you want example to move, fade, or zoom a view.

 Develop an android application to show current location of an user’s car.

Sure! Here's the simplest answer to show the user's car (current location) on a map.

✅ 1. Add Permissions in AndroidManifest.xml:


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

✅ 2. Simple Layout (activity_main.xml):


<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

✅ 3. Java Code (MainActivity.java):


import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;

public class MainActivity extends FragmentActivity implements


OnMapReadyCallback {

GoogleMap map;
FusedLocationProviderClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

client = LocationServices.getFusedLocationProviderClient(this);
SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
map = googleMap;

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}

map.setMyLocationEnabled(true);

client.getLastLocation().addOnSuccessListener(location -> {
if (location != null) {
LatLng carLocation = new LatLng(location.getLatitude(),
location.getLongitude());
map.addMarker(new
MarkerOptions().position(carLocation).title("My Car"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(carLocation,
16));
}
});
}
}

✅ This will show a marker on Google Map at your current (car) location.
Sure! Here's the full and simple XML layout to show Google Map in your app.

✅ activity_main.xml (Simple Map Layout)


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Google Map Fragment -->


<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

This will simply show the Google Map in full screen.


Make sure you also have a Google Maps API key added in your AndroidManifest.xml.

Would you like me to give that line too?

 Design a employee registration form using UI component.

No problem! Here's the full employee registration form XML with the necessary UI
components. No Java code is needed for the UI layout part.

✅ Employee Registration Form XML Layout (activity_main.xml)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- Employee Name -->


<EditText
android:id="@+id/edtName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Name"
android:inputType="textPersonName" />

<!-- Employee Email -->


<EditText
android:id="@+id/edtEmail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Email"
android:inputType="textEmailAddress" />

<!-- Employee Phone -->


<EditText
android:id="@+id/edtPhone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Phone Number"
android:inputType="phone" />

<!-- Employee Department -->


<Spinner
android:id="@+id/spinnerDept"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<!-- Submit Button -->


<Button
android:id="@+id/btnSubmit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Submit" />

</LinearLayout>

✅ Explanation:

 EditText: For Name, Email, and Phone input.


 Spinner: Dropdown for selecting the department.
 Button: Submit button to submit the form.

This is the UI layout for the Employee Registration form. Let me know if you'd like help
handling form submission or any further features!

 Write a program to display a rectangular progress bar

Sure! Here's a simple example of how to create a rectangular progress bar in Android.

✅ XML Layout (activity_main.xml)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
android:gravity="center">

<!-- Progress Bar -->


<ProgressBar
android:id="@+id/progressBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"

/>

</LinearLayout>

✅ Explanation:

 ProgressBar: A horizontal rectangular progress bar with a max value of 100 and initial
progress set to 50.
 indeterminate="false": This makes the progress bar show the actual progress.
 max="100": The maximum value for the progress bar.
 progress="50": The initial progress of the bar (50%).

You can update the progress of the bar in Java like this:
ProgressBar progressBar = findViewById(R.id.progressBar);
progressBar.setProgress(70); // Set progress to 70

This is a very simple rectangular progress bar. You can change the progress dynamically
based on your needs.

 Develop a program to implement : i) List view of 5 items ii) iii) Grid view of 4 × 4 items Image
view.

Here’s a simple Android program that implements:

1. ListView with 5 items.


2. GridView with 4x4 items (16 items).
3. ImageView to display images.

1. ListView with 5 Items:

XML Layout (activity_main.xml):


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- ListView -->


<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

<!-- GridView -->


<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:gravity="center"
android:numColumns="4"

/>

<!-- ImageView -->


<ImageView
android:id="@+id/imageView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="20dp"
android:src="@drawable/ic_launcher_foreground"
android:layout_gravity="center" />

</LinearLayout>

2. Java Code (MainActivity.java):


package com.example.listgridimageview;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.GridView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// ListView with 5 items


ListView listView = findViewById(R.id.listView);
String[] listItems = {"Item 1", "Item 2", "Item 3", "Item 4", "Item
5"};
ArrayAdapter<String> listAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(listAdapter);

// GridView with 4x4 items


GridView gridView = findViewById(R.id.gridView);
String[] gridItems = new String[16];
for (int i = 0; i < 16; i++) {
gridItems[i] = "Item " + (i + 1);
}
ArrayAdapter<String> gridAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, gridItems);
gridView.setAdapter(gridAdapter);

// ImageView interaction (You can set different images based on


GridView or ListView click)
ImageView imageView = findViewById(R.id.imageView);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int
position, long id) {

imageView.setImageResource(R.drawable.ic_launcher_foreground); // Change
image when clicked
}
});
}
}

3. Explanation:

1. ListView:
o Displays 5 items using an ArrayAdapter.
o Items: "Item 1", "Item 2", "Item 3", "Item 4", and "Item 5".
2. GridView:
o Displays 16 items in a 4x4 grid (4 columns and 4 rows).
o Items: "Item 1" to "Item 16".
o The grid layout is controlled by the numColumns attribute.
3. ImageView:
o Displays an image (ic_launcher_foreground by default).
o When an item in the GridView is clicked, it will change the image displayed in
the ImageView.

4. Images:

Make sure you have a sample image (like ic_launcher_foreground) in your res/drawable
folder. You can replace it with any image you want.
This is a simple program that shows a ListView, GridView, and ImageView. Let me know if
you need any additional modifications or explanations!

 Write a program to find the direction from user’s current location to MSBTE, Bandra. (Write only
.Java and manifest file)

Here’s a simple program that shows the user’s current location and a marker for MSBTE,
Bandra using Google Maps.

1. Manifest File (AndroidManifest.xml)


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.directions">

<!-- Permissions -->


<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"
/>

<!-- Google Maps API Key -->


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar">

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY_HERE" />

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

</manifest>

 Replace "YOUR_API_KEY_HERE" with your Google Maps API Key.

2. MainActivity.java
package com.example.directions;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.tasks.OnSuccessListener;

public class MainActivity extends AppCompatActivity implements


OnMapReadyCallback {

private GoogleMap mMap;


private FusedLocationProviderClient fusedLocationClient;
private static final double MSBTE_LAT = 19.0400;
private static final double MSBTE_LNG = 72.8238;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

fusedLocationClient =
LocationServices.getFusedLocationProviderClient(this);

MapFragment mapFragment = (MapFragment)


getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new
String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
return;
}

fusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
LatLng userLocation = new
LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new
MarkerOptions().position(userLocation).title("Your Location"));

mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 14));

LatLng msbteLocation = new LatLng(MSBTE_LAT,


MSBTE_LNG);
mMap.addMarker(new
MarkerOptions().position(msbteLocation).title("MSBTE, Bandra"));
}
}
});
}
}

3. Explanation:

 Permissions: Requests permission to access location.


 Google Maps: Displays the map and shows markers for both the user's location and
MSBTE, Bandra.
 FusedLocationProviderClient: Retrieves the user’s current location.
 Markers: Adds markers for the current location and MSBTE location.

This is a simple solution showing the user's location and MSBTE on Google Maps.

 Develop a simple calculator using relative layout.

Here’s how you can develop a simple calculator app using RelativeLayout in Android:

Step 1: Create a New Android Project

1. Open Android Studio and create a new project.


2. Choose "Empty Activity" and click "Finish".

Step 2: Modify the activity_main.xml Layout

This layout will use RelativeLayout to position buttons and the text view.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- TextView to display result -->


<TextView
android:id="@+id/result"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textSize="48sp"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:textAlignment="textEnd" />

<!-- Buttons for calculator -->


<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:layout_below="@id/result"
android:layout_alignParentStart="true"
android:layout_marginTop="20dp" />

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="2"
android:layout_toEndOf="@id/button1"
android:layout_alignBaseline="@id/button1"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="3"
android:layout_toEndOf="@id/button2"
android:layout_alignBaseline="@id/button2"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="4"
android:layout_below="@id/button1"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />

<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="5"
android:layout_toEndOf="@id/button4"
android:layout_alignBaseline="@id/button4"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="6"
android:layout_toEndOf="@id/button5"
android:layout_alignBaseline="@id/button5"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="7"
android:layout_below="@id/button4"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />

<Button
android:id="@+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8"
android:layout_toEndOf="@id/button7"
android:layout_alignBaseline="@id/button7"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:layout_toEndOf="@id/button8"
android:layout_alignBaseline="@id/button8"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/button0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_below="@id/button7"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />

<Button
android:id="@+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="+"
android:layout_toEndOf="@id/button0"
android:layout_alignBaseline="@id/button0"
android:layout_marginStart="10dp" />

<Button
android:id="@+id/buttonEquals"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="="
android:layout_below="@id/button0"
android:layout_alignParentStart="true"
android:layout_marginTop="10dp" />

<Button
android:id="@+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="C"
android:layout_toEndOf="@id/buttonEquals"
android:layout_alignBaseline="@id/buttonEquals"
android:layout_marginStart="10dp" />

</RelativeLayout>

Step 3: Implement the Logic in MainActivity.java

Now, let's write the logic for handling the button clicks and performing calculations.

package com.example.simplecalculator;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private TextView result;


private String currentInput = "";
private double firstOperand = 0;
private String operator = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

result = findViewById(R.id.result);

// Number buttons
Button button1 = findViewById(R.id.button1);
Button button2 = findViewById(R.id.button2);
Button button3 = findViewById(R.id.button3);
Button button4 = findViewById(R.id.button4);
Button button5 = findViewById(R.id.button5);
Button button6 = findViewById(R.id.button6);
Button button7 = findViewById(R.id.button7);
Button button8 = findViewById(R.id.button8);
Button button9 = findViewById(R.id.button9);
Button button0 = findViewById(R.id.button0);

// Operator buttons
Button buttonAdd = findViewById(R.id.buttonAdd);

// Other buttons
Button buttonEquals = findViewById(R.id.buttonEquals);
Button buttonClear = findViewById(R.id.buttonClear);

// Setting onClickListeners for number buttons


button1.setOnClickListener(v -> appendToInput("1"));
button2.setOnClickListener(v -> appendToInput("2"));
button3.setOnClickListener(v -> appendToInput("3"));
button4.setOnClickListener(v -> appendToInput("4"));
button5.setOnClickListener(v -> appendToInput("5"));
button6.setOnClickListener(v -> appendToInput("6"));
button7.setOnClickListener(v -> appendToInput("7"));
button8.setOnClickListener(v -> appendToInput("8"));
button9.setOnClickListener(v -> appendToInput("9"));
button0.setOnClickListener(v -> appendToInput("0"));

// Setting onClickListener for operator buttons


buttonAdd.setOnClickListener(v -> setOperator("+"));

// Equals button logic


buttonEquals.setOnClickListener(v -> calculateResult());

// Clear button logic


buttonClear.setOnClickListener(v -> clear());
}

private void appendToInput(String value) {


currentInput += value;
result.setText(currentInput);
}

private void setOperator(String operator) {


if (!currentInput.isEmpty()) {
firstOperand = Double.parseDouble(currentInput);
this.operator = operator;
currentInput = "";
}
}

private void calculateResult() {


if (!currentInput.isEmpty()) {
double secondOperand = Double.parseDouble(currentInput);
double resultValue = 0;

switch (operator) {
case "+":
resultValue = firstOperand + secondOperand;
break;
// You can add more operations like -, *, / here
}

result.setText(String.valueOf(resultValue));
currentInput = String.valueOf(resultValue); // For continued
calculation
}
}

private void clear() {


currentInput = "";
result.setText("0");
}
}

 Develop a program to add “Hello World” marker at (10,10) co-ordinates. Write only . java file.

Here's a simpler version of how to add "Hello World" at coordinates (10,10) in an Android app
using a custom view:

Step 1: Create a New Android Project

1. Open Android Studio and create a new project.


2. Choose "Empty Activity" and click "Finish".

Step 2: Modify activity_main.xml

In your activity_main.xml, add a custom view:

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Custom view that will draw the text -->


<com.example.helloworldapp.HelloWorldView
android:id="@+id/helloWorldView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>

Step 3: Create a Custom View (HelloWorldView.java)

Create a new Java class HelloWorldView.java:

package com.example.helloworldapp;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Color;
import android.view.View;

public class HelloWorldView extends View {

public HelloWorldView(Context context) {


super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);

// Create a paint object to style the text


Paint paint = new Paint();
paint.setColor(Color.BLACK); // Set text color to black
paint.setTextSize(50); // Set text size

// Draw "Hello World" at coordinates (10, 10)


canvas.drawText("Hello World", 10, 10, paint);
}
}

Step 4: Run the App

1. In the HelloWorldView, we override the onDraw() method to draw "Hello World" at


position (10,10).
2. The text color is set to black, and the text size is set to 50 pixels.

When you run the app, you will see the text "Hello World" displayed at coordinates (10, 10) on
the screen.

This is the simplest version of what you asked for!

 Write an xml file to create login page using Table Layout.

Step 1: Create activity_main.xml


<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TableLayout
android:id="@+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:padding="16dp"
android:stretchColumns="1">

<!-- Row for Username -->


<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Username:"
android:textSize="16sp"
android:paddingEnd="8dp" />
<EditText
android:id="@+id/username"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter Username"
android:inputType="text" />
</TableRow>

<!-- Row for Password -->


<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password:"
android:textSize="16sp"
android:paddingEnd="8dp" />
<EditText
android:id="@+id/password"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Enter Password"
android:inputType="textPassword" />
</TableRow>

<!-- Row for Login Button -->


<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/loginButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:background="@color/colorPrimary"
android:textColor="#FFFFFF" />
</TableRow>

<!-- Row for Sign Up Text -->


<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Don't have an account?"
android:textSize="14sp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sign Up"
android:textSize="14sp"
android:textColor="#007BFF"
android:clickable="true"
android:focusable="true"
android:layout_marginStart="8dp" />
</TableRow>
</TableLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

 Develop an application to display analog Time Picker. Also display the


selected time.

To develop an application that displays an analog time picker and shows the selected time, you
can use Android's TimePicker widget. Below is a simple example to achieve this using
TimePickerDialog to select the time and display it.

Step 1: Modify activity_main.xml

In the XML layout, we'll use a TimePicker widget and a TextView to show the selected time.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- Button to show the TimePicker -->


<Button
android:id="@+id/timePickerButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pick Time"
android:layout_centerHorizontal="true" />

<!-- TextView to display the selected time -->


<TextView
android:id="@+id/selectedTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Time: 00:00"
android:textSize="18sp"
android:layout_below="@id/timePickerButton"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true" />

</RelativeLayout>

Step 2: Modify MainActivity.java


Now, in MainActivity.java, we'll set up the TimePickerDialog to show the analog time
picker and display the selected time.

package com.example.analogtimepicker;

import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

private TextView selectedTime;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

selectedTime = findViewById(R.id.selectedTime);
Button timePickerButton = findViewById(R.id.timePickerButton);

timePickerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Get the current time to set the default values in the
TimePickerDialog
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

// Create a TimePickerDialog
TimePickerDialog timePickerDialog = new TimePickerDialog(
MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int
hourOfDay, int minute) {
// Display the selected time in the TextView
selectedTime.setText("Selected Time: " +
hourOfDay + ":" + String.format("%02d", minute));
}
},
hour, minute, true // true for 24-hour format, false
for 12-hour format
);
timePickerDialog.show();
}
});
}
}
Explanation:

1. XML Layout:
o We have a Button that triggers the TimePickerDialog.
o We have a TextView to display the selected time.
2. MainActivity:
o When the "Pick Time" button is clicked, a TimePickerDialog is shown with the
current time as the default.
o The OnTimeSetListener listens for the user selecting a time and updates the
TextView with the selected time in the format HH:MM.
o The true parameter in the TimePickerDialog constructor specifies using a 24-
hour clock. If you prefer a 12-hour format, use false instead.

Step 3: Run the Application

1. When you run the app, you will see a button to "Pick Time."
2. Upon clicking it, an analog time picker will appear where the user can select the time.
3. After selecting the time, the TextView below the button will display the selected time in
the format HH:MM.

This is a simple and easy-to-understand way to implement an analog time picker and display the
selected time in Android. Let me know if you need any additional help!

 Develop a program to perform addition, subtraction, division,


multiplication of two numbers and display the result. (Use appropriate
UI controls)

Here's a simple program that performs basic arithmetic operations (addition, subtraction,
multiplication, and division) of two numbers and displays the result. The program uses Android's
EditText for user input, Button for operations, and a TextView to display the result.

Step 1: Modify activity_main.xml

In the XML layout, we will use EditText to input two numbers, Button for each operation, and
a TextView to display the result.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">

<!-- EditText for First Number -->


<EditText
android:id="@+id/firstNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter First Number"
android:inputType="numberDecimal" />

<!-- EditText for Second Number -->


<EditText
android:id="@+id/secondNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Second Number"
android:inputType="numberDecimal"
android:layout_below="@id/firstNumber"
android:layout_marginTop="10dp" />

<!-- Buttons for operations -->


<Button
android:id="@+id/addButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add"
android:layout_below="@id/secondNumber"
android:layout_marginTop="20dp" />

<Button
android:id="@+id/subtractButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Subtract"
android:layout_below="@id/addButton"
android:layout_marginTop="10dp" />

<Button
android:id="@+id/multiplyButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Multiply"
android:layout_below="@id/subtractButton"
android:layout_marginTop="10dp" />

<Button
android:id="@+id/divideButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Divide"
android:layout_below="@id/multiplyButton"
android:layout_marginTop="10dp" />

<!-- TextView to display result -->


<TextView
android:id="@+id/resultText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Result: "
android:textSize="18sp"
android:layout_below="@id/divideButton"
android:layout_marginTop="20dp"
android:textColor="#000000" />
</RelativeLayout>
Step 2: Modify MainActivity.java

In MainActivity.java, we will implement the logic to perform the arithmetic operations and
display the result.

package com.example.simplecalculator;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private EditText firstNumber, secondNumber;


private TextView resultText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Initialize the UI elements


firstNumber = findViewById(R.id.firstNumber);
secondNumber = findViewById(R.id.secondNumber);
resultText = findViewById(R.id.resultText);

// Add button listener


Button addButton = findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation("add");
}
});

// Subtract button listener


Button subtractButton = findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation("subtract");
}
});

// Multiply button listener


Button multiplyButton = findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation("multiply");
}
});
// Divide button listener
Button divideButton = findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
performOperation("divide");
}
});
}

private void performOperation(String operation) {


// Get values from EditText fields
String num1 = firstNumber.getText().toString();
String num2 = secondNumber.getText().toString();

// Check if both fields are filled


if (!num1.isEmpty() && !num2.isEmpty()) {
double number1 = Double.parseDouble(num1);
double number2 = Double.parseDouble(num2);
double result = 0;

switch (operation) {
case "add":
result = number1 + number2;
break;
case "subtract":
result = number1 - number2;
break;
case "multiply":
result = number1 * number2;
break;
case "divide":
if (number2 != 0) {
result = number1 / number2;
} else {
resultText.setText("Error: Cannot divide by zero");
return;
}
break;
}

// Display the result


resultText.setText("Result: " + result);
} else {
resultText.setText("Please enter valid numbers.");
}
}
}

Explanation:

1. XML Layout:
o EditText: For entering the first and second numbers.
o Button: For performing the arithmetic operations (add, subtract, multiply,
divide).
o TextView: To display the result.
2. MainActivity:
o The onCreate method initializes the views and sets OnClickListener for each
button.
o The performOperation method is called when any operation button is clicked. It
retrieves the numbers from the EditText fields, performs the selected operation,
and displays the result in the TextView.
o We check for division by zero to avoid a crash.

Step 3: Run the Application

1. Open the app on an Android device or emulator.


2. Enter two numbers in the input fields.
3. Click on any of the operation buttons (Add, Subtract, Multiply, Divide).
4. The result will be displayed below the buttons.

This is a simple and easy-to-understand way to implement a calculator app with basic arithmetic
operations. Let me know if you need any further assistance!

 Develop an application to display a Google Map. (Write JAVA and


Manifest file)

Here's a simplified version of how to display a Google Map in your Android app.

Step 1: Add Google Maps API Key

1. Get your Google Maps API key from Google Cloud Console.
2. Add the API key to res/values/google_maps_api.xml:

<resources>
<string name="google_maps_key">YOUR_API_KEY</string>
</resources>

Step 2: Update AndroidManifest.xml

Add the following permissions and metadata for the API key:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mapexample">

<uses-permission android:name="android.permission.INTERNET" />


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"
/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.DayNight">

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/google_maps_key" />

<activity
android:name=".MapsActivity"
android:label="Google Maps"
android:theme="@style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Step 3: Create MapsActivity.java

This Java file will set up the Google Map.

package com.example.mapexample;

import android.os.Bundle;
import androidx.fragment.app.FragmentActivity;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements


OnMapReadyCallback {

private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

// Set up map fragment


SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;

// Add a marker and move the camera to Sydney


LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in
Sydney"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
}

Step 4: Create Layout for MapsActivity

In res/layout/activity_maps.xml, display the map using SupportMapFragment:

<?xml version="1.0" encoding="utf-8"?>


<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.SupportMapFragment"/>

Step 5: Add Dependencies in build.gradle

In your app's build.gradle, add the Maps SDK dependency:

dependencies {
implementation 'com.google.android.gms:play-services-maps:17.0.0'
}

Step 6: Run the Application

Once you’ve set everything up:

1. Make sure you have an internet connection.


2. Build and run your app. You should see a Google Map with a marker placed in Sydney.

This setup will get a basic map running with a marker. Let me know if you need further
clarification!

 Develop a program to TURN ON and OFF bluetooth. Write .java file and
permission tags

Here is a simple Android app to turn Bluetooth ON and OFF with minimal code.

Step 1: Add Bluetooth Permissions to AndroidManifest.xml

In your AndroidManifest.xml, add the necessary Bluetooth permissions:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothapp">

<!-- Bluetooth permissions -->


<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.DayNight">

<activity
android:name=".MainActivity"
android:label="Bluetooth Control"
android:theme="@style/Theme.AppCompat.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Step 2: Create MainActivity.java

This Java file contains the logic to turn Bluetooth ON and OFF.

package com.example.bluetoothapp;

import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private BluetoothAdapter bluetoothAdapter;


private Button btnEnableBluetooth, btnDisableBluetooth;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get BluetoothAdapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

// Check if Bluetooth is supported on the device


if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported",
Toast.LENGTH_SHORT).show();
finish(); // Close the app if Bluetooth is not supported
}

// Find buttons by their IDs


btnEnableBluetooth = findViewById(R.id.btnEnableBluetooth);
btnDisableBluetooth = findViewById(R.id.btnDisableBluetooth);

// Enable Bluetooth
btnEnableBluetooth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!bluetoothAdapter.isEnabled()) {
bluetoothAdapter.enable();
Toast.makeText(MainActivity.this, "Bluetooth ON",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bluetooth is already
ON", Toast.LENGTH_SHORT).show();
}
}
});

// Disable Bluetooth
btnDisableBluetooth.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(MainActivity.this, "Bluetooth OFF",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "Bluetooth is already
OFF", Toast.LENGTH_SHORT).show();
}
}
});
}
}

Step 3: Create activity_main.xml Layout

Design a simple layout with two buttons for turning Bluetooth ON and OFF.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- Button to enable Bluetooth -->


<Button
android:id="@+id/btnEnableBluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn ON Bluetooth"
android:layout_centerHorizontal="true" />

<!-- Button to disable Bluetooth -->


<Button
android:id="@+id/btnDisableBluetooth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Turn OFF Bluetooth"
android:layout_below="@id/btnEnableBluetooth"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
</RelativeLayout>

Explanation:

1. Bluetooth Permissions: We need BLUETOOTH, BLUETOOTH_ADMIN, and


ACCESS_FINE_LOCATION permissions to control Bluetooth functionality.
2. BluetoothAdapter: This is used to check the Bluetooth state and to enable/disable
Bluetooth.
3. Turning Bluetooth ON/OFF:
o Turn ON Bluetooth: If Bluetooth is off, it will be turned on using
bluetoothAdapter.enable().
o Turn OFF Bluetooth: If Bluetooth is on, it will be turned off using
bluetoothAdapter.disable().

Step 4: Run the App

 Run this app on a physical Android device (since Bluetooth doesn't work on emulators).
 The app will display two buttons:
o Turn ON Bluetooth: Turns Bluetooth on if it is off.
o Turn OFF Bluetooth: Turns Bluetooth off if it is on.

That's it! This is the simplest way to control Bluetooth in an Android app. Let me know if you
need more help!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy