创建一 bean类
public class Music {
private String name;
private String path;
private String size;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
}
//使用ContentPrivade 获取本地音乐
public class MusicPath {
public List<Music> allMusic(Context context){
List<Music> list=new ArrayList<Music>();
ContentResolver cr = context.getContentResolver();
Cursor cursor=cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
while(cursor.moveToNext()){
Music music=new Music();
String name=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
String path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
String size=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
music.setName(name);
music.setPath(path);
music.setSize(size);
list.add(music);
}
return list;
}
}
Activity中的方法调用
public class MainActivity extends Activity {
private ListView lv;
private List<Music> list;
private MediaPlayer player;
private int i=-1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.lv);
list = new MusicPath().allMusic(this);
lv.setAdapter(new MyAdapter());
player = new MediaPlayer();
lvListener();
}
private void lvListener() {
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if(arg2!=i){
try {
player.reset();
player.setDataSource(list.get(arg2).getPath());
player.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
}else{
if(player.isPlaying()){
player.pause();
}else{
player.start();
}
}
i=arg2;
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
player.stop();
}
class MyAdapter extends BaseAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if(arg1==null){
arg1=View.inflate(MainActivity.this, R.layout.lv_lv, null);
TextView tv1=(TextView) arg1.findViewById(R.id.tv1);
TextView tv2=(TextView) arg1.findViewById(R.id.tv2);
tv1.setText(list.get(arg0).getName());
tv2.setText(list.get(arg0).getSize());
}
return arg1;
}
}
}