List Paired Devices in Android Studio
Syntax
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
List<String> deviceList = new ArrayList<String>();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceList.add(device.getName() + "\n" + device.getAddress());
}
}
Example
private void listPairedDevices() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
List<String> deviceList = new ArrayList<String>();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
deviceList.add(device.getName() + "\n" + device.getAddress());
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, deviceList);
ListView listView = (ListView) findViewById(R.id.listViewPairedDevices);
listView.setAdapter(adapter);
}
Output
The above example code will display all the paired devices with the device name and address in a listView.
Explanation
This code generates a list of paired Bluetooth devices and displays them on an Android application using a ListView.
The BluetoothAdapter
class provides access to the Bluetooth functionality of the Android device. The getDefaultAdapter()
method returns a reference to the local Bluetooth adapter. The getBondedDevices()
method returns a set of paired Bluetooth devices. Each BluetoothDevice object contains information on the paired device, such as name and address.
The code contains a for loop which iterates through the paired devices and adds their name and address to a list. This list is then passed to an ArrayAdapter
which converts the list to a ListView
display.
Use
This code can be used in Android applications that require Bluetooth functionality. It can be used to display a list of paired devices for the user to select.
Important Points
- This code will only display paired devices.
- To pair a new device, use the
startActivityForResult()
method to invoke the pairing process. - The Bluetooth permission must be added to the AndroidManifest.xml file.
Summary
The listPairedDevices() method in Android Studio generates a list of paired Bluetooth devices and displays them on a ListView in an Android application. It uses the BluetoothAdapter and BluetoothDevice classes to access Bluetooth functionality and create the list of paired devices.