Android:Recently Added songs list using media store
I am working on simple audio media player. I am using media store to get information of all songs stored on the sdcard. So far So good. Everything is w开发者_如何学编程orking fine.
But I am stuck now. How can I get last added (recently added) songs using media store?
Regards, Niral
This is from the source of the Default Music Player in Android 2.3
private void playRecentlyAdded() {
// do a query for all songs added in the last X weeks
int X = MusicUtils.getIntPref(this, "numweeks", 2) * (3600 * 24 * 7);
final String[] ccols = new String[] { MediaStore.Audio.Media._ID};
String where = MediaStore.MediaColumns.DATE_ADDED + ">" + (System.currentTimeMillis() / 1000 - X);
Cursor cursor = MusicUtils.query(this, MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
ccols, where, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor == null) {
// Todo: show a message
return;
}
try {
int len = cursor.getCount();
long [] list = new long[len];
for (int i = 0; i < len; i++) {
cursor.moveToNext();
list[i] = cursor.getLong(0);
}
MusicUtils.playAll(this, list, 0);
} catch (SQLiteException ex) {
} finally {
cursor.close();
}
}
I'm not sure if this is what you are looking for, but when I looked up at the default android music player source, i found out that there is a "recently added" playlist in media store. Its id in MediaStore.Audio.Playlists is -1.
EDIT:
After further research, I found out that -1 is just a value to indicate that it does not exist on the Playlist table. You may use the following solution instead:
Upon querying MediaStore.Audio.Media, add this to your where clause condition:
MediaStore.Audio.Media.DATE_ADDED + ">" + (System.currentTimeMillis() / 1000 - NUM_OF_DAYS);
NUM_OF_DAYS refers to how old your audio file is stored in your SD card.
Take Note: query from MediaStore.Audio.Media, not MediaStore.Audio.Playlist.
In your custom list that you maintain add one more integer field 'dateAdded' and to access that use
int dateAddedIndex = internalContentCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED);
if (dateAddedIndex != -1) {
songs.setDateAdded(externalContentCursor.getInt(externalContentCursor.getColumnIndex(MediaStore.Audio.Media.DATE_ADDED)));
}
After getting this sort the list according to the time they were added
public static List<Songs> getTopRecentAdded(List<Songs> list) {
Collections.sort(list, new Comparator<Songs>() {
@Override
public int compare(Songs left, Songs right) {
return left.getDateAdded() - right.getDateAdded();
}
});
Collections.reverse(list);
return list;
}
This will return the list which contain song at first which was added last.
精彩评论