所以在 API 31 中有新的蓝牙权限。我想用这个打开或关闭蓝牙:
private void changeBluetoothState(boolean status) {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (status)
mBluetoothAdapter.enable();
else mBluetoothAdapter.disable();
}
并且在清单中我已经有了这个:
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-feature
android:name="android.hardware.bluetooth"
android:required="false" />
Android 文档表示,如果针对 API 31 或更高版本,则将
android:maxSdkVersion="30"
添加到上述蓝牙权限中。我还在 Android Studio 中收到一个错误,enable() 和disable() 函数需要"android.permission.BLUETOOTH_CONNECT"
。
如果添加
android:maxSdkVersion="30"
告诉系统忽略
关于更高 API 的声明是可选的而不是强制性的,
这是否意味着不添加它将使该语句继续工作
更高的 API?
如果
"android.permission.BLUETOOTH_CONNECT"
允许我的应用程序
与其他蓝牙设备交互那么为什么需要
启用或禁用原始设备上的蓝牙适配器?
如果运行时需要请求BLUETOOTH_CONNECT权限 正确的完整方法是什么?意思是检查它是否已经存在 如果没有授予,则请求它。我没有 Android 12 设备,所以 无法测试此代码。
针对Android 12我的工作解决方案是通过这种方式声明权限:
<!--Before Android 12 (but still needed location, even if not requested)-->
<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" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<!--From Android 12-->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
就像你说的,BLUETOOTH_SCAN是不够的,你需要BLUETOOTH_CONNECT(如果你像我一样决定要求用户启用蓝牙,通过操作BluetoothAdapter.ACTION_REQUEST_ENABLE启动新的startActivityForResult)
如果需要在运行时请求 BLUETOOTH_CONNECT 权限,正确的完整方法是什么?意思是检查它是否已经被授予,如果没有则请求它。我没有 Android 12 设备,因此无法测试此代码。
是的,与在 Android 上请求位置权限的方式相同< 12 (not need anymore) now you ask for both BLUETOOTH_SCAN and BLUETOOTH_CONNECT
为了改进@AndreasGobs的答案,请在代码下方根据当前可用权限测试与设备的连接是否可行。 在清单中,我设置了 COARSE 和 FINE 位置权限必须限制为最大 API 30。 在 Android 6、8.1、11 和 12 设备上进行了测试。 我希望这会有用。
/**
* - API < S
* - Check ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION permissions
* - API < O
* - Check has GPS
* - Check GPS enabled
* - API >= S
* - Check BLUETOOTH_SCAN permission
* - Check BLUETOOTH_CONNECT permission
* - Check Bluetooth enabled
*/
private boolean canConnect(){
Timber.d("canConnect called");
List<String> deniedPermissions = new ArrayList<>();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) {
if (!checkPermission(Manifest.permission.ACCESS_COARSE_LOCATION))
deniedPermissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
if (!checkPermission(Manifest.permission.ACCESS_FINE_LOCATION))
deniedPermissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
if(deniedPermissions.isEmpty()){
if (!MmcDeviceCapabilities.hasLocationGps() //check if the device has GPS
|| Build.VERSION.SDK_INT < Build.VERSION_CODES.O
|| MmcDeviceCapabilities.isGpsEnabled()){ //check if the GPS is enabled
if(MmcDeviceCapabilities.bluetoothEnabled()) //check if bluetooth is enabled
return true;
else {
requestEnableBluetooth(); //method to request enable bluetooth
return false;
}
}
else {
Timber.d("Request enable GPS");
requestEnableGps(); //method to request enable GPS (improving devices scan)
return false;
}
}
else {
Timber.d("Request GPS permissions");
requestRuntimePermissions(
"Bluetooth GPS request",
"GPS permissions request rationale",
GPS_PERMISSIONS_CODE,
deniedPermissions.toArray(new String[0]));
return false;
}
}
else { // Build.VERSION_CODES.S or later
if(!checkPermission(Manifest.permission.BLUETOOTH_SCAN))
deniedPermissions.add(Manifest.permission.BLUETOOTH_SCAN);
if(!checkPermission(Manifest.permission.BLUETOOTH_CONNECT))
deniedPermissions.add(Manifest.permission.BLUETOOTH_CONNECT);
if(deniedPermissions.isEmpty())
if(MmcDeviceCapabilities.bluetoothEnabled()) //check if bluetooth is enabled
return true;
else {
requestEnableBluetooth(); //method to request enable bluetooth
return false;
}
else {
Timber.d("Request bluetooth permissions");
requestRuntimePermissions(
"Bluetooth permissions request",
"Bluetooth permissions request rationale",
CONNECT_PERMISSIONS_CODE,
deniedPermissions.toArray(new String[0]));
return false;
}
}
}
/**
* This method checks if a runtime permission has been granted.
* @param permission The permission to check.
* @return <code>TRUE</code> if the permission has been granted, <code>FALSE</code> otherwise.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
private boolean checkPermission(@NonNull String permission){
return ActivityCompat.checkSelfPermission(this, permission)
== PackageManager.PERMISSION_GRANTED;
}
private void requestRuntimePermissions(@NonNull String title, @NonNull String description, int requestCode, @NonNull String... permissions){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0])) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder
.setTitle(title)
.setMessage(description)
.setCancelable(false)
.setNegativeButton(android.R.string.no, (dialog, id) -> {
//do nothing
})
.setPositiveButton(android.R.string.ok, (dialog, id) -> ActivityCompat.requestPermissions(this, permissions, requestCode));
showDialog(builder); //method to show a dialog
}
else ActivityCompat.requestPermissions(this, permissions, requestCode);
}
这对我在 Android 12 上使用 React Native 0.68.5 有效
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
我正在使用 React Native 0.64,并且我在 Android 12+ 上遇到了一些类似的问题
我的清单文件
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
但这还不够,我仍然收到请求蓝牙权限的错误。
我发现 BLUETOOTH_SCAN 是导致我出现问题的原因。 因此,在请求许可后,我能够使用我的应用程序再次发现蓝牙设备
import {
requestMultiple,
PERMISSIONS,
RESULTS,
} from "react-native-permissions";
然后我就有了这个帮手
let androidPermissions = [PERMISSIONS.ANDROID.BLUETOOTH_SCAN];
const isAndroid12OrGreater = await IS_ANDROID_12_OR_GREATER(); // <-- helper I created to check Android version
if (isAndroid && isAndroid12OrGreater)
android.push(PERMISSIONS.ANDROID.BLUETOOTH_SCAN); // <-- this one solved the issue in my case
const statuses = await requestMultiple(androidPermissions);
return Object.values(statuses).some(el => el === RESULTS.GRANTED); // and then I do some stuff with the results
Android 12+ 需要蓝牙的运行时权限。
这是一个用于使设备可发现的蓝牙运行时权限的 Kotlin 示例...
val activityResultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
if (result.resultCode == RESULT_OK) {
// There are no request codes
result.data
} else {
// Do something
}
}
if (bluetoothAdapter?.isEnabled == true) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
fun hasPermissions(context: Context, vararg permissions: String): Boolean =
permissions.all {
ActivityCompat.checkSelfPermission(
context,
it
) == PackageManager.PERMISSION_GRANTED
}
val permissionAll = 1
val permissions =
arrayOf(
// dev manual says need these for API 30 (v11) or lower, not added to manifest, will try without
// Manifest.permission.ACCESS_COARSE_LOCATION,
// Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.BLUETOOTH_ADVERTISE,
Manifest.permission.BLUETOOTH_CONNECT,
Manifest.permission.BLUETOOTH_SCAN
)
if (!hasPermissions(requireContext(), *permissions)) {
ActivityCompat.requestPermissions(
(activity as MainActivity),
permissions,
permissionAll
)
}
} else {
TODO("VERSION.SDK_INT < S")
}
val intentDiscover = Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE)
activityResultLauncher.launch(intentDiscover)
}