如何在用户拒绝后为 Android 12 重新请求 BLUETOOTH_SCAN 和 BLUETOOTH_CONNECT 权限?

How to re-request BLUETOOTH_SCAN and BLUETOOTH_CONNECT permissions for Android 12 after a user denial?

我在以 SDK 31 (Android 12) 为目标时重新请求扫描和连接蓝牙设备所需的权限时遇到问题。

我在主 activity 的 onCreate():

中调用了这个方法
public void requestBluetoothPermissions() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

        if ((this.checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)
            || (this.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)) {

            Log.w(getClass().getName(), "requestBluetoothPermissions() BLUETOOTH_SCAN AND BLUETOOTH_CONNECT permissions needed => requesting them...");

            this.requestPermissions(new String[]{
                    Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT
            }, MyActivity.REQUEST_BLUETOOTH_PERMISSIONS);

        }
    }
}

第一次调用时工作正常,即向用户显示 Android 弹出窗口,提示他授予权限。

但如果他拒绝授予权限,下次调用onCreate()时,将不会显示弹窗,这意味着用户仍然无法授予权限。

知道为什么以及如何解决这个问题吗?

出现 Android 12 个块在用户仅拒绝一次后请求相同的权限。

因此,我最终使用 ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.BLUETOOTH_SCAN) 来确定是否可以请求权限,在这种情况下,会显示一条信息栏消息,解释为什么需要权限,并带有一个打开应用程序设置的按钮,其中可以授予权限。

这是代码示例:

public void requestBluetoothPermissions() {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {

        if ((this.checkSelfPermission(Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED)
            || (this.checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED)) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                    Manifest.permission.BLUETOOTH_SCAN)) {

                 // display permission rationale in snackbar message
            } else {
                Log.w(getClass().getName(), "requestBluetoothPermissions() BLUETOOTH_SCAN AND BLUETOOTH_CONNECT permissions needed => requesting them...");

                this.requestPermissions(new String[]{
                    Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT
                    }, MyActivity.REQUEST_BLUETOOTH_PERMISSIONS);
            }
        }
    }
}