当前位置:   article > 正文

android 蓝牙 setscanmode,蓝牙LE扫描在后台无法在Android M上运行

bluetoothadapter setscanmode方法无法使用

以下代码适用于运行Android 5.1.1(Build LMY48M)的Nexus 9,但不适用于运行Android 6.0的Nexus 9(Build MPA44l)

List filters = new ArrayList();

ScanSettings settings = (new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)).build();

ScanFilter.Builder builder = new ScanFilter.Builder();

builder.setManufacturerData((int) 0x0118, new byte[]{(byte) 0xbe, (byte) 0xac}, new byte[]{(byte) 0xff, (byte)0xff});

ScanFilter scanFilter = builder.build();

filters.add(scanFilter);

mBluetoothLeScanner.startScan(filters, settings, new ScanCallback() {

...

});

在Android 5.x上,当看到与扫描过滤器匹配的制造商广告时,上述代码产生回调. (参见下面的示例Logcat输出.)在带有MPA44l的Nexus 9上,没有收到回调.如果您注释掉扫描过滤器,则会在Nexus 9上成功接收回调.

09-22 00:07:28.050 1748-1796/org.altbeacon.beaconreference D/BluetoothLeScanner﹕ onScanResult() - ScanResult{mDevice=00:07:80:03:89:8C, mScanRecord=ScanRecord [mAdvertiseFlags=6, mServiceUuids=null, mManufacturerSpecificData={280=[-66, -84, 47, 35, 68, 84, -49, 109, 74, 15, -83, -14, -12, -111, 27, -87, -1, -90, 0, 1, 0, 1, -66, 0]}, mServiceData={}, mTxPowerLevel=-2147483648, mDeviceName=null], mRssi=-64, mTimestampNanos=61272522487278}

有没有人看过ScanFilters在Android M上工作?

解决方法:

我的应用程序连接到蓝牙也有类似的问题.不是LE ScanFilter,但它就像OP一样是权限问题.

根本原因是从SDK 23开始,您需要使用Activity的requestPermissions()方法在运行时提示用户获取权限.

这对我有用:

>将以下两行之一添加到根节点内的AndroidManifest.xml中:

>在您的Activity中,在尝试连接到蓝牙之前,请调用Activity的requestPermissions()方法,该方法打开系统对话框以提示用户获取权限.权限对话框在另一个线程中打开,因此在尝试连接到蓝牙之前一定要等待结果.

>覆盖Activity的onRequestPermissionsResult()来处理结果.如果用户拒绝授予权限,该方法实际上只需要做一些事情,告诉用户应用程序无法进行蓝牙活动.

This blog post有一些示例代码,它使用AlertDialogs告诉用户发生了什么.这是一个很好的起点,但有一些缺点:

>它不处理等待requestPermissions()线程完成

>包含对requestPermissions()的调用的AlertDialog对我来说似乎是无关紧要的.对requestPermissions()的裸调用就足够了.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/956084
推荐阅读
相关标签
  

闽ICP备14008679号