由于权限被拒绝,MediaScannerConnection在Android 6上失败

时间:2015-10-14 15:45:14

标签: android-permissions android-6.0-marshmallow

我使用MediaScannerConnection调用其scanFile方法,用于将图像添加到设备库。但是在Android 6中,当我执行它时会收到这些异常:

  

E / DatabaseUtils:java.lang.SecurityException:Permission Denial:   阅读com.android.providers.media.MediaProvider uri   content:// media / external / fs_id from pid = 22984,uid = 10078需要   android.permission.READ_EXTERNAL_STORAGE或grantUriPermission()

  

E / iu.UploadsManager:java.lang.SecurityException:Permission Denial:   阅读com.android.providers.media.MediaProvider uri   content:// media / external / fs_id from pid = 22984,uid = 10078需要   android.permission.READ_EXTERNAL_STORAGE或grantUriPermission()

任何帮助?

1 个答案:

答案 0 :(得分:0)

这是处理权限的新方法的结果。您的应用现在需要获得运行时许可,并准备被拒绝。

在你的onCreate(或任何地方),你检查并可能要求许可:

            if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)) {

            // Show an expanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

        } else {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                    MY_PERMISSIONS_REQUEST_READ_MEDIA);

            // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
            // app-defined int constant. The callback method gets the
            // result of the request.
        }
    }

然后准备好接受这样的权限:

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_MEDIA: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            } else {
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
            }
            return;
        }
    }
}