内容解析者(ContentResolver)
2018-06-12 本文已影响89人
海在路上
参考博客
使用ContentResolver调用ContentProvider提供的接口,操作数据
当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,
1. 获取ContentResolver对象
ContentResolver contentResolver = context.getContentResolver();
获取图片
mCursor = contentResolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
MediaStore.Images.Media.MIME_TYPE + "=? or "
+ MediaStore.Images.Media.MIME_TYPE + "=?",
new String[]{"image/jpeg", "image/png"},
MediaStore.Images.Media.DATE_MODIFIED);
获取视频
Uri mVideoUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
mCursor = contentResolver.query(mVideoUri, null,
MediaStore.Video.Media.MIME_TYPE + "=?",
new String[]{"video/mp4"},
MediaStore.Video.Media.DATE_MODIFIED);
根据cursor获取内容
while (mCursor.moveToNext()) {
String path = mCursor.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
long size = mCursor.getLong(mCursor
.getColumnIndex(MediaStore.Images.Media.SIZE));
String display_name = mCursor.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
String parentName = new File(path).getParentFile().getName();
读取短信
Cursor cursor = resolver.query(Uri.parse("content://sms"),new String[]{"address","date","body"},null,null,null);
while(cursor.moveToNext()) {
Log.e(TAG,cursor.getString(0) + " " + cursor.getString(1) +
" " + cursor.getString(2));
}
获取联系人信息:
Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
Uri dataUri = Uri.parse("content://com.android.contacts/data");
// 获取联系人信息
private void queryContact() {
Cursor cursor = resolver.query(uri,new String[]{"contact_id",},null,null,null);
while (cursor.moveToNext()) {
Log.e(TAG,cursor.getString(0) + " 联系人ID");
String contact_id = cursor.getString(0);
if (contact_id != null) {
Cursor dataCursor = resolver.query(dataUri, new String[] {
"mimetype", "data1" }, "raw_contact_id=?",
new String[] { contact_id }, null);
while(dataCursor.moveToNext()) {
String mimetype = dataCursor.getString(0); // 获取到mimeyType
String data1 = dataCursor.getString(1);
//String name = dataCursor.getString(3);
// 3 然后根据 mimetype类型 来区分数据类型
if ("vnd.android.cursor.item/email_v2".equals(mimetype)) {
//info.setEmail(data1);
} else if ("vnd.android.cursor.item/name".equals(mimetype)) {
//info.setName(data1);
Log.e(TAG,"data---姓名:-" + data1);
} else if ("vnd.android.cursor.item/phone_v2"
.equals(mimetype)) {
Log.e(TAG,"data---电话号码-" + data1);
//info.setPhone(data1);
}}}}}