1、问题
高版本android 给定蓝牙权限,并注册监听事件后,ACTION_FOUND还是不能触发事件。程序如下图所示。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.king.Bluetooth.activity">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"
tools:ignore="ProtectedPermissions" />
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
2、解决办法:
经过很多次测试发现,即使给了权限软件好使拿不到,在程序运行的时候判断一下,如果权限没获取到,在动态获取下即可解决问题。可以在onCreate函数中添加下面程序即可。
/*
this method is required for all devices running API 23+ (Android 6.0 + )
Android must programmatically check the permission for bluetooth
only put permission in manifest is not enough
Note: this will only execute on version > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermission() {
Log.d(TAG, "checkBTPermission: Start");
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if(permissionCheck != 0){
this.requestPermissions(new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
}, 1001); //any number
}else{
Log.d(TAG,
"checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
}
Log.d(TAG, "checkBTPermission: Finish");
}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/20210113204944965.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3Nvbmdpc2dvb2Q=,size_16,color_FFFFFF,t_70)