Bluetooth device list android

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 😉

Источник

Android bluetooth get connected devices

How can I get a list of all connected bluetooth devices for Android regardless of profile? Alternatively, I see that you can get all connected devices for a specific profile via BluetoothManager.getConnectedDevices. And I guess I could see which devices are connected by listening for connections/disconnections via ACTION_ACL_CONNECTED/ACTION_ACL_DISCONNECTED. seems error prone. But I’m wondering if there’s a simpler way to get the list of all connected bluetooth devices.

you’re right in that just listening to acl connected / disconnect is problematic because it can occur while your app is not running or listening for the broadcasts

3 Answers 3

To see a complete list, this is a 2-step operation:

To get a list of, and iterate, the currently paired devices:

Set pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices(); if (pairedDevices.size() > 0) < for (BluetoothDevice d: pairedDevices) < String deviceName = d.getName(); String macAddress = d.getAddress(); Log.i(LOGTAG, "paired device: " + deviceName + " at " + macAddress); // do what you need/want this these list items >> 

Discovery is a little bit more of a complex operation. To do this, you’ll need to tell the BluetoothAdapter to start scanning/discovering. As it finds things, it sends out Intents that you’ll need to receive with a BroadcastReceiver.

Читайте также:  Как изменить название bluetooth устройства

First, we’ll set up the receiver:

private void setupBluetoothReceiver() < BroadcastRecevier btReceiver = new BroadcastReciver() < @Override public void onReceive(Context context, Intent intent) < handleBtEvent(context, intent); >>; IntentFilter eventFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); // this is not strictly necessary, but you may wish // to know when the discovery cycle is done as well eventFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); myContext.registerReceiver(btReceiver, eventFilter); > private void handleBtEvent(Context context, Intent intent) < String action = intent.getAction(); Log.d(LOGTAG, "action received: " + action); if (BluetoothDevice.ACTION_FOUND.equals(action)) < BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); Log.i(LOGTAG, "found device: " + device.getName()); >else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) < Log.d(LOGTAG, "discovery complete"); >> 

Now all that is left is to tell the BluetoothAdapter to start scanning:

BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter(); // if already scanning . cancel if (btAdapter.isDiscovering()) < btAdapter.cancelDiscovery(); >btAdapter.startDiscovery(); 

Источник

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.

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.

Читайте также:  Блютуз наушники mi true wireless ebs basic 2

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

Источник

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