android 动态权限中未调用 onReqestPermissionResult

onReqestPermissionResult not being called in android dynamic permission

我正在尝试在 运行 时调用用户启用他们的写外部存储权限。我使用了下面的代码。它显示 运行 时间权限对话框。当我点击允许或拒绝时,它不会调用 onReqestPermissionResult(回调方法)方法。

我必须为此做什么?

public class PermissionCheck extends Activity {

    private static final String TAG = "PermissionCheck";

    private Fragment mFragment;
    private Activity mActivity;

    public PermissionCheck(Fragment fragment){
        mFragment = fragment;
        mActivity = fragment.getActivity();
    }

    public boolean isStoragePermissionGranted() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (PackageManager.PERMISSION_GRANTED == ContextCompat.checkSelfPermission(mActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                return true;
            } else {
                ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                return false;
            }
        }
        else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
            Log.v(TAG,"Permission: "+permissions[0]+ "was "+grantResults[0]);
        }
    }
}

替换:

ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

有:

 ActivityCompat.requestPermissions(PermissionCheck.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

并将 onRequestPermissionsResult() 替换为:

@Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1: {
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  Toast.makeText(getActivity(), "Permission is granted", Toast.LENGTH_LONG).show();

                } else {
                    Toast.makeText(getActivity(), "Please give your permission.", Toast.LENGTH_LONG).show();
                }
                break;
            }
        }
    }

您正在 requestPermissions 中传递另一个 activity 的实例,因此 onRequestPermissionResult 在您的 mActivity 中调用,而不是在 PermissionCheck 中调用。尝试将 requestPermissions 更改为:

ActivityCompat.requestPermissions(PermissionCheck.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);