我正在尝试扫描Microchip的RN4020 BLE模块。找到绑定后,设备绑定成功。此功能适用于所有经过测试的Android版本(5、7和8)。
现在,绑定完成后,RN4020开始使用直接广告来进行广告,因此我读了here,了解如何检测直接广告。原来您需要向您freeAxes
添加您要检测的设备的MAC地址。我从绑定的设备中获得了所有地址,因此这是我获得扫描过滤器的部分:
ScanFilter
这是我获得扫描设置的部分:
private List<ScanFilter> get_scan_filter()
{
ScanFilter.Builder filter_builder = new ScanFilter.Builder();
ScanFilter filter = filter_builder.setServiceUuid(new ParcelUuid(UUIDS.MY_SERVICE_UUID)).build();
List<ScanFilter> filter_list = new LinkedList<ScanFilter>();
filter_list.add(filter);
//add MAC addresses of bonded devices in scan filter
BluetoothAdapter bluetooth_adapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> bonded_devices = bluetooth_adapter.getBondedDevices();
for(BluetoothDevice device : bonded_devices){
String address = device.getAddress();
if(address != null){
filter_list.add(new ScanFilter.Builder().setDeviceAddress(address).build());
}
}
return filter_list;
}
最后开始扫描:
private ScanSettings get_scan_settings()
{
ScanSettings.Builder settings_builder = new ScanSettings.Builder();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
settings_builder = settings_builder.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES);
}
ScanSettings settings = settings_builder.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY).build();
return settings;
}
le_scanner.startScan(get_scan_filter(), get_scan_settings(), le_scan_callback);
的代码甚至都不重要,因为如果发生直接广告投放,则对于Android 7和8版本都不会被调用。 一切适用于Android 5。
在版本7和8上,我还要求运行时ACCESS_COARSE_LOCATION权限:
le_scan_callback
,并确保在执行此操作时启用if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access");
builder.setMessage("Please grant location access so this app can detect BLE devices.");
builder.setPositiveButton("ok", null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
}
});
builder.show();
}
。
Location
因此,似乎一切都应该起作用,但事实并非如此。请记住,上面的代码在绑定Android 5之前和之后都可以正常工作(扫描程序找到了我的RN4020 BLE模块),但是在绑定完成之后,对于Android 7和8,扫描都找不到任何东西。为什么会发生这种情况?任何帮助表示赞赏。