从MediaStore中检索最近的歌曲

时间:2016-05-05 14:00:12

标签: java android mediastore

经过一番研究,我仍然没有弄清楚如何在过去7天内查询歌曲。目前,这就是我试图检索歌曲的方式,但似乎总是返回空白。

public void displayRecentSongs() {

    //retrieve song info
    ContentResolver musicResolver = getActivity().getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    String where = MediaStore.Audio.Media.DATE_ADDED + ">" + (System.currentTimeMillis() / 1000 - 7);
    Cursor musicCursor = musicResolver.query(musicUri, null, where, null, null);

    if(musicCursor!=null && musicCursor.moveToFirst()){
        //get columns
        int idColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media._ID);
        int titleColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.TITLE);
        int artistColumn = musicCursor.getColumnIndex
                (android.provider.MediaStore.Audio.Media.ARTIST);
        int pathColumn = musicCursor.getColumnIndex
                (MediaStore.Audio.Media.DATA);
        //add songs to list
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            String thisPath = musicCursor.getString(pathColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist, null, thisPath));
        }
        while (musicCursor.moveToNext());
    }
    musicCursor.close();

}

注意:我已经对它进行了测试,以便仔细检查它是否会查询我在上周内下载的歌曲,但无济于事。

1 个答案:

答案 0 :(得分:0)

System.currentTimeMillis() / 1000 - 7是现在的七秒钟,以自Unix时代以来的秒数表示。

System.currentTimeMillis() / 1000 - 7*60*60*24将在七天前出现,以自Unix时代以来的秒数表示。您应该能够从7*60*60*24TimeUnit?)获得TimeUnit.SECONDS.convert(7, TimeUnit.DAYS)计算,但我没有尝试过,我对the TimeUnit documentation感到有些困惑。< / p>