1. 程式人生 > >Android初試--Android中的ContentProvider(3)

Android初試--Android中的ContentProvider(3)

通訊錄中的聯絡人操作
(有興趣可以檢視com.android.providers.contacts.ContactsProvider2類和android.provider.ContactsContract類)
通過ContentProvider操作通訊錄,對聯絡人資訊進行新增、刪除、修改、查詢操作
在AndroidManifest.xml新增讀寫聯絡人資訊的許可權
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
需要使用到的相關Uri:
content://com.android.contacts/contacts 操作的資料是聯絡人資訊
content://com.android.contacts/data/phones 操作的資料是聯絡人電話
content://com.android.contacts/data/emails 操作的資料是聯絡人Email
與通訊錄相關的資料庫表

\data\data\com.android.providers.contacts\databases\contact2.db   

raw_contacts表、data表

1、獲取聯絡人
//[content://com.android.contacts/contacts]
private static final Uri CONTACTS_URI = ContactsContract.Contacts.CONTENT_URI;
//[content://com.android.contacts/data/phones]
private static final Uri PHONES_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
//[content://com.android.contacts/data/emails]
private static final Uri EMAIL_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
private static final String _ID = ContactsContract.Contacts._ID;
private static final String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
private static final String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
private static final String CONTACT_ID = ContactsContract.Data.CONTACT_ID;
private static final String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String PHONE_TYPE = ContactsContract.CommonDataKinds.Phone.TYPE;
private static final String EMAIL_DATA = ContactsContract.CommonDataKinds.Email.DATA;
private static final String EMAIL_TYPE = ContactsContract.CommonDataKinds.Email.TYPE;

public void testGetContact() throws Exception{
Uri uri = ContactsContract.Contacts.CONTENT_URI;
ContentResolver contentResolver = this.getContext().getContentResolver();
Cursor cursor = contentResolver.query(uri, null, null, null, null);
while(cursor.moveToNext()){
StringBuilder sb = new StringBuilder();
String contactid = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
sb.append("contactid=").append(contactid + ",");
sb.append("displayName=").append(displayName + ",");
// 獲取手機號  
int hasPhoneNumber = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));  
if (hasPhoneNumber > 0) { 
Uri phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor phones = contentResolver.query(phoneUri, null, 
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactid, null, null);
while(phones.moveToNext()){
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int phoneType = phones.getInt(phones.getColumnIndex(PHONE_TYPE));
sb.append("phoneNumber=").append(phoneNumber + ",");
sb.append("phoneType=").append(getPhoneTypeNameById(phoneType) + ",");
}
phones.close();
}
// 獲取郵箱
Uri emailUri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor emails = contentResolver.query(emailUri, null, 
ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=" + contactid, null, null);
while(emails.moveToNext()){
String email = emails.getString(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
int emailType = emails.getInt(emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
sb.append("email=").append(email + ",");
sb.append("emailType=").append(getEmailTypeNameById(emailType) + ",");
}
emails.close();
Log.i(TAG, sb.toString());
}
cursor.close();
}
private String getPhoneTypeNameById(int typeId) {  
switch (typeId) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME: return "home";
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE: return "mobile";
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK: return "work";
default: return "none";
}
}
private String getEmailTypeNameById(int typeId) {
switch (typeId) {
case ContactsContract.CommonDataKinds.Email.TYPE_HOME: return "home";
case ContactsContract.CommonDataKinds.Email.TYPE_WORK: return "work";
case ContactsContract.CommonDataKinds.Email.TYPE_OTHER: return "other";
default: return "none";
}
}

2、儲存聯絡人
//[content://com.android.contacts/raw_contacts]
private static final Uri RAW_CONTACTS_URI = ContactsContract.RawContacts.CONTENT_URI;
//[content://com.android.contacts/data]
private static final Uri DATA_URI = ContactsContract.Data.CONTENT_URI;
private static final String ACCOUNT_TYPE = ContactsContract.RawContacts.ACCOUNT_TYPE;
private static final String ACCOUNT_NAME = ContactsContract.RawContacts.ACCOUNT_NAME;
private static final String RAW_CONTACT_ID = ContactsContract.Data.RAW_CONTACT_ID;
private static final String MIMETYPE = ContactsContract.Data.MIMETYPE;
private static final String NAME_ITEM_TYPE = ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
private static final String DISPLAY_NAME = ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME;
private static final String PHONE_ITEM_TYPE = ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
private static final String PHONE_NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String PHONE_TYPE = ContactsContract.CommonDataKinds.Phone.TYPE;
private static final int PHONE_TYPE_HOME = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
private static final int PHONE_TYPE_MOBILE = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
private static final String EMAIL_ITEM_TYPE = ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
private static final String EMAIL_DATA = ContactsContract.CommonDataKinds.Email.DATA;
private static final String EMAIL_TYPE = ContactsContract.CommonDataKinds.Email.TYPE;
private static final int EMAIL_TYPE_HOME = ContactsContract.CommonDataKinds.Email.TYPE_HOME;
private static final int EMAIL_TYPE_WORK = ContactsContract.CommonDataKinds.Email.TYPE_WORK;
/**
 * 方法一
 * @throws Exception
 */
public void testSaveContact1() throws Exception{
ContentValues values = new ContentValues();
ContentResolver resolver = getContext().getContentResolver();
Uri rawContactUri = resolver.insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
//往data表新增聯絡人姓名
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId); 
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);//內容型別
values.put(StructuredName.GIVEN_NAME, "張三");
resolver.insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
//往data表新增電話
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(Phone.NUMBER, "13800000000");
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
resolver.insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
//往data表新增電子郵件
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
values.put(Email.DATA, "[email protected]");
values.put(Email.TYPE, Email.TYPE_WORK);
resolver.insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
}
/**
 * 方法二: 批量新增,處於同一事務中
 * @throws Exception
 */
public void testSaveContact2() throws Exception{
//文件位置:reference\android\provider\ContactsContract.RawContacts.html
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
//新增空記錄
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
//文件位置:reference\android\provider\ContactsContract.Data.html
//新增聯絡人姓名
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.GIVEN_NAME, "李四")
.build());
//新增家庭座機號碼  
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, "01034567890")
.withValue(Phone.TYPE, Phone.TYPE_HOME)
.build());
//新增移動手機號碼
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, "13900000000")
.withValue(Phone.TYPE, Phone.TYPE_MOBILE)
.withValue(Phone.LABEL, "手機號")
.build());
//新增家庭電子郵件
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.DATA, "[email protected]")
.withValue(Email.TYPE, Email.TYPE_HOME)
.build());
//新增工作電子郵件
ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.DATA, "[email protected]")
.withValue(Email.TYPE, Email.TYPE_WORK)
.build());
//批量執行,返回執行結果集
ContentProviderResult[] results = this.getContext().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
for(ContentProviderResult result : results){
Log.i(TAG, result.uri.toString());
}

}

3.提取相簿中的圖片。
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);


protected void onActivityResult(int requestCode, int resultCode, Intent data) {  
super.onActivityResult(requestCode, resultCode, data);
Bitmap bm = null;
Cursor cursor = null;
ContentResolver resolver = getContentResolver();
switch (requestCode) {
case 1:
try {
// 獲取圖片的uri
Uri originalUri = data.getData();
// 獲取bitmap圖片
bm = MediaStore.Images.Media.getBitmap(resolver, originalUri);
String[] projection = { MediaStore.Images.Media.DATA };
cursor = managedQuery(originalUri, projection, null, null, null);
// 獲得使用者選擇的圖片的索引值
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
// 將游標移至開頭
cursor.moveToFirst();
// 最後根據索引值獲取圖片路徑
String path = cursor.getString(column_index);
imageUrlText.setText(path);
Log.i(TAG, path);
} catch (Exception e) {
Log.e(TAG, e.toString());
} finally {
if(cursor != null){
cursor.close();
cursor = null;
}
if(bm != null){
bm = null;
}
}
break;
default:
break;
}
}