Practical No : 24
Xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<!-- Empty space to push buttons to center -->
<Space
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<!-- Button group -->
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btnOn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn ON Bluetooth"
android:layout_marginBottom="8dp" />
<Button
android:id="@+id/btnVisible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Make Visible"
android:layout_marginBottom="8dp" />
<Button
android:id="@+id/btnList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="List Devices"
android:layout_marginBottom="8dp" />
<Button
android:id="@+id/btnOff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Turn OFF Bluetooth" />
</LinearLayout>
<!-- ListView at the bottom -->
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginTop="20dp" />
</LinearLayout>
Java code :
package com.example.pr24;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
ListView listView;
ArrayAdapter<String> adapter;
ArrayList<String> deviceList = new ArrayList<>();
private static final int REQUEST_PERMISSION = 1001;
private static final int REQUEST_ENABLE_BT = 1002;
private static final int REQUEST_DISCOVERABLE = 1003;
// Declare button variables
Button btnOn, btnOff, btnVisible, btnList;
@RequiresPermission(allOf = {Manifest.permission.BLUETOOTH_CONNECT, Manifest.permission.BLUETOOTH_SCAN})
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize buttons
btnOn = findViewById(R.id.btnOn);
btnOff = findViewById(R.id.btnOff);
btnVisible = findViewById(R.id.btnVisible);
btnList = findViewById(R.id.btnList);
listView = findViewById(R.id.listView);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, deviceList);
listView.setAdapter(adapter);
// Turn ON Bluetooth
btnOn.setOnClickListener(v -> {
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
} else if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} else {
Toast.makeText(this, "Bluetooth already ON", Toast.LENGTH_SHORT).show();
}
});
// Turn OFF Bluetooth
btnOff.setOnClickListener(v -> {
if (bluetoothAdapter != null && bluetoothAdapter.isEnabled()) {
bluetoothAdapter.disable();
Toast.makeText(this, "Bluetooth turned OFF", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Bluetooth already OFF", Toast.LENGTH_SHORT).show();
}
});
// Make Device Discoverable
btnVisible.setOnClickListener(v -> {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
if (bluetoothAdapter != null && !bluetoothAdapter.isDiscovering()) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); // 5 min
startActivityForResult(discoverableIntent, REQUEST_DISCOVERABLE);
}
});
// List Paired Devices
btnList.setOnClickListener(v -> {
listDevices();
});
// Runtime Permission (for Android 12+)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH_CONNECT}, REQUEST_PERMISSION);
}
}
}
private void listDevices() {
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
return;
}
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, "Turn on Bluetooth first", Toast.LENGTH_SHORT).show();
return;
}
deviceList.clear();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission required", Toast.LENGTH_SHORT).show();
return;
}
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceList.add(device.getName() + "\n" + device.getAddress());
}
} else {
deviceList.add("No paired devices found.");
}
adapter.notifyDataSetChanged();
}
// Handle permission result
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Bluetooth permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Bluetooth permission denied", Toast.LENGTH_SHORT).show();
}
}
}
}
Manifest code :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.pr24">
<!-- Required Bluetooth and Location Permissions -->
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
tools:targetApi="31">
<activity android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Output :