getBluetoothLeAdvertiser() returns null

别等时光非礼了梦想. 提交于 2019-12-22 14:17:11

问题


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! :)


回答1:


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.

if(!mBluetoothAdapter.isMultipleAdvertisementSupported()){
    //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




回答2:


Check for mBluetoothAdapter != null && mBluetoothAdapter.isEnabled() before you start the scanning



来源:https://stackoverflow.com/questions/37938655/getbluetoothleadvertiser-returns-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!