[英]Access to the musical files in internal storage. Android
我有以下方法:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_songs);
ListView songsListView = findViewById(R.id.songList);
songsList = new ArrayList<Song>();
if (isStoragePermissionGranted()) {
getSongsList();
}
Collections.sort(songsList, new Comparator<Song>() {
@Override
public int compare(Song o1, Song o2) {
return o1.getTitle().compareTo(o2.getTitle());
}
});
SongAdapter adapter = new SongAdapter(this, songsList);
songsListView.setAdapter(adapter);
}
public void getSongsList(){
ContentResolver musicResolver = getContentResolver();
Uri musicUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
@SuppressLint("Recycle")
Cursor musicCursor = musicResolver.query(musicUri,null,null,null,null);
if (musicCursor!=null && musicCursor.moveToFirst()){
int titleColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
do{
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songsList.add(new Song(thisId, thisTitle, thisArtist));
}while (musicCursor.moveToNext());
}
}
public boolean isStoragePermissionGranted() {
String TAG = this.getClass().getSimpleName();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted");
return true;
} else {
Log.v(TAG,"Permission is revoked");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted");
return true;
}
}
具有此方法的活动应按字母顺序显示内部存储中的歌曲列表。 但是当我运行程序时,我在这个活动中看不到任何东西。 当我在日志中观看时,我没有看到任何带有此活动标签的内容,但是当我在调试器中观看时,我看到该方法boolean isStoragePermissionGranted()
返回false
所以,在这种情况下,我有一个问题:如何获得从内部存储中获取音乐的许可?
您还应该检查 READ_EXTERNAL_STORAGE
public boolean isReadStoragePermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
Log.v(TAG,"Permission is granted1");
return true;
} else {
Log.v(TAG,"Permission is revoked1");
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 3);
return false;
}
}
else { //permission is automatically granted on sdk<23 upon installation
Log.v(TAG,"Permission is granted1");
return true;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.