因为Android M权限问题导致的"Permission Denial: reading com.android.providers.media.MediaProvider"解决办法

程序出错报告

在模拟器上调试程序,出错代码如下:

Cursor cur = context.getContentResolver().query(        
    MediaStore.Audio.Media.INTERNAL_CONTENT_URI,
    new String[] { MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ARTIST,
                        MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA }, null, null, null);

AndroidManifest.xml已经添加了如下权限.

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

但是有如下错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{io.github.oncealong.yplayer/io.github.oncealong.yplayer.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=8520, uid=10058 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=8520, uid=10058 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()

程序出错原因

最后查明是因为API过高权限访问有修改, 在API级别>=23时, 权限访问被分为三个级别, 分别为”PROTECTION_NORMAL, PROTECTION_DANGEROUS, 和PROTECTION_SIGNATURE(还有两个标志可以和SIGNATURE联合使用才有意义)”. PROTECTION_NORMAL是普通权限, 通过manifest文件在安装时被授予. PROTECTION_SIGNATURE是签名权限, 通过”检查manifest和app签名是否匹配app中声明的权限”在安装时授予. 对于 PROTECTION_DANGEROUS, 不仅需要在manifest中声明, 还需要在运行时通过requestPermissions获得, 也就是弹出来一个个对话框, 让用户确认是否授予app这些权限.
这些是常见PROTECTION_DANGEROUS权限, 如果你在程序中使用了, 那么在API>=23, 很可能会不正常工作.
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
ADD_VOICEMAIL
BODY_SENSORS
CALL_PHONE
CAMERA
GET_ACCOUNTS
PROCESS_OUTGOING_CALLS
READ_CALENDAR
READ_CALL_LOG
READ_CELL_BROADCASTS
READ_CONTACTS
READ_EXTERNAL_STORAGE
READ_PHONE_STATE
READ_SMS
RECEIVE_MMS
RECEIVE_SMS
RECEIVE_WAP_PUSH
RECORD_AUDIO
SEND_SMS
USE_SIP
WRITE_CALENDAR
WRITE_CALL_LOG WRITE_CONTACTS
WRITE_EXTERNAL_STORAGE

一篇讲解Android M最新的运行时权限的文章.
[http://jijiaxin89.com/2015/08/30/Android-s-Runtime-Permission/]

错误解决办法

最后解决办法: 使用PermissionsDispatcher库,这里封装了常用操作.github地址: https://github.com/hotchemi/PermissionsDispatcher.

简易使用方法:
1. 在build.gradle(Project)中的buildscript.dependecies添加:

 dependencies {
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
    }

2. 在build.gradle(Module)中紧挨着

apply plugin: 'com.android.application'

添加

apply plugin: 'android-apt'

然后在 dependencies中添加如下内容,其中2.1.2代表版本.

compile "com.github.hotchemi:permissionsdispatcher:2.1.2"
apt "com.github.hotchemi:permissionsdispatcher-processor:2.1.2"

整体看起来就像这样,带有**的表示需要添加的:

apply plugin: 'com.android.application'
**apply plugin: 'android-apt'**

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "io.github.oncealong.yplayer"
        minSdkVersion 14
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:+'
    **compile "com.github.hotchemi:permissionsdispatcher:2.1.2"** 
    **apt "com.github.hotchemi:permissionsdispatcher-processor:2.1.2"**
}

3. 在需要权限的类上加上@RuntimePermissions注解, 在需要权限的方法上加上@NeedsPermission, 需要权限的方法不能是private, PermissionsDispatcher不是使用的反射, 而是使用的委托的方式. 这两个注解是必须要有的,如下:

@RuntimePermissions
public class MainActivity extends AppCompatActivity {
    ...
    @NeedsPermission(Manifest.permission.CAMERA)
    void showCamera() {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.sample_content_fragment, CameraPreviewFragment.newInstance())
                .addToBackStack("camera")
                .commitAllowingStateLoss();
    }
    ...
}

4. build一下, 会自动生成一个叫MainActivityPermissionsDispatcher的类, 所有需要权限的操作都会委托给这个类. 然后在activity的onRequestPermissionsResult方法中将操作委托给MainActivityPermissionsDispatcher.onRequestPermissionsResult方法.

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    // NOTE: delegate the permission handling to generated method
    MainActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
}

搞定收工, 如果你感觉这种简单还在接受范围内. 可以去github主页看下.

发布了111 篇原创文章 · 获赞 124 · 访问量 53万+
展开阅读全文

android大神过来看看我的错误,刚学android不会看

08-02

08-02 19:31:44.213 32733-474/com.example.lenovo.push E/AndroidRuntime: FATAL EXCEPTION: ModernAsyncTask #1 Process: com.example.lenovo.push, PID: 32733 java.lang.RuntimeException: An error occurred while executing doInBackground() at android.support.v4.content.ModernAsyncTask$3.done(ModernAsyncTask.java:161) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) at java.util.concurrent.FutureTask.setException(FutureTask.java:223) at java.util.concurrent.FutureTask.run(FutureTask.java:242) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) at java.lang.Thread.run(Thread.java:762) Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=32733, uid=10358 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission() at android.os.Parcel.readException(Parcel.java:1693) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:183) at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135) at android.content.ContentProviderProxy.query(ContentProviderNative.java:421) at android.content.ContentResolver.query(ContentResolver.java:536) at android.support.v4.content.ContentResolverCompatJellybean.query(ContentResolverCompatJellybean.java:33) at android.support.v4.content.ContentResolverCompat$ContentResolverCompatImplJB.query(ContentResolverCompat.java:57) at android.support.v4.content.ContentResolverCompat.query(ContentResolverCompat.java:125) at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:59) at android.support.v4.content.CursorLoader.loadInBackground(CursorLoader.java:37) at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:302) at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:57) at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:45) at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:138) at java.util.concurrent.FutureTask.run(FutureTask.java:237) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)  at java.lang.Thread.run(Thread.java:762)  问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览