Anfaje Anfaje - 1 year ago 241
Android Question

getBluetoothLeAdvertiser() returns null

BluetoothLeAdvertiser advertiser = BluetoothAdapter.getDefaultAdapter().getBluetoothLeAdvertiser();

This returns null. I have tried on an API 21 and on an API 23 device, but with the same result. I have no idea what I am missing?

The app builds and runs just fine, until of course the advertiser is used and the app crashes.

I appreciate any help provided! :)

Answer Source

If you check the developer docs, link here. You'll see that the null object is returned in the following case:

Returns a BluetoothLeAdvertiser object for Bluetooth LE Advertising operations. Will return null if Bluetooth is turned off or if Bluetooth LE Advertising is not supported on this device.

If you are unsure whether the device supports Bluetooth at all you should check if the BluetoothAdapter returned by the system is null

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
    // Device does not support Bluetooth

Then they advice you to call isMultipleAdvertisementSupported() to see if it is supported first.

    //Device does not support Bluetooth LE

If it supports BLE you must check to see if Bluetooth is enabled and if not, make the user aware and resolve it.

if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);

That should cover most of the times the adapter is null