简体   繁体   中英

How to know if a bluetooth device is online with it's address?

I am getting list of all paired devices by using method bluetoothAdapter.getBondDevices() . Is there anyway to check how many devices are actually online ie ready to receive data?

What I'm doing in my app is to create BroadcastReceiver, and implement onReceive(), where I'm checking for BluetoothDevice.ACTION_FOUND and adding discovered devices to a list:

//holds names of BT devices discovered
private ArrayList<String> btDevices = new ArrayList<String>();

In onCreate(), create receiver:

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);
            if (device.getName() != null) {
                btDevices.add(device.getName());
            }
            else {
                Log.d("MyTag", "device.getName() is null");
            }
        }
    }
};

Then, create intent filter and register receiver:

IntentFilter btFilter = new IntentFilter();
btFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
btFilter.addAction(BluetoothDevice.ACTION_FOUND);

registerReceiver(mReceiver, btFilter);

Get bluetoothAdapter and start discovery:

bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

//we have adapter
if (bluetoothAdapter != null) {
    //Bluetooth is OFF, so turn it on
if (!bluetoothAdapter.isEnabled()) {
        bluetoothAdapter.enable();      
    }
    else {
        bluetoothAdapter.startDiscovery();
    }
}

Then, I can check how many devices have been discovered with btDevices.size()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM