MediaStore中定义了一系列的数据表格,通过ContentResolver提供的查询接口,我们可以得到各种需要的媒体信息。通过以下两个URI可以扫描设备外部和内部的媒体文件 。Android系统提供了MediaProvider,MediaStore, MediaScanner 接口,通过Content Provider的方式提供给用户。以下是一个简单的例子:(注意,项目使用AndroidAnnotation框架)
package com.example.testaa;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.TextView;
/*
*@author: ZhengHaibo
*web: http://blog.csdn.net/nuptboyzhb
*mail: zhb931706659@126.com
*2014-4-15 Nanjing,njupt,China
*/
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
@ViewById
Button getImage;
@ViewById
Button getVideo;
@ViewById
Button getAudio;
@ViewById
TextView myTextView;
/**
* 加载完View之后进行的处理
*/
@AfterViews
void afterViewProcess() {
}
/**
* 获取图像列表
*/
@Click
void getImage() {
String[] projection = { MediaStore.Images.Media._ID,
MediaStore.Images.Media.DISPLAY_NAME,
MediaStore.Images.Media.DATA };
String orderBy = MediaStore.Images.Media.DISPLAY_NAME;
Uri uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
getContentProvider(uri,projection, orderBy);
}
/**
* 获取视频列表
*/
@Click
void getVideo() {
// TODO Auto-generated method stub
String []projection = { MediaStore.Video.Media._ID,
MediaStore.Video.Media.DISPLAY_NAME,
MediaStore.Video.Media.DATA};
String orderBy = MediaStore.Video.Media.DISPLAY_NAME;
Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
getContentProvider(uri,projection, orderBy);
}
/**
* 获取音频列表
*/
@Click
void getAudio() {
String []projection = { MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.DISPLAY_NAME,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.SIZE};
String orderBy = MediaStore.Audio.Media.DISPLAY_NAME;
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
getContentProvider(uri,projection, orderBy);
}
/**
* 获取ContentProvider
* @param projection
* @param orderBy
*/
public void getContentProvider(Uri uri,String[] projection, String orderBy) {
// TODO Auto-generated method stub
List<HashMap<String, String>> listImage = new ArrayList<HashMap<String, String>>();
Cursor cursor = getContentResolver().query(uri, projection, null,
null, orderBy);
if (null == cursor) {
return;
}
while (cursor.moveToNext()) {
HashMap<String, String> map = new HashMap<String, String>();
for(int i=0;i<projection.length;i++){
map.put(projection[i], cursor.getString(i));
System.out.println(projection[i]+":"+cursor.getString(i));
}
listImage.add(map);
}
myTextView.setText(listImage.toString());
}}
唯一的参数改变是mediastore后面那个包名的不同,分别是images,video,audio,这些包后面的包名都是media