onRequestPermissionsResult() 未在片段中调用,尝试了我能找到的所有解决方案

onRequestPermissionsResult() not called in fragment, tried all solutions I could find

当我 运行 我的代码时,

onRequestPermissionsResult() 从未被调用。我的片段中有一个请求权限的方法:

void initiateGalleryUpload() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(getActivity(), READ_EXTERNAL_STORAGE) != PERMISSION_GRANTED) {
                if (shouldShowRequestPermissionRationale(READ_EXTERNAL_STORAGE)) {
                    new AlertDialog.Builder(getActivity())
                            .setMessage(getString(R.string.read_storage_permission_rationale))
                            .setPositiveButton("OK", (dialog, which) -> {
                                Timber.d("Requesting permissions for read external storage");
                                requestPermissions(new String[]{READ_EXTERNAL_STORAGE}, 1);
                                dialog.dismiss();
                            })
                            .setNegativeButton("Cancel", null)
                            .create()
                            .show();
                } else {
                    requestPermissions(new String[]{READ_EXTERNAL_STORAGE},
                            1);
                }
            } else {
                controller.startGalleryPick();
            }
        }
        else {
            controller.startGalleryPick();
        }

以及同一片段中覆盖 onRequestPermissionsResult 的另一个方法:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Timber.d("onRequestPermissionsResult: req code = " + " perm = " + permissions + " grant =" + grantResults);

    switch (requestCode) {
        // 1 = "Read external storage" allowed when gallery selected
        case 1: {
            if (grantResults.length > 0 && grantResults[0] == PERMISSION_GRANTED) {
                Timber.d("Call controller.startGalleryPick()");
                controller.startGalleryPick();
            }
        }
        break;

我已阅读但不适用于我的情况的常见错误:

权限对话框按预期出现,我可以 select "OK"。

非常感谢您对此提供的帮助,因为我浏览了十几个 Whosebug 帖子都无济于事。如果有人需要,请完成代码 here

在您的 activity-level onRequestPermissionsResult() 中,处理 activity.

发出的任何权限请求

如果 requestCode 与 activity 请求的不匹配(例如,在 switchdefault 分支中),链接到超类(super.onRequestPermissionsResult(requestCode, permissions, grantResults);).如果您不这样做,对于 fragment-initiated 个请求,可能会阻止 FragmentActivity 将结果路由到片段。