- Android bluetooth: Paired devices list
- 3 Answers 3
- Android + Pair devices via bluetooth programmatically
- Android Bluetooth List Paired Devices with Examples
- Android Bluetooth List Paired Devices
- Android List Bluetooth Paired Devices Example
- activity_main.xml
- MainActivity.java
- AndroidManifest.xml
- Output of Android Bluetooth List Paired Devices Example
- How to Display Bluetooth Paired Devices Programmatically in Android?
- Step by Step Implementation
Android bluetooth: Paired devices list
I have a bluetooth device with SPP profile and bluetooth version 2.1.
I have an app which connects to that device and communicates with it. The device uses «Just Works» pairing technique. I am facing a problem on certain phones like Samsung Galaxy tablet, Galaxy S. The problem is after the user exits from the app, I am closing the sockets and disconnecting from the device. After successful disconnection, it is observed that the device’s entry is removed from the paired devices list.
3 Answers 3
I haven’t worked with tablets, but I did write an app that used SPP for Android phones. What I found was that in order to get Bluetooth to be stable, I have to manually bond with the device I want to communicate with. We used the code below to initiated bonding from within the app, and it should preserve the bonding just as if you manually paired through the settings menu.
Here is the general flow: 1) Register a BroadcastReceiver to listen for BluetoothDevice.ACTION_BOND_STATE_CHANGED
2) After device discovery you should have a BluetoothDevice object.
3) Use reflection to call ‘createBond’ method on a BluetoothDeviceObject
3a) Wait for bond state change events before opening sockets
BluetoothDevice device = ; Method m = device.getClass().getMethod("createBond", (Class[])null); m.invoke(device, (Object[])null); int bondState = device.getBondState(); if (bondState == BluetoothDevice.BOND_NONE || bondState == BluetoothDevice.BOND_BONDING) < waitingForBonding = true; // Class variable used later in the broadcast receiver // Also. I have the whole bluetooth session running on a thread. This was a key point for me. If the bond state is not BOND_BONDED, I wait here. Then see the snippets below synchronized(this) < wait(); >>
4) Wait for the bond state to change from BOND_BONDING to BOND_BONDED
Inside a BroadcastReciever:
public void onReceive(Context context, Intent intent) < if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(intent.getAction())) < int prevBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1); int bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1); if (waitingForBonding) < if (prevBondState == BluetoothDevice.BOND_BONDING) < // check for both BONDED and NONE here because in some error cases the bonding fails and we need to fail gracefully. if (bondState == BluetoothDevice.BOND_BONDED || bondState == BluetoothDevice.BOND_NONE) < // safely notify your thread to continue >> > > >
5) Open sockets and communicate
You can also you the ‘removeBond’ method via reflection to remove your device from the pairing list.
Android + Pair devices via bluetooth programmatically
I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair. I want to know mistake in my code or any other way to do what i need.
package com.marakana; import java.util.Set; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; public class BluetoothDemo extends Activity < // Debugging private static final String TAG = "DeviceListActivity"; private static final boolean D = true; // Return Intent extra public static String EXTRA_DEVICE_ADDRESS = "device_address"; // Member fields private BluetoothAdapter mBtAdapter; private ArrayAdaptermPairedDevicesArrayAdapter; private ArrayAdapter mNewDevicesArrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.device_list); // Set result CANCELED incase the user backs out setResult(Activity.RESULT_CANCELED); // Initialize the button to perform device discovery Button scanButton = (Button) findViewById(R.id.button_scan); scanButton.setOnClickListener(new OnClickListener() < public void onClick(View v) < doDiscovery(); v.setVisibility(View.GONE); >>); // Initialize array adapters. One for already paired devices and // one for newly discovered devices mPairedDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); mNewDevicesArrayAdapter = new ArrayAdapter(this, R.layout.device_name); // Find and set up the ListView for paired devices ListView pairedListView = (ListView) findViewById(R.id.paired_devices); pairedListView.setAdapter(mPairedDevicesArrayAdapter); pairedListView.setOnItemClickListener(mDeviceClickListener); // Find and set up the ListView for newly discovered devices ListView newDevicesListView = (ListView) findViewById(R.id.new_devices); newDevicesListView.setAdapter(mNewDevicesArrayAdapter); newDevicesListView.setOnItemClickListener(mDeviceClickListener); // Register for broadcasts when a device is discovered IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, filter); // Register for broadcasts when discovery has finished filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); this.registerReceiver(mReceiver, filter); // Get the local Bluetooth adapter mBtAdapter = BluetoothAdapter.getDefaultAdapter(); // Get a set of currently paired devices Set pairedDevices = mBtAdapter.getBondedDevices(); // If there are paired devices, add each one to the ArrayAdapter if (pairedDevices.size() > 0) < findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE); for (BluetoothDevice device : pairedDevices) < mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> else < String noDevices = getResources().getText(R.string.none_paired).toString(); mPairedDevicesArrayAdapter.add(noDevices); >> @Override protected void onDestroy() < super.onDestroy(); // Make sure we're not doing discovery anymore if (mBtAdapter != null) < mBtAdapter.cancelDiscovery(); >// Unregister broadcast listeners this.unregisterReceiver(mReceiver); > /** * Start device discover with the BluetoothAdapter */ private void doDiscovery() < if (D) Log.d(TAG, "doDiscovery()"); // Indicate scanning in the title setProgressBarIndeterminateVisibility(true); setTitle(R.string.scanning); // Turn on sub-title for new devices findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE); // If we're already discovering, stop it if (mBtAdapter.isDiscovering()) < mBtAdapter.cancelDiscovery(); >// Request discover from BluetoothAdapter mBtAdapter.startDiscovery(); > // The on-click listener for all devices in the ListViews private OnItemClickListener mDeviceClickListener = new OnItemClickListener() < public void onItemClick(AdapterViewav, View v, int arg2, long arg3) < // Cancel discovery because it's costly and we're about to connect mBtAdapter.cancelDiscovery(); // Get the device MAC address, which is the last 17 chars in the View String info = ((TextView) v).getText().toString(); String address = info.substring(info.length() - 17); // Create the result Intent and include the MAC address Intent intent = new Intent(); intent.putExtra(EXTRA_DEVICE_ADDRESS, address); // Set result and finish this Activity setResult(Activity.RESULT_OK, intent); finish(); >>; // The BroadcastReceiver that listens for discovered devices and // changes the title when discovery is finished private final BroadcastReceiver mReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < String action = intent.getAction(); // When discovery finds a device if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // If it's already paired, skip it, because it's been listed already if (device.getBondState() != BluetoothDevice.BOND_BONDED) < mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >// When discovery is finished, change the Activity title > else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < setProgressBarIndeterminateVisibility(false); setTitle(R.string.select_device); if (mNewDevicesArrayAdapter.getCount() == 0) < String noDevices = getResources().getText(R.string.none_found).toString(); mNewDevicesArrayAdapter.add(noDevices); >> > >; >
Android Bluetooth List Paired Devices with Examples
In android, Bluetooth is a communication network protocol, which allows devices to connect wirelessly to exchange the data with other Bluetooth devices.
Generally, in android applications by using Bluetooth API’s we can implement Bluetooth functionalities, such as enable or disable a Bluetooth, searching for available Bluetooth devices, connecting with the devices and managing the data transfer between devices within the range.
In android, we can perform Bluetooth related activities by using BluetoothAdapter class in our applications. To know more about BluetoothAdapter, check this Android Bluetooth with Examples.
Android Bluetooth List Paired Devices
By using BluetoothAdapter method getBondedDevices(), we can get the Bluetooth paired devices list.
Following is the code snippet to get all paired devices with name and MAC address of each device.
// Get paired devices.
Set pairedDevices = bAdapter.getBondedDevices();
if (pairedDevices.size() > 0 ) // There are paired devices. Get the name and address of each paired device.
for (BluetoothDevice device : pairedDevices) String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
>
>
If you observe above code, we are getting the Bluetooth paired devices name and mac address by using BluetoothDevice object.
As we discussed in previous tutorial Android Bluetooth with Examples, we need to set Bluetooth permissions in our android manifest file like show below to use Bluetooth features in our android applications.
Following is the example of getting the list of available Bluetooth paired devices on button click in android applications.
Android List Bluetooth Paired Devices Example
Create a new android application using android studio and give names as BluetoothListPairedDevicesExample. In case if you are not aware of creating an app in android studio check this article Android Hello World App.
Once we create an application, open activity_main.xml file from \res\layout folder path and write the code like as shown below.
activity_main.xml
< LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android"
android :layout_width= «match_parent»
android :layout_height= «match_parent»
android :orientation= «vertical» >
< Button
android :layout_width= «wrap_content»
android :layout_height= «wrap_content»
android :id= «@+id/btnGet»
android :text= «Get Paired Devices»
android :layout_marginLeft= «130dp»
android :layout_marginTop= «200dp»/>
< ListView
android :id= «@+id/deviceList»
android :layout_width= «match_parent»
android :layout_height= «wrap_content» >
?>
Now open your main activity file MainActivity.java from \java\com.tutlane.bluetoothexample path and write the code like as shown below
MainActivity.java
package com.tutlane.bluetoothlistpaireddevicesexample;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.support.v7.app.AppCompatActivity;
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 java.util.ArrayList;
import java.util.Set;
public class MainActivity extends AppCompatActivity private ListView lstvw ;
private ArrayAdapter aAdapter ;
private BluetoothAdapter bAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
protected void onCreate(Bundle savedInstanceState) super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button btn = (Button)findViewById(R.id. btnGet );
btn.setOnClickListener( new View.OnClickListener() @Override
public void onClick(View v) if ( bAdapter == null ) Toast.makeText(getApplicationContext(), «Bluetooth Not Supported» ,Toast. LENGTH_SHORT ).show();
>
else Set pairedDevices = bAdapter .getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()> 0 ) for (BluetoothDevice device: pairedDevices) String devicename = device.getName();
String macAddress = device.getAddress();
list.add( «Name: » +devicename+ «MAC Address: » +macAddress);
>
lstvw = (ListView) findViewById(R.id. deviceList );
aAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout. simple_list_item_1 , list);
lstvw .setAdapter( aAdapter );
>
>
>
>);
>
>
If you observe above code, we are getting the Bluetooth paired devices name and mac address by using BluetoothDevice object.
As discussed, we need to set Bluetooth permissions in android manifest file (AndroidManifest.xml) to access Bluetooth features in android applications. Now open android manifest file (AndroidManifest.xml) and write the code like as shown below
AndroidManifest.xml
If you observe above code, we added required Bluetooth permissions in manifest file to access Bluetooth features in android applications.
Output of Android Bluetooth List Paired Devices Example
When we run the above program in the android studio we will get the result as shown below.
When we click on Get Paired Devices button, we will get list of paired Bluetooth devices in our android application.
This is how we can get Bluetooth paired devices list in android applications based on our requirements.
How to Display Bluetooth Paired Devices Programmatically in Android?
Bluetooth’s technology is a high-speed, low-powered wireless technology link designed to connect devices such as phones or other portable equipment. It has a specification (IEEE 802.15.1) for low-power radio communications to link computers, phones, and other network devices over a short distance in a wireless manner. Bluetooth signals cover distances, typically up to 10 meters or 30 feet. Bluetooth supports the waveband of 2.45 GHz and may support up to 721 kbps alongside three voice channels. This waveband has been put aside by international agreement to use Industrial, Scientific, and Medical devices (ISM).rd-compatible with 1.0 devices. Bluetooth is capable of connecting up to “eight devices” at a time. Every device offers a unique 48-bit address from the IEEE 802 standard. The Bluetooth specification defines and supports a variety of Bluetooth network connections. In this way, Bluetooth networking may be a remarkably flexible form of a wireless system for various short-range applications. Through this article, we want to share with you the implementation of an application that displays a list of Bluetooth Paired Devices along with their MAC IDs. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using both Java and Kotlin language.
Step by Step Implementation
To programmatically show a list of Bluetooth Paired devices against our device in Android, follow the following steps:
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the AndroidManifest.xml file
Go to the AndroidManifest.xml file and add these permissions required by the Bluetooth adapter: BLUETOOTH, BLUETOOTH_ADMIN, and ACCESS_COARSE_LOCATION.
Below is the complete code for the AndroidManifest.xml file.