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); >>
Поиск устройств Bluetooth
Bluetooth Finder — средство поиска устройств Bluetooth позволяет обнаруживать любые устройства Bluetooth вокруг вас. С помощью этого приложения поиска Bluetooth вы можете легко включить или выключить Bluetooth в этом приложении диспетчера Bluetooth. Этот Bluetooth Finder — Bluetooth Tracker помогает вам искать и находить сопряженные Bluetooth устройства с помощью индикатора мощности принятого сигнала (RSSI). Если вы хотите найти какое-либо устройство Bluetooth рядом с вами, просто откройте это приложение Bluetooth Finder — Air Finder и пройдите по ближайшим местам, чтобы приложение соответственно сообщило о мощности сигнала и показало, находится ли устройство Bluetooth рядом с вами. Вы можете получить всю информацию о доступных сопряженных устройствах. Bluetooth Finder — track my Fit-bit позволяет вам определять местонахождение ваших устройств Bluetooth с помощью индикатора мощности принятого сигнала (RSSI). Поиск Bluetooth — все сопряженные устройства отображают полный список уже сопряженных и подключенных устройств.
Какие функции мы предлагаем в этом искателе Bluetooth — сканирование устройств Bluetooth?
-Как включить или выключить Bluetooth:
Поиск Bluetooth — включите Bluetooth вручную, войдя в это приложение для быстрого переключения Bluetooth. Вы также можете выключить Bluetooth, нажав кнопку выключения Bluetooth на главном переключателе.
-Как сканировать устройства Bluetooth рядом с вами:
Найти Bluetooth — поиск устройств Bluetooth рядом с вами позволяет искать и перечислять все ближайшие устройства Bluetooth. BT Scanner помогает найти наушники Bluetooth, беспроводные наушники и динамики, а также отслеживать любые типы устройств Bluetooth.
-Как увидеть сопряженные устройства Bluetooth на вашем устройстве:
Поиск Bluetooth — Просмотр сопряженных устройств показывает подробный список всех устройств Bluetooth, сопряженных с вашим телефоном. Он помогает вам видеть все устройства Bluetooth, включая подключенные и сопряженные устройства Bluetooth, а также неизвестные устройства. Информация о сопряженных устройствах Bluetooth позволяет получать и просматривать информацию обо всех устройствах Bluetooth, которые когда-то были сопряжены и подключены к вашему устройству.
-Как найти устройства bluetooth, используя силу bluetooth:
Поиск Bluetooth — сканирует мощность сигнала Bluetooth, получает характеристики Bluetooth всех видимых устройств рядом с вами и показывает мощность сигналов Bluetooth каждого устройства. Это приложение для сканирования Bluetooth RSSI показывает уровень мощности Bluetooth-устройств в радиусе действия. Чем ближе вы подойдете к сопряженному устройству, тем сильнее будет сигнал. Таким образом, сканер мощности Bluetooth можно использовать для поиска устройств Fitbit с использованием уровней сигнала Bluetooth.
-Как просмотреть информацию о Bluetooth:
Найти Bluetooth — приложение «Найти информацию о Bluetooth» отображает всю информацию о вашем адаптере Bluetooth, установленном в вашем мобильном телефоне. Вы можете просматривать всю необходимую информацию на своем Bluetooth. Он также может найти Mac-адрес вашего устройства Bluetooth.
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); >>