我刚刚添加到清单中:
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
然后我像其他任何人一样向 Main Activity 请求这些权限。为了请求许可,我正在使用库
implementation 'pub.devrel:easypermissions:3.0.0'
那么你可以调用这个函数
public static final String[] BLUETOOTH_PERMISSIONS_S = { Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT} ;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (!EasyPermissions.hasPermissions(this, BLUETOOTH_PERMISSIONS_S)) {
EasyPermissions.requestPermissions(this, message, yourRequestCode,BLUETOOTH_PERMISSIONS_S);
}
}
并覆盖 onRequestPermissionResult
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
JetPACK 组合更新
如果您使用的是 jetpack compose,则可以这样处理:
在 rememberMultiplePermissionState 函数中创建您的权限列表
rememberMultiplePermissionsState(
permissions = listOf(
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN
)
)
然后观察生命周期事件和恢复启动权限请求
val lifecycleOwner = LocalLifecycleOwner.current
DisposableEffect(key1 = lifecycleOwner,
effect = {
val observer = LifecycleEventObserver { _, event ->
if(event == Lifecycle.Event.ON_START) {
permissionsState.launchMultiplePermissionRequest()
}
}
lifecycleOwner.lifecycle.addObserver(observer)
onDispose {
lifecycleOwner.lifecycle.removeObserver(observer)
}
})
观察权限状态
permissionsState.permissions.forEach { permissionState ->
when(permissionState.permission) {
Manifest.permission.ACCESS_FINE_LOCATION -> {
when {
permissionState.hasPermission -> {}
}
}
}
}
}