问题
I'm working on a MP3 application in which I'd like to index the files on my SDCard. What is the best way to do it?
My Idea. Search for files when the application is started for the first time and register a broadcast receiver for the SDCard state change intents and search for the files whenever the intent is broadcasted.
But in this case the ANR would show up if my broadcast receiver doesn't return within 10 seconds.
Looking for better and failsafe ideas. Thanks.
回答1:
Agree with Chris, MediaScanner finds music for you, populating the MediaStore database. Here's some code to look up a music entry:
final Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final String[] cursor_cols = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.TITLE,
};
final String where = MediaStore.Audio.Media.IS_MUSIC + "=1";
final Cursor cursor = getContentResolver().query(uri, cursor_cols, where, null, null);
cursor.moveToNext();
final String artist = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
final String album = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
final String track = cursor.getString(_cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
doSomethingInteresting(artist, album, track);
The "data" field contains a handle you can use with MediaPlayer.
回答2:
To avoid the ANR you need to do the search outside the UI thread. As SD cards can be big, you probably want to do it in a service rather than in your foreground activity so that the user can use their device for other things while the search is ongoing.
But android already finds and indexes supported media files, so you should see if you can leverage the built-in MediaScanner stuff.
来源:https://stackoverflow.com/questions/4369325/android-finding-files-on-the-sdcard