[英]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.