Oreo, BLE scanner startScan with PendingIntent not working on Samsung device

北慕城南 提交于 2019-12-03 09:11:18

You have registered the broadcast receiver in the AndroidManifest.xml with an Intent Filter name

<action android:name="BluetoothDevice.ACTION_FOUND" />

First of all, you may provide there any String. Above suggest that you are using this constant, but in fact you are just using the String as is (BluetoothDevice.ACTION_FOUND). I would recommend changing it to some com.testapp.samsungoscan.ACTION_FOUND. The Extras are not needed and they suggest they are in fact extras, but they are just another action names with name "extra".

I recommend changing to:

<receiver android:name="com.testapp.samsungoscan.BleReceiver">
    <intent-filter>
         <action android:name="com.testapp.samsungoscan.ACTION_FOUND" />
    </intent-filter>
</receiver>

Secondly, you have to create the PendingIntent with this action name:

private fun getPendingIntent(): PendingIntent {
    return PendingIntent.getBroadcast(
            this, REQ_CODE,
            Intent(this.applicationContext, BleReceiver::class.java).setAction("com.testapp.samsungoscan.ACTION_FOUND"),
            PendingIntent.FLAG_UPDATE_CURRENT)
}

Creating an intent with providing Component name is required since Oreo to be able to get any broadcasts. I'm not sure, however, will it work after your app has been killed by the system.

Lastly, I recommend requesting FINE_LOCATION, as this: https://android-review.googlesource.com/c/platform/packages/apps/Bluetooth/+/848935 change may in the future require fine location permission to scan for Bluetooth devices.

You need to pass an empty filters list to the startScan() call instead of null

List<ScanFilter> listOfFiters = new ArrayList<>();
ScanFilter.Builder builder = new ScanFilter.Builder();
ScanFilter filter = builder.build();
listOfFiters.add(filter);

bleScanner.startScan(listOfFilters, null, getPendingIntent())

Ah, and in addition to passing empty filter to the startScan you will also need ACCESS_FINE_LOCATION permission on latest Android versions.

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