尽管已授予WRITE_EXTERNAL_STORAGE,但ContextCompat.checkSelfPermission返回-1

时间:2019-02-09 16:59:02

标签: java android android-manifest

在电话设置中,授予权限。装有Android 8.0的手机。

compileSdkVersion 28
minSdkVersion 16
targetSdkVersion 28

清单具有:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"  />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在我的代码中,此“ permissions”变量始终等于-1:

int permissions = ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);

2 个答案:

答案 0 :(得分:0)

从Android 6(API 23)开始,您还必须在运行时请求此权限。该视频可能会有所帮助:https://youtu.be/WGz-alwVh8A

答案 1 :(得分:0)

好,感谢Larry Schiefer的运行时权限。

考虑使用android文档:

link 1 link 2

我从链接2对该方法进行了一些更改。在执行某些操作之前,它会检查权限,并在必要时要求用户确认,否则,它将强制设置权限。

    public void requestRuntimePermission(final Context context, final String manifestPermission, final int requestCode) {

        int permissions = ContextCompat.checkSelfPermission(context, manifestPermission);
        if (permissions != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
                    manifestPermission)) {

                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(context);
                builder.setMessage("Allow access?")
                        .setCancelable(true)
                        //Cancel
                        .setNegativeButton("Yes", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        })
                        //Ok
                        .setPositiveButton("No", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                ActivityCompat.requestPermissions((Activity) context,
                                        new String[]{manifestPermission},
                                        requestCode);
                            }
                        });
                android.support.v7.app.AlertDialog alert = builder.create();
                alert.show();

            } else {
                // Permission has not been granted yet. Request it directly.
                ActivityCompat.requestPermissions((Activity) context, new String[]{manifestPermission},
                        requestCode);
            }

        }
    }

用法示例:

requestRuntimePermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE, 0);

P.S。 requestRuntimePermission中的requestCode参数可用于标识onRequestPermissionsResult回调中允许的权限。 (link 3