Android的READ_EXTERNAL_STORAGE权限


84

我正在尝试访问用户设备上的媒体文件(音乐)以进行播放;一个简单的“ hello world”音乐播放器应用。

我遵循了一些教程,它们基本上给出了相同的代码。但这是行不通的。它不断崩溃,并告诉我:

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

现在,这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest
    xmlns:android="http://schemas.android.com/apk/res/android"
    package="slimsimapps.troff" >

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


<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>

这是我的Java方法:

public void initialize() {
    ContentResolver contentResolver = getContentResolver();
    Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor cursor = contentResolver.query(uri, null, null, null, null);
    if (cursor == null) {
        // query failed, handle error.
    } else if (!cursor.moveToFirst()) {
        // no media on the device
    } else {
        do {
            addSongToXML(cursor);
        } while (cursor.moveToNext());
    }
}

我努力了:

要将其放在清单文件中的不同位置:

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

要在读取外部存储权限下添加android:maxSdkVersion:

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

要将其放在清单/应用程序/活动标签中:

android:exported=“true

将uri和cursro之间的grantUriPremission放在javamethod中:

grantUriPermission(null, uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);

要使用它,它不会崩溃,但是光标变为空:

uri = MediaStore.Audio.Media.getContentUri("EXTERNAL_CONTENT_URI”);

要使用INTERNAL内容uri,它可以按预期工作,但是只能给出“ OS声音”,例如快门声,电池电量低,单击按钮等:

uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;

请帮助,这不是我所知道的难题,但我感觉自己像是一个初学者!

我已阅读并尝试过(或认为它们不适用于我的问题):

堆栈跟踪:

09-08 06:59:36.619    2009-2009/slimsimapps.troff D/AndroidRuntime﹕ Shutting down VM
    --------- beginning of crash
09-08 06:59:36.619    2009-2009/slimsimapps.troff E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: slimsimapps.troff, PID: 2009
    java.lang.IllegalStateException: Could not execute method for android:onClick
            at android.view.View$DeclaredOnClickListener.onClick(View.java:4452)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Method.invoke(Native Method)
            at android.view.View$DeclaredOnClickListener.onClick(View.java:4447)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2009, uid=10059 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
            at android.os.Parcel.readException(Parcel.java:1599)
            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:491)
            at android.content.ContentResolver.query(ContentResolver.java:434)
            at slimsimapps.troff.MainActivity.initialize(MainActivity.java:106)
            at slimsimapps.troff.MainActivity.InitializeExternal(MainActivity.java:80)
            at java.lang.reflect.Method.invoke(Native Method)
            at android.view.View$DeclaredOnClickListener.onClick(View.java:4447)
            at android.view.View.performClick(View.java:5198)
            at android.view.View$PerformClick.run(View.java:21147)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:148)
            at android.app.ActivityThread.main(ActivityThread.java:5417)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
    --------- beginning of system

如果您未在清单<uses-permission android:name =“ android.permission.READ_EXTERNAL_STORAGE” />中未给出此行,就会显示该错误,您是否正在尝试读取受某些其他应用保护的文件?
sunil sunny

您在哪个api级别上尝试此操作?
Sharp Edge

您是否尝试过清理项目。?
sunil sunny

@sunilsunny我不是要读取受保护的som文件,无论如何我也不知道,只是一个简单的媒体播放器。是的,我曾尝试清洗它,我试图重新启动计算机时,我试图生成APK签署并发布到Google Play和访问它作为一个测试人员,没有运气....
斯利姆辛

@尖锐的边缘 ; 我的AVD是标准的Nexus 5,API 23.我的Gradle模块有:compileSdkVersion 23 buildToolsVersion “23.0.0”的minSdkVersion 14 targetSdkVersion 23,所以我会说23
斯利姆辛

Answers:


90

您有两种解决方案。快速的方法是将targetApi降低到22(build.gradle文件)。第二是使用新的精彩的许可请求模型:

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

    // Should we show an explanation?
    if (shouldShowRequestPermissionRationale(
            Manifest.permission.READ_EXTERNAL_STORAGE)) {
        // Explain to the user why we need to read the contacts
    }

    requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

    // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
    // app-defined int constant that should be quite unique

    return;
}

在此处找到的代码段:https//developer.android.com/training/permissions/requesting.html

解决方案2:如果不起作用,请尝试以下操作:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
        REQUEST_PERMISSION);

return;

}

然后在回调中

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION) {
    if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // Permission granted.
    } else {
        // User refused to grant permission.
    }
}
}

那是从评论。谢谢


1
当然是!Google在最新的Android中引入了新的权限模型!谢谢,我会尽快对此进行测试并将其标记为正确!(我开始认为这已经被忘记了!)
Slim Sim

1
所请求的许可应为READ_EXTERNAL_STORAGE。喜欢这个答案
maclir

将!= PackageManager.READ_EXTERNAL_STORAGE换成!= PackageManager.PERMISSION_GRANTED
Renascienza

1
@Renascienza,是的,您是对的。有人用错误的方式编辑了这个答案。
piotrpo

2
什么是MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE?
独奏

17

您必须在运行时请求许可:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
        && ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            REQUEST_PERMISSION);
    dialog.dismiss();
    return;
}

在下面的回调中,您可以毫无问题地访问存储。

@Override
public void onRequestPermissionsResult(final int requestCode, @NonNull final String[] permissions, @NonNull final int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission granted.
        } else {
            // User refused to grant permission.
        }
    }
}

7

步骤1:在android manifest.xml上添加权限

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

步骤2:onCreate()方法

int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_READ_MEDIA);
    } else {
        readDataExternal();
    }

第三步:重写onRequestPermissionsResult方法以获取回调

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_READ_MEDIA:
            if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                readDataExternal();
            }
            break;

        default:
            break;
    }
}

注意:readDataExternal()是从外部存储获取数据的方法。

谢谢。


1
我认为您在此处放错了所需的权限:READ_EXTERNAL_STORAGE。
Renascienza

4

我也有类似的错误日志,这就是我所做的-

  1. 在onCreate方法中,我们请求一个用于检查权限的对话框

    ActivityCompat.requestPermissions(MainActivity.this,
    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
    
  2. 检查结果的方法

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission granted and now can proceed
             mymethod(); //a sample method called
    
            } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        // add other cases for more permissions
        }
    }
    

请求运行时权限的官方文档


1
我用过它,它工作得很好,是否可以在所有android设备上正常工作?
Mahdi Hraybi '17

1

您的问题是否已解决?您的目标SDK是什么?尝试添加android;maxSDKVersion="21"<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />


使用Cordova为我工作,方法是将AndroidManifest.xml中的最大SDK版本设置为22(而不是23)
George Kagan

0

http://developer.android.com/reference/android/provider/MediaStore.Audio.AudioColumns.html

尝试换线 contentResolver.query

//change it to the columns you need
String[] columns = new String[]{MediaStore.Audio.AudioColumns.DATA}; 
Cursor cursor = contentResolver.query(uri, columns, null, null, null);

公共静态最终字符串MEDIA_CONTENT_CONTROL

由于媒体使用的私密性,不适合第三方应用程序使用

http://developer.android.com/reference/android/Manifest.permission.html#MEDIA_CONTENT_CONTROL

尝试删除第<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>一个并重试?


谢谢,我尝试了您的建议,但是它在同一地点崩溃了……我使用的是Mac,这可能是个问题吗?
Slim Sim 2015年

更新,尝试删除<uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL"/>并尝试?因为您的应用不允许许可请求,这可能会导致奇怪的行为
Derek Fung

谢谢,我试图删除该权限,但它在同一位置以相同的错误崩溃...
Slim Sim

0

请检查以下代码,使用它您可以从sdcard找到所有音乐文件:

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_animations);
    getAllSongsFromSDCARD();

}

public void getAllSongsFromSDCARD() {
    String[] STAR = { "*" };
    Cursor cursor;
    Uri allsongsuri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String selection = MediaStore.Audio.Media.IS_MUSIC + " != 0";

    cursor = managedQuery(allsongsuri, STAR, selection, null, null);

    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                String song_name = cursor
                        .getString(cursor
                                .getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
                int song_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media._ID));

                String fullpath = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.DATA));

                String album_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM));
                int album_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));

                String artist_name = cursor.getString(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST));
                int artist_id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Audio.Media.ARTIST_ID));
                System.out.println("sonng name"+fullpath);
            } while (cursor.moveToNext());

        }
        cursor.close();
    }
}


}

我还在AndroidManifest.xml文件中添加了以下行,如下所示:

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="17" />

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

谢谢,我之前尝试过类似的操作,但是我尝试了您的代码,它在“ cursor = managedQuery(allsongsuri,STAR,selection,null,null);”上崩溃,与以前相同。顺便说说; 不推荐使用managedQuery,但是如果我将其更改为具有相同输入参数的“ contentResolver.query”,它仍然会崩溃……
Slim Sim

嗨,我能够使用上述代码获取所有sdcadr歌曲。使用Android 4.2.2版设备,也可以使用5.0.2版。您在其中尝试。什么样的错误你有,请与Android版本描述
拉詹Bhavsar

我已经用堆栈跟踪更新了问题,希望能对您有所帮助。您使用Android版本是什么意思?(我正在使用apk 23)
Slim Sim

好的,让我提供完整的源代码,然后再次签出。
Rajan Bhavsar 2015年

如果您想自己进行测试,请在此处下载zip:drive.google.com/open?id=0B2AV8VRk9HUeVzFXSWVRZU9TRUk运行时,请按左初始化按钮以生成裂缝。
Slim Sim 2015年

0

除了所有答案。您也可以指定minsdk并与此注释一起应用

@TargetApi(_apiLevel_)

我用它来接受此请求,即使我的minsdk是18。它的作用是该方法仅在设备目标为“ _apilevel_”和上层设备时运行。这是我的方法:

    @TargetApi(23)
void solicitarPermisos(){

    if (ContextCompat.checkSelfPermission(this,permiso)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (shouldShowRequestPermissionRationale(
                Manifest.permission.READ_EXTERNAL_STORAGE)) {
            // Explain to the user why we need to read the contacts
        }

        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                1);

        // MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
        // app-defined int constant that should be quite unique

        return;
    }

}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.