Android 13 蓝牙动态权限申请指南
Android 13 中如何处理蓝牙动态权限申请
在 Android 13 及以上版本中,蓝牙权限申请需要在运行时进行动态授权。以下是处理蓝牙动态权限申请的步骤:
- 在
AndroidManifest.xml文件中添加以下权限:
<uses-permission android:name='android.permission.BLUETOOTH'/>
<uses-permission android:name='android.permission.BLUETOOTH_ADMIN'/>
<uses-permission android:name='android.permission.ACCESS_FINE_LOCATION'/>
- 在
Activity或Fragment中,检查是否授权了蓝牙权限。如果没有授权,则请求权限。
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private static final int REQUEST_ENABLE_LOCATION = 2;
//检查蓝牙权限是否被授权
private boolean isBluetoothPermissionGranted() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) == PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
//请求蓝牙权限
private void requestBluetoothPermission() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ENABLE_BLUETOOTH);
}
//处理权限请求的回调
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//权限被授予,执行相应操作
} else {
//权限被拒绝,提示用户
}
}
}
- 如果需要访问设备位置,则还需要请求位置权限。在请求蓝牙权限时,同时请求位置权限。
//检查位置权限是否被授权
private boolean isLocationPermissionGranted() {
return ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
//请求位置权限
private void requestLocationPermission() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_ENABLE_LOCATION);
}
//处理权限请求的回调
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_ENABLE_LOCATION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//权限被授予,执行相应操作
} else {
//权限被拒绝,提示用户
}
}
}
以上是 Android 13 中处理蓝牙动态权限申请的步骤。
原文地址: https://www.cveoy.top/t/topic/lgce 著作权归作者所有。请勿转载和采集!