首页 > 解决方案 > 如何在新的 ActivityResult API (1.3.0-alpha05) 中获取权限请求?

问题描述

因此,我尝试使用新的 registerForActivityResult() 方法获得许可,并通过 .launch() 按钮单击来请求它,它似乎没有打开任何窗口来请求它。我总是在 registerForActivityResult() 中得到错误。

    // Permission to get photo from gallery, gets permission and produce boolean
private ActivityResultLauncher<String> mPermissionResult = registerForActivityResult(
        new ActivityResultContracts.RequestPermission(),
        new ActivityResultCallback<Boolean>() {
            @Override
            public void onActivityResult(Boolean result) {
                if(result) {
                    Log.e(TAG, "onActivityResult: PERMISSION GRANTED");
                } else {
                    Log.e(TAG, "onActivityResult: PERMISSION DENIED");
                }
            }
        });



        // Launch the permission window -- this is in onCreateView()
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
         mPermissionResult.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION);

        }
    });

这是我的日志:onActivityResult: PERMISSION DENIED

标签: javaandroidandroid-fragmentsandroid-permissions

解决方案


更新
这个答案有效,但我找到了一个更好的权限请求解决方案,这里没有空洞。


来自文档

在您的活动/片段中,创建此字段:

// Register the permissions callback, which handles the user's response to the
// system permissions dialog. Save the return value, an instance of
// ActivityResultLauncher, as an instance variable.
private ActivityResultLauncher<String> requestPermissionLauncher =
    registerForActivityResult(new RequestPermission(), isGranted -> {
        if (isGranted) {
            // Permission is granted. Continue the action or workflow in your
            // app.
        } else {
            // Explain to the user that the feature is unavailable because the
            // features requires a permission that the user has denied. At the
            // same time, respect the user's decision. Don't link to system
            // settings in an effort to convince the user to change their
            // decision.
        }
    });

在同一个活动/片段中的某处:

if (ContextCompat.checkSelfPermission(
        context, Manifest.permission.ACCESS_BACKGROUND_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {
    performAction(...);
} else if (shouldShowRequestPermissionRationale(...)) {
    // In an educational UI, explain to the user why your app requires this
    // permission for a specific feature to behave as expected. In this UI,
    // include a "cancel" or "no thanks" button that allows the user to
    // continue using your app without granting the permission.
    showInContextUI(...);
} else {
    // You can directly ask for the permission.
    // The registered ActivityResultCallback gets the result of this request.
    requestPermissionLauncher.launch(Manifest.permission.ACCESS_BACKGROUND_LOCATION);
}

如果您一直收到不合理的“权限被拒绝”,也许您没有在您的manifest.xml?


推荐阅读