我正在Android上构建一个音乐播放器应用,但我无法快速加载设备上的歌曲列表。它在大约6.8-7秒内加载577首歌曲,这太长了。有什么提示吗?
我正在尝试获取以下信息: 曲
这是我目前的算法:
public static ArrayList<Song> getSongList(Activity activity, String artistBound, Album albumBound) {
long start = System.currentTimeMillis();
ArrayList<Song> songList = new ArrayList<>();
ContentResolver musicResolver = activity.getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
int albumIdColumn = musicCursor.getColumnIndex
(MediaStore.Audio.Media.ALBUM_ID);
int ringColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.IS_RINGTONE);
int notifColumn = musicCursor.getColumnIndex(MediaStore.Audio.Media.IS_NOTIFICATION);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
Artist thisArtist = new Artist(musicCursor.getString(artistColumn));
if(artistBound != null && !thisArtist.getName().equals(artistBound)) continue;
long albumId = musicCursor.getLong(albumIdColumn);
Cursor albumCursor = activity.getContentResolver().query(
MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Audio.Albums.ALBUM_ART, MediaStore.Audio.Albums.ALBUM},
MediaStore.Audio.Albums._ID + " = ?",
new String[]{Long.toString(albumId)},
null
);
boolean queryResult = albumCursor.moveToFirst();
String albumCover = null;
String albumName = null;
Album album = null;
if (queryResult) {
albumCover = albumCursor.getString(0);
albumName = albumCursor.getString(1);
album = new Album(albumName, albumCover);
}
albumCursor.close();
if(musicCursor.getInt(ringColumn) > 0 || musicCursor.getInt(notifColumn) > 0) {
} else {
if(albumBound == null || albumBound.getName().equals(album.getName())) {
songList.add(new Song(thisId, thisTitle, thisArtist, album));
}
}
}
while (musicCursor.moveToNext());
}
Collections.sort(songList);
Log.d("app", "Got " + songList.size() + " songs in: " + (System.currentTimeMillis() - start) + "ms");
return songList;
}
问题是,我正在尝试在开头加载此列表,因为音乐播放器的第一个屏幕是歌曲列表。但就像现在一样,应用程序会在尝试加载时挂起。
编辑:删除搜索相册信息的代码使其运行速度极快。如何优化专辑信息搜索?
答案 0 :(得分:2)
其中一个解决方案是使用延迟加载方法。这个想法是你没有加载所有的条目,但是让我们说一半的数据集。在您的情况下,这将大大减少加载时间。在互联网上,您可以找到几种从服务器获取图像并显示它们的延迟加载实现。您可以通过某种方式对其进行编辑,以便从本地存储中读取歌曲。检查已接受的答案here。