哪个Android权限更适合蓝牙设备发现或接收蓝牙广播?

时间:2017-04-20 04:29:25

标签: android bluetooth android-manifest android-permissions broadcast

我在尝试蓝牙设备发现时遇到了权限问题。

问题: - “需要android.permission.ACCESS_COARSE_LOCATION,因为发件人com.android.bluetooth”已经为清单添加了以下权限

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

1 个答案:

答案 0 :(得分:2)

在棉花糖上发现BT设备的正确程序如下:

1)在清单中有ACCESS_COARSE_LOCATION权限要求以及通常的蓝牙权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2)确保您拥有ACCESS_COARSE_LOCATION

的运行时权限
protected void checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                REQUEST_COARSE_LOCATION);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                   String permissions[], int[] grantResults) {
    switch (requestCode) {
    case REQUEST_COARSE_LOCATION: {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            proceedDiscovery(); // --->
        } else {
            //TODO re-request
        }
        break;
    }
}
}

3)为ACTION_FOUND注册广播接收器并呼叫

BluetoothAdapter.startDiscovery()
protected void proceedDiscovery() {
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothDevice.ACTION_NAME_CHANGED);
    registerReceiver(mReceiver, filter);

    mBluetoothAdapter.startDiscovery();
}