Find BLE devices
To find BLE devices, you use the startScan() method. This method takes a ScanCallback as a parameter. You must implement this callback, because that is how scan results are returned. Because scanning is battery-intensive, you should observe the following guidelines:
- As soon as you find the desired device, stop scanning.
- Never scan on a loop, and always set a time limit on your scan. A device that was previously available may have moved out of range, and continuing to scan drains the battery.
In the following example, the BLE app provides an activity ( DeviceScanActivity ) to scan for available Bluetooth LE devices and display them in a list to the user. The following snippet shows how to start and stop a scan:
Kotlin
private val bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner private var scanning = false private val handler = Handler() // Stops scanning after 10 seconds. private val SCAN_PERIOD: Long = 10000 private fun scanLeDevice() < if (!scanning) < // Stops scanning after a pre-defined scan period. handler.postDelayed(< scanning = false bluetoothLeScanner.stopScan(leScanCallback) >, SCAN_PERIOD) scanning = true bluetoothLeScanner.startScan(leScanCallback) > else < scanning = false bluetoothLeScanner.stopScan(leScanCallback) >>
Java
private BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); private boolean scanning; private Handler handler = new Handler(); // Stops scanning after 10 seconds. private static final long SCAN_PERIOD = 10000; private void scanLeDevice() < if (!scanning) < // Stops scanning after a predefined scan period. handler.postDelayed(new Runnable() < @Override public void run() < scanning = false; bluetoothLeScanner.stopScan(leScanCallback); >>, SCAN_PERIOD); scanning = true; bluetoothLeScanner.startScan(leScanCallback); > else < scanning = false; bluetoothLeScanner.stopScan(leScanCallback); >>
Note: The BluetoothLeScanner is only available from the BluetoothAdapter if Bluetooth is currently enabled on the device. If Bluetooth is not enabled, then getBluetoothLeScanner() returns null.
To scan for only specific types of peripherals, you can instead call startScan(List, ScanSettings, ScanCallback) , providing a list of ScanFilter objects that restrict the devices that the scan looks for and a ScanSettings object that specifies parameters about the scan.
The following code sample is an implementation of ScanCallback , which is the interface used to deliver BLE scan results. When results are found, they are added to a list adapter in the DeviceScanActivity to display to the user.
Kotlin
private val leDeviceListAdapter = LeDeviceListAdapter() // Device scan callback. private val leScanCallback: ScanCallback = object : ScanCallback() < override fun onScanResult(callbackType: Int, result: ScanResult) < super.onScanResult(callbackType, result) leDeviceListAdapter.addDevice(result.device) leDeviceListAdapter.notifyDataSetChanged() >>
Java
private LeDeviceListAdapter leDeviceListAdapter = new LeDeviceListAdapter(); // Device scan callback. private ScanCallback leScanCallback = new ScanCallback() < @Override public void onScanResult(int callbackType, ScanResult result) < super.onScanResult(callbackType, result); leDeviceListAdapter.addDevice(result.getDevice()); leDeviceListAdapter.notifyDataSetChanged(); >>;
Note: You can only scan for Bluetooth LE devices or scan for classic Bluetooth devices, as described in Bluetooth overview. You cannot scan for both Bluetooth LE and classic devices at the same time.
Content and code samples on this page are subject to the licenses described in the Content License. Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.
Last updated 2021-10-27 UTC.
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); >>
How to Find a Lost Bluetooth Device
Andy O’Donnell, MA, is a former freelance contributor to Lifewire and a senior security engineer who is active in internet and network security.
Lisa Mildon is a Lifewire writer and an IT professional with 30 years of experience. Her writing has appeared in Geekisphere and other publications.
- The Quick Guide to Webcams
- Keyboards & Mice
- Monitors
- Cards
- HDD & SSD
- Printers & Scanners
- Raspberry Pi
What to Know
- Make sure Bluetooth is on. Download and then open a Bluetooth scanner app and start scanning.
- When found, move around to measure the proximity of the device.
- If you lost Bluetooth headphones or another audio device, send some loud music to it using a music app.
When you set up a Bluetooth device on a PC or mobile device, you usually pair it to another device. For example, you can pair a Bluetooth device with a car audio system or wireless speaker. This pairing mechanism is critical to helping you find a lost Bluetooth device. Learn how to find a lost Bluetooth device using phones and tablets with iOS or Android.
Locating a Lost Bluetooth Device
As long as your headphones, earbuds, or another Bluetooth-enabled device has some battery life and was turned on when you lost it, the odds are good that you can find it using a smartphone and a Bluetooth scanning app. Several of these apps are available for both iOS and Android-based phones and tablets.
- Make sure Bluetooth is active on the phone. Your phone can’t pick up the signal from the lost Bluetooth device if the phone’s Bluetooth radio is off. On Android, access Quick Settings. If the Bluetooth icon is gray, tap it to turn it on. (You may have to swipe left to find Bluetooth.) It’s also easy to turn on Bluetooth on an iPhone in the Settings app.
When the item shows up on the list, try to locate it. If the signal strength drops (for example, goes from -200 dBm to -10 dBm), you’ve moved away from the device. If the signal strength improves (for example, goes from -10 dBm to -1 dBm), you’re getting warmer. Keep playing this game of Hot or Cold until you find the phone.
On most Android devices, to change the Bluetooth name, go to Settings > Connected Devices > Connection preferences > Bluetooth > Device name. To rename on iOS devices, go to Settings > Bluetooth > Choose connected Bluetooth accessory > Name.
First, make sure Bluetooth is turned on. Next, go to Settings > Connections > Bluetooth. Select the cogwheel next to the device you want to unpair > Unpair.
How to get the bluetooth devices as a list?
I am trying to get my bonded bluetooth devices but I can get it as a long string instead of list. This is my code:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set pairedDevices = mBluetoothAdapter.getBondedDevices(); ArrayList listview = new ArrayList(Arrays.asList(pairedDevices.toString())); setListAdapter(new ArrayAdapter(this, R.layout.list, listview));
I am getting something like this: [00:23:7F:1c, f0:09:f1:b4:b0] . And its all in one line. How can I change it to be in a list and not all in one line? Also, how can I get the friendly names of the devices and not these numbers? Thanks.
6 Answers 6
You should change your code as below:
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set pairedDevices = mBluetoothAdapter.getBondedDevices(); List s = new ArrayList(); for(BluetoothDevice bt : pairedDevices) s.add(bt.getName()); setListAdapter(new ArrayAdapter(this, R.layout.list, s));
yea. Thanks. only need to add that i changed List
have the same error after your update. did the same change i did before and it works now. this was the error it gave me befor my fix: The type List is not generic; it cannot be parameterized with arguments
The implementation for list item click listener totally depends on you. You may definitely extend AdapterView.OnItemClickListener to make Bluetooth connection to the device shown in list. Use listView.setOnItemClickListener to provide your custom click listener.
Find list of Nearby Bluetooth Devices:
Find Screenshot for the same.
MainActivity.java:
public class MainActivity extends ActionBarActivity < private ListView listView; private ArrayListmDeviceList = new ArrayList(); private BluetoothAdapter mBluetoothAdapter; @Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.listView); mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); mBluetoothAdapter.startDiscovery(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); >@Override protected void onDestroy() < unregisterReceiver(mReceiver); super.onDestroy(); >private final BroadcastReceiver mReceiver = new BroadcastReceiver() < public void onReceive(Context context, Intent intent) < String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) < BluetoothDevice device = intent .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); mDeviceList.add(device.getName() + "\n" + device.getAddress()); Log.i("BT", device.getName() + "\n" + device.getAddress()); listView.setAdapter(new ArrayAdapter(context, android.R.layout.simple_list_item_1, mDeviceList)); > > >;
activity_main.xml:
Manifest file:
Please make sure that you ask Location permission to your user and turn GPS On.
Reason: From Android 6.0 you need Location permission for Bluetooth Discovery.
More reference:
Do you know how can I connect it with a click? I mean if I have a list with all of my paired devices do you know how to connect it with 1 click?
I am trying this code.It is provide all paired devices. How can I get ReadyToPair device?Is there any way to achieve this thing?
ListPairedDevicesActivity.java
import java.util.Set; import android.app.ListActivity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothClass; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class ListPairedDevicesActivity extends ListActivity < @Override protected void onCreate(Bundle savedInstanceState) < // TODO Auto-generated method stub super.onCreate(savedInstanceState); ArrayAdapterbtArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); Set pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) < for (BluetoothDevice device : pairedDevices) < String deviceBTName = device.getName(); String deviceBTMajorClass = getBTMajorDeviceClass(device .getBluetoothClass() .getMajorDeviceClass()); btArrayAdapter.add(deviceBTName + "\n" + deviceBTMajorClass); >> setListAdapter(btArrayAdapter); > private String getBTMajorDeviceClass(int major) < switch(major)< case BluetoothClass.Device.Major.AUDIO_VIDEO: return "AUDIO_VIDEO"; case BluetoothClass.Device.Major.COMPUTER: return "COMPUTER"; case BluetoothClass.Device.Major.HEALTH: return "HEALTH"; case BluetoothClass.Device.Major.IMAGING: return "IMAGING"; case BluetoothClass.Device.Major.MISC: return "MISC"; case BluetoothClass.Device.Major.NETWORKING: return "NETWORKING"; case BluetoothClass.Device.Major.PERIPHERAL: return "PERIPHERAL"; case BluetoothClass.Device.Major.PHONE: return "PHONE"; case BluetoothClass.Device.Major.TOY: return "TOY"; case BluetoothClass.Device.Major.UNCATEGORIZED: return "UNCATEGORIZED"; case BluetoothClass.Device.Major.WEARABLE: return "AUDIO_VIDEO"; default: return "unknown!"; >> @Override protected void onListItemClick(ListView l, View v, int position, long id) < // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); Intent intent = new Intent(); setResult(RESULT_OK, intent); finish(); >>
AndroidBluetooth.java
import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class AndroidBluetooth extends Activity < private static final int REQUEST_ENABLE_BT = 1; private static final int REQUEST_PAIRED_DEVICE = 2; /** Called when the activity is first created. */ Button btnListPairedDevices; TextView stateBluetooth; BluetoothAdapter bluetoothAdapter; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); btnListPairedDevices = (Button)findViewById(R.id.listpaireddevices); stateBluetooth = (TextView)findViewById(R.id.bluetoothstate); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); CheckBlueToothState(); btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener); >private void CheckBlueToothState()< if (bluetoothAdapter == null)< stateBluetooth.setText("Bluetooth NOT support"); >else< if (bluetoothAdapter.isEnabled())< if(bluetoothAdapter.isDiscovering())< stateBluetooth.setText("Bluetooth is currently in device discovery process."); >else < stateBluetooth.setText("Bluetooth is Enabled."); btnListPairedDevices.setEnabled(true); >>else < stateBluetooth.setText("Bluetooth is NOT Enabled!"); Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); >> > private Button.OnClickListener btnListPairedDevicesOnClickListener = new Button.OnClickListener()< @Override public void onClick(View arg0) < // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(AndroidBluetooth.this, ListPairedDevicesActivity.class); startActivityForResult(intent, REQUEST_PAIRED_DEVICE); >>; @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) < // TODO Auto-generated method stub if(requestCode == REQUEST_ENABLE_BT)< CheckBlueToothState(); >if (requestCode == REQUEST_PAIRED_DEVICE) < if(resultCode == RESULT_OK)< >> > >
AndroidManifest.xml