我正在开发一个具有连接功能的应用程序,该应用程序使用SDK 23连接到蓝牙设备。我在请求蓝牙的多个权限时遇到问题。这是我到目前为止所做的:
@Override
public void onStart() {
super.onStart();
if (D)
Log.e(TAG, "++ ON START ++");
if (ContextCompat.checkSelfPermission(MyBlueToothClientActivity.this,
Manifest.permission.BLUETOOTH)
!= PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(MyBlueToothClientActivity.this,
new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN},
REQUEST_ENABLE_BT);
}
if (ContextCompat.checkSelfPermission(MyBlueToothClientActivity.this,
Manifest.permission.BLUETOOTH)
!= PackageManager.PERMISSION_GRANTED) {
} else {
ActivityCompat.requestPermissions(MyBlueToothClientActivity.this,
new String[]{Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN},
REQUEST_CONNECT_DEVICE_INSECURE);
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_ENABLE_BT: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
if (CommonData.mChatService == null)
setupChat();
Toast.makeText(MyBlueToothClientActivity.this, "Permission denied for bluetooth", Toast.LENGTH_SHORT).show();
}
return;
}
case REQUEST_CONNECT_DEVICE_INSECURE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay!
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_CONNECT_DEVICE_INSECURE);
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
if (CommonData.mChatService == null)
setupChat();
Toast.makeText(MyBlueToothClientActivity.this, "Permission denied for bluetooth", Toast.LENGTH_SHORT).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
虽然我能够获得请求启用蓝牙的对话框,但我没有得到第二个许可,即连接到设备。在logcat中,我得到:
01-01 06:41:24.334 25473-25473 E/BluetoothChat: ++ ON START ++
01-01 06:41:24.344 25473-25473 W/Activity: Can reqeust only one set of permissions at a time
由于我无法连接到设备,我只是被困在这里。这个代码在Android版本到Lollipop上工作正常,只会导致Marshmallow版本出现问题。
答案 0 :(得分:17)
BLUETOOTH
和BLUETOOTH_ADMIN
为normal permissions,因此会自动授予它们。只有table of dangerous permissions中的权限需要在运行时请求。
但是,如Android 6.0 changes: Access to Hardware Identifier中所述:
要通过蓝牙和Wi-Fi扫描访问附近外部设备的硬件标识符,您的应用现在必须具有ACCESS_FINE_LOCATION或ACCESS_COARSE_LOCATION权限:
如果您正在使用这些方法中的任何一种,则您需要在运行时至少请求ACCESS_COARSE_LOCATION
(因为 是危险权限)。