APP申请权限

写了一个Demo列出并播放本地的视频文件,但运行时发现/storage/emulated/0目录下面空空如也,没有任何目录和文件。颇费周折,才晓得是没有获取READ_EXTERNAL_STORAGE权限导致的。

原来从Android 6.0开始,APP不仅需要在AndroidManifest.xml声明其所需的permission,还需要在源码中显式申请权限(会弹出一个dialog,询问用户是否授予权限),否则系统不予授权。

申请权限的示例源码如下:

private static final int CODE_FOR_READ_PERMISSION = 100;

/**
 * Beginning with Android 6.0 (API level 23), developers declare that your app
 * needs a permission by listing the permission in the app manifest, and then
 * requesting that the user approve each permission at runtime.
 */
private void requestReadPermission() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CODE_FOR_READ_PERMISSION);
        }
    }
}

注意,CODE_FOR_READ_PERMISSION是一个本地定义的常量。

参考链接

  • Request permissions at runtime appropriately (in Android 6.0+)
  • Request App Permissions

你可能感兴趣的:(Android)