//下面实现的是内容提供者查询的系统的音乐文件我们通过适配器展示在列表上面 获得音乐文件的名称 歌者 路径
import java.util.ArrayList;
import java.util.List;
import com.example.adapter.MusicAdapter;
import com.example.bean.Music;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ListView;
public class MainActivity extends Activity{
private ListView lv;//音乐列表
private List<Music> list=new ArrayList<Music>();
private MusicAdapter adapter;//适配器
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
lv=(ListView) findViewById(R.id.lv);
ContentResolver cr=getContentResolver();
if (cr==null) {
return;
}
//获得所有的歌曲 查询所有的歌曲
Cursor cursor = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
if (cursor == null) {
return;
}
if (cursor.moveToFirst()) {
do {
Music music=new Music();
String title = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String url = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
music.setTitle(title);
music.setSinger(singer);
music.setUrl(url);
list.add(music);
} while (cursor.moveToNext());
adapter=newMusicAdapter(MainActivity.this, list);
lv.setAdapter(adapter);
}
}
//封装的utils包也实现查询音乐文件
public class MusicUtil {
public static List<Music> getList(Context context){
//查询SD卡上所有音乐文件
List<Music> list =new ArrayList<Music>();
ContentResolver resolver = context.getContentResolver();
//查询到音乐的所有信息
Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Media.DATA,MediaStore.Audio.Media.ARTIST}, null, null, null);
while(cursor.moveToNext()){
list.add(new Music(cursor.getString(0), cursor.getString(1), cursor.getString(2)));
}
return list;
}
}
//效果图展示