Android: requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

1.最近在SDK6.0开发项目组遇到一个这样的问题:requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

2.原因:从6.0(api 23)开始, android采用了Runtime permission request, 即在运行时请求权限,而不是在编译的时候,即使在manifest.xml里面添加了权限也要在运行时请求。

   但不是所有的permission都要Runtime request,涉及到资源文件请求时就会用到Runtime request,比如获取位置信息, content provider获取media的情况。

3.解决方法:

a) 首先确认在manefist里面添加了READ_EXTERNAL_STORAGE权限。

        b) 在代码中实现Runtime request:

        

@SuppressLint("NewApi")
private void requestReadExternalPermission() {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "READ permission IS NOT granted...");
        
        if (shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) {
            
            Log.d(TAG, "11111111111111");
        } else {
            // 0 是自己定义的请求coude
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
            Log.d(TAG, "222222222222");
        }
    } else {
        Log.d(TAG, "READ permission is granted...");
    }
}


    c)处理请求:
    
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    Log.d(TAG, "requestCode=" + requestCode + "; --->" + permissions.toString()
            + "; grantResult=" + grantResults.toString());
    switch (requestCode) {
        case 0: {
            
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted
                // request successfully, handle you transactions

            } else {

                // permission denied
                // request failed
            }
            
            return;
        }
        default:
            break;

    }
}

你可能感兴趣的:(Android)