public static List<Song> getMusicData(Context context) {
List<Song> list = new ArrayList<Song>();
// 媒体库查询语句(写一个工具类MusicUtils)
Cursor cursor = context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,
null, MediaStore.Audio.AudioColumns.IS_MUSIC);
if (cursor != null) {
while (cursor.moveToNext()) {
Song song = new Song();
song.song = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));//歌曲名称
song.singer = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));//歌手
song.album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));//专辑名
song.path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));//歌曲路径
song.duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));//歌曲时长
song.size = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));//歌曲大小
if (song.size > 1000 * 800) {
// 注释部分是切割标题,分离出歌曲名和歌手 (本地媒体库读取的歌曲信息不规范)
if (song.song.contains("-")) {
String[] str = song.song.split("-");
song.singer = str[0];
song.song = str[1];
}
list.add(song);
}
}
// 释放资源
cursor.close();
}
return list;
}
首先获取数据库,也算自己长知识的地方。
1:MediaStore.Audio.Media.EXTERNAL_CONTENT_URI 这是什么呢?怎么用
MediaStore是android系统提供的一个多媒体数据库,专门用于存放多媒体信息的,通过ContentResolver即可对数据库进行操作。获取ContentResolver的方法是context.getContentResolver() ,使用小技巧,算是固定写法遇到特殊情况特殊处理
context.getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null,null, MediaStore.Audio.AudioColumns.IS_MUSIC);
重点:Java都是一个个类组成的,需要对一堆的同类型的变量进行操作,先创建对应的集合,然后通过switch进行遍历,在遍历的过程中创建对象,(如果在思考中出现需要new 很多的相同对象的时候,优先考虑switch,然后创建集合,然后对集合再进行操作)。集合常用ArrayList。