如何获得外部SD卡的许可?

时间:2017-06-22 19:59:57

标签: android android-mediaplayer

我正在创建一个音乐播放器,我尝试从SD卡访问歌曲。但它显示了与许可相关的一些错误。如何确保授予权限。我是android的初学者。任何帮助将不胜感激。

这就是我访问歌曲的方式。

     public void getSongList(){

    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);

    if(musicCursor!=null && musicCursor.moveToFirst()){

        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);

        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        }
        while (musicCursor.moveToNext());
    }
}

我正在onCreate中对列表进行排序。

     protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //retrieve list view
    songView = (ListView)findViewById(R.id.song_list);
    //instantiate list
    songList = new ArrayList<Song>();
    //get songs from device
    getSongList();
    //sort alphabetically by title
    Collections.sort(songList, new Comparator<Song>(){
        public int compare(Song a, Song b){
            return a.getTitle().compareTo(b.getTitle());
        }
    });

即使在添加了@hasbi建议的功能后,我也遇到了同样的错误。这是我的logcat摘要。

    FATAL EXCEPTION: main
                                                                        Process: com.example.john.musicplayer, PID: 2716
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.john.musicplayer/com.example.john.musicplayer.MainActivity}: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2716, uid=10083 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                                                                            at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                                         Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/audio/media from pid=2716, uid=10083 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()
                                                                            at android.os.Parcel.readException(Parcel.java:1683)
                                                                            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:530)
                                                                            at android.content.ContentResolver.query(ContentResolver.java:472)
                                                                            at com.example.john.musicplayer.MainActivity.getSongList(MainActivity.java:147)
                                                                            at com.example.john.musicplayer.MainActivity.onCreate(MainActivity.java:63)
                                                                            at android.app.Activity.performCreate(Activity.java:6662)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707) 
                                                                            at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:154) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6077) 
                                                                            at java.lang.reflect.Method.invoke(Native Method) 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

2 个答案:

答案 0 :(得分:0)

添加

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

到您的清单文件

将此代码添加到mainactivity的oncreate函数

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

将此代码添加到主活动文件的全局区域

@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 was granted, yay! Do the
            // contacts-related task you need to do.          
        } 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;
    }

    // other 'case' lines to check for other
    // permissions this app might request
}
}`

答案 1 :(得分:0)

在logcat中,它显示权限拒绝,请清楚应用数据并重新检查。另外,再次检查@hasbi提到的代码