Android available bluetooth devices

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 );
>
>
>
>);
>
>

Читайте также:  Прошивка usb bluetooth адаптера

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.

Android Bluetooth List Paired Devices Example Result

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 scan for available bluetooth devices in range in android?

I need to get a list of available bluetooth devices in the area using google android 2.1. Thing is, i don’t just need a list of those devices, i need some unique id for each device found and i need an indicator, how «good» the signal is received (like the «level» in android.wifi.ScanResult). How do i do that?

4 Answers 4

mBluetoothAdapter.startDiscovery(); mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); //Finding devices if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Get the BluetoothDevice object from the Intent BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); // Add the name and address to an array adapter to show in a ListView mArrayAdapter.add(device.getName() + "\n" + device.getAddress()); >> >; IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); 

@SaharMillis: What about it doesn’t work for you? It works fine, but your other device needs to be discoverable, not just with bluetooth on.

how does this work if there are multiple bluetooth devices found in the range. Does the receiver get triggered multiple times?

@Zapnologica the BroadcastReceiver gets notified once per device; therefore one has to keep them in an ArrayList field, or alike. while there are two? further actions available, beside the BluetoothDevice.ACTION_FOUND , of which one indicates the scan being complete.

Call method bluetoothScanning, context is required

void bluetoothScanning() < IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); final BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.startDiscovery(); >// Create a BroadcastReceiver for ACTION_FOUND. private final BroadcastReceiver mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Discovery has found a device. Get the BluetoothDevice // object and its info from the Intent. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address Log.i("Device Name: " , "device " + deviceName); Log.i("deviceHardwareAddress " , "hard" + deviceHardwareAddress); >> >; 

Name: LE-Bose Revolve+ SoundLink deviceHardwareAddress: MAC .

Читайте также:  Флешка определяется блютуз нет

@GregD this is my exact problem. it was working fine, but then it started to show only mac addresses and not names. can’t figure out why

This code uses BeaconManager, it continuously scans for new Bluetooth devices and returns a Beacons List object which you can use to get what ever information you need.

Make sure you import BeaconManager

private BeaconManager beaconManager; //In onCreate method beaconManager = BeaconManager.getInstanceForApplication(this); beaconManager.getBeaconParsers().add(new BeaconParser(). setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24")); //use these out of the onCreate method public void onScanStart(View view) < stopScanButton.setEnabled(true); scanningButton.setEnabled(false); beaconManager.bind(this); >@Override public void onBeaconServiceConnect() < beaconManager.removeAllRangeNotifiers(); beaconManager.addRangeNotifier(new RangeNotifier() < @Override public void didRangeBeaconsInRegion(Collectionbeacons, Region region) < for (Beacon b : beacons) < System.out.println(String.format("%s: %f: %d", b.getBluetoothName(), b.getDistance(), b.getRssi())); >); try < //Tells the BeaconService to start looking for beacons that match the passed. beaconManager.startRangingBeaconsInRegion(new Region("myRangingUniqueId", null, null, null)); >catch (RemoteException e) < Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); >> 

Let me know if that works for you!

To able to discovery devices by bluetooth. Make sure you

  • Enable bluetooth
  • Allow required permissions for your application (some permission is runtime permission). You can check here https://developer.android.com/about/versions/12/features/bluetooth-permissions

AndroidManifest.xml

MainActivity

class MainActivity : AppCompatActivity() < private var bluetoothAdapter: BluetoothAdapter? = null private val bluetoothReceiver: BroadcastReceiver = object : BroadcastReceiver() < override fun onReceive(context: Context?, intent: Intent) < val action = intent.action Log.i("TAG", "onReceive $action") if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) < Log.i("TAG", "Discovery finished, hide loading") >else if (BluetoothDevice.ACTION_FOUND == action) < val device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE) Log.i("TAG", "Device Name: " + (device?.name ?: "")) Log.i("TAG", "Device Address:" + (device?.address ?: "")) > > > override fun onCreate(savedInstanceState: Bundle?) < . findViewById(R.id.button_start_discovery).setOnClickListener < if (bluetoothAdapter == null) < initBluetoothDiscovery() >startDiscovery() > > private fun initBluetoothDiscovery() < val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager bluetoothAdapter = bluetoothManager.adapter val intentFilter = IntentFilter().apply < addAction(BluetoothDevice.ACTION_FOUND) addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED) >registerReceiver(bluetoothReceiver, intentFilter) > private fun startDiscovery() < if (bluetoothAdapter?.isDiscovering == true) < Log.i("TAG", "cancel start discovery") bluetoothAdapter?.cancelDiscovery() >Log.i("TAG", "start discovery, show loading") bluetoothAdapter?.startDiscovery() > override fun onDestroy() < super.onDestroy() bluetoothAdapter?.cancelDiscovery(); unregisterReceiver(bluetoothReceiver); >> 

Источник

list connected bluetooth devices?

This works, but it’s more like polling. Is there a way to have a nice callback of when the list changes? Using BluetoothDevice.ACTION_ACL_CONNECTED, it’s not quite the same as it’s about pairing/bonding, and it’s not reliable either (doesn’t say when it finished bonding) .

As of API 14 (Ice Cream), Android has a some new BluetoothAdapter methods including:

public int getProfileConnectionState (int profile)

where profile is one of HEALTH, HEADSET, A2DP

Check response, if it’s not STATE_DISCONNECTED you know you have a live connection.

Here is code example that will work on any API device:

BluetoothAdapter mAdapter; /** * Check if a headset type device is currently connected. * * Always returns false prior to API 14 * * @return true if connected */ public boolean isVoiceConnected() < boolean retval = false; try < Method method = mAdapter.getClass().getMethod("getProfileConnectionState", int.class); // retval = mAdapter.getProfileConnectionState(android.bluetooth.BluetoothProfile.HEADSET) != android.bluetooth.BluetoothProfile.STATE_DISCONNECTED; retval = (Integer)method.invoke(mAdapter, 1) != 0; >catch (Exception exc) < // nothing to do >return retval; > 

final BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();

if (btAdapter != null && btAdapter.isEnabled()) // null means no Bluetooth!

If the Bluetooth is not turned out you can either use btAdapter.enable() which is not recommended in the documentation or ask the user to do it : Programmatically enabling bluetooth on Android

  • Fourth, you create a BluetoothProfile.ServiceListener which contains two callbacks triggered when a service is connected and disconnected :
final BluetoothProfile.ServiceListener listener = new BluetoothProfile.ServiceListener() < @Override public void onServiceConnected(int profile, BluetoothProfile proxy) < >@Override public void onServiceDisconnected(int profile) < >>; 

Now since you have to repeat the querying process for all available Bluetooth Profiles in the Android SDK (A2Dp, GATT, GATT_SERVER, Handset, Health, SAP) you should proceed as follow :

Читайте также:  Адаптер bluetooth выключен ubuntu

In onServiceConnected , place a condition that check what is the current profile so that we add the found devices into the correct collection and we use : proxy.getDevicesMatchingConnectionStates(states) to filter out unconnected devices:

And finally, the last thing to do is start the querying process :

btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.A2DP); btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT); // NOTE ! Requires SDK 18 ! btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.GATT_SERVER); // NOTE ! Requires SDK 18 ! btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEADSET); btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.HEALTH); // NOTE ! Requires SDK 14 ! btAdapter.getProfileProxy(yourContext, listener, BluetoothProfile.SAP); // NOTE ! Requires SDK 23 ! 

Источник

Obtaining a List of Available Bluetooth Devices on Android

In this question, @nhoxbypass provides this method for the purpose of adding found Bluetooth devices to a list:

private BroadcastReceiver myReceiver = new BroadcastReceiver() < @Override public void onReceive(Context context, Intent intent) < Message msg = Message.obtain(); String action = intent.getAction(); if(BluetoothDevice.ACTION_FOUND.equals(action))< //Found, add to a device list >> >; 

However, I do not understand how a reference to the found device can be obtained, how can this be done? I do not have permission to comment on the original question, so I have chosen to extend it here.

2 Answers 2

In order to receive information about each device discovered, your application must register a BroadcastReceiver for the ACTION_FOUND intent. The system broadcasts this intent for each device. The intent contains the extra fields EXTRA_DEVICE and EXTRA_CLASS, which in turn contain a BluetoothDevice and a BluetoothClass, respectively.

This sample code is included as well:

@Override protected void onCreate(Bundle savedInstanceState) < . // Register for broadcasts when a device is discovered. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); >// Create a BroadcastReceiver for ACTION_FOUND. private final BroadcastReceiver mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) < // Discovery has found a device. Get the BluetoothDevice // object and its info from the Intent. BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName(); String deviceHardwareAddress = device.getAddress(); // MAC address >> >; 

If you are working with Bluetooth on Android, I suggest to read that guide carefully. Then read it one more time 😉

Источник

Оцените статью
Adblock
detector