简体   繁体   中英

Which android permission is better for Bluetooth device discovery or receiving Bluetooth broadcast?

I am getting permission issues while trying for Bluetooth device discovery.

Issue:- "requires android.permission.ACCESS_COARSE_LOCATION due to sender com.android.bluetooth" already added the following permissions to manifest

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

The correct procedure for BT device discovery on Marshmallow is as follows:

1) Have ACCESS_COARSE_LOCATION permission requirement in manifest along with usual bluetooth permissions:

<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)Ensure you have run-time permission for 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) Register a broadcast receiver for ACTION_FOUND and call

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

    mBluetoothAdapter.startDiscovery();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM