24

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?

Abdul Rahman
  • 2,097
  • 4
  • 28
  • 36
xenonite
  • 1,671
  • 4
  • 28
  • 43

4 Answers4

52

Check out code below :

Starting search

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);
Vingtoft
  • 13,368
  • 23
  • 86
  • 135
Deepthi
  • 875
  • 1
  • 12
  • 20
  • Nice clean code, this should be the correct answer. – Dayan May 24 '16 at 21:02
  • @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. – user420667 Apr 22 '17 at 21:52
  • how does this work if there are multiple bluetooth devices found in the range. Does the receiver get triggered multiple times? – Zapnologica Jul 17 '18 at 19:24
  • 1
    @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. – Martin Zeitler Jul 18 '18 at 06:45
  • @SaharMillis make sure you have put permission in the manifest of location and Bluetooth – Riddhi Shankar Apr 18 '19 at 05:48
14

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

Result

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

user3826696
  • 1,045
  • 12
  • 13
  • Nice example. Note that deviceName may be null. – GregD Apr 03 '22 at 20:17
  • @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 – jane Jan 31 '23 at 06:47
1

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(Collection<Beacon> beacons, 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!

Aimery
  • 1,559
  • 1
  • 19
  • 24
1

To able to discovery devices by bluetooth. Make sure you

AndroidManifest.xml

<uses-permission
    android:name="android.permission.BLUETOOTH"
    android:maxSdkVersion="30" />
<uses-permission
    android:name="android.permission.BLUETOOTH_ADMIN"
    android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

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>(BluetoothDevice.EXTRA_DEVICE)

                Log.i("TAG", "Device Name: " + (device?.name ?: ""))
                Log.i("TAG", "Device Address:" + (device?.address ?: ""))
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        ...

        findViewById<Button>(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);
    }
}
Linh
  • 57,942
  • 23
  • 262
  • 279