troubledsoul
troubledsoul

Reputation: 79

bluetoothAdapter.enable(); shows Bluetooth enable prompt without intent ACTION_REQUEST_ENABLE in some devices

I would like to enable bluetooth with my app without user interaction, the prompt does not appear on my devices - Android 7, 8 & 9, and my friend's Android 10. But it appears in my work colleague's devices (Android 10).

I used the following permissions

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

And used the following Bluetooth Adaptor methods.

bluetoothAdapter.enable();
bluetoothAdapter.disable();

I have no intent ACTION_REQUEST_ENABLE or ACTION_REQUEST_DISABLE in my source code.

Am I missing some permissions or methods? Or is this an environment problem? Any advise on how should I handle this would be much appreciated.

Thank you.

Upvotes: 1

Views: 471

Answers (1)

dingpwen
dingpwen

Reputation: 161

bluetoothAdapter.enable() will directly run com.android.settings/.bluetooth.RequestPermissionHelperActivity, and you should listen for ACTION_STATE_CHANGED yourself.

I think use the BluetoothAdapter.ACTION_REQUEST_ENABLE is a better way, which will first run com.android.settings.bluetooth.RequestPermissionActivity and then RequestPermissionHelperActivity. RequestPermissionActivity will listen for ACTION_STATE_CHANGED, while your app only need the result code of Activity.RESULT_OK.

private boolean ensureBluetoothEnabled() {
    if(((BluetoothManager) Objects.requireNonNull(getSystemService(Context.BLUETOOTH_SERVICE)))
            .getAdapter().isEnabled()) {
        return true;
    } else {
        Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        btIntent.putExtra(Intent.EXTRA_PACKAGE_NAME, Constants.PACKAGE);
        startActivityForResult(btIntent, REQUEST_CODE_BL_OPEN);
        return false;
    }
}

Upvotes: 2

Related Questions