Friday, July 30, 2010

Android Bluetooth scanning

Discovering Bluetooth devices in Android is fairly simple, there are a lot of examples on the internet. What not all of those examples show you, and what got me into trouble was the bold bit in the code snippet below: I didn't realise that BluetoothAdapter.getDefaultAdapter() will return null when the user turns Bluetooth of in the phone settings. That got me a nice NullPointerException ...

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
    // bluetooth disabled/not available
}

else {
    context.registerReceiver(new BluetoothListener(), new IntentFilter(BluetoothDevice.ACTION_FOUND));
    bluetoothAdapter.startDiscovery();
}


private class BluetoothListener extends BroadcastReceiver {
    @Override
    public void onReceive(Context c, Intent intent) {
        BluetoothDevice rbd = (BluetoothDevice)intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        // ...
    }
}

No comments: