1.查找、增加、删除、修改联系人
直接贴代码:
ContactsManager.java
package com.example.siqi.contacts;
import java.util.ArrayList;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.util.Log;
public class ContactsManager {
private ContentResolver contentResolver;
private static final String TAG = "ContactsManager";
/**
* Use a simple string represents the long.
*/
private static final String COLUMN_CONTACT_ID =
ContactsContract.Data.CONTACT_ID;
private static final String COLUMN_RAW_CONTACT_ID =
ContactsContract.Data.RAW_CONTACT_ID;
private static final String COLUMN_MIMETYPE =
ContactsContract.Data.MIMETYPE;
private static final String COLUMN_NAME =
ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME;
private static final String COLUMN_NUMBER =
ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String COLUMN_NUMBER_TYPE =
ContactsContract.CommonDataKinds.Phone.TYPE;
private static final String COLUMN_EMAIL =
ContactsContract.CommonDataKinds.Email.DATA;
private static final String COLUMN_EMAIL_TYPE =
ContactsContract.CommonDataKinds.Email.TYPE;
private static final String MIMETYPE_STRING_NAME =
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE;
private static final String MIMETYPE_STRING_PHONE =
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE;
private static final String MIMETYPE_STRING_EMAIL =
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE;
public ContactsManager(ContentResolver contentResolver) {
this.contentResolver = contentResolver;
}
/**
* Search and fill the contact information by the contact name given.
* @param contact Only the name is necessary.
*/
public Contact searchContact(String name) {
Log.w(TAG, "**search start**");
Contact contact = new Contact();
contact.setName(name);
Log.d(TAG, "search name: " + contact.getName());
String id = getContactID(contact.getName());
contact.setId(id);
if(id.equals("0")) {
Log.d(TAG, contact.getName() + " not exist. exit.");
} else {
Log.d(TAG, "find id: " + id);
//Fetch Phone Number
Cursor cursor = contentResolver.query(
android.provider.ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{COLUMN_NUMBER, COLUMN_NUMBER_TYPE},
COLUMN_CONTACT_ID + "='" + id + "'", null, null);
while(cursor.moveToNext()) {
contact.setNumber(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER)));
contact.setNumberType(cursor.getString(cursor.getColumnIndex(COLUMN_NUMBER_TYPE)));
Log.d(TAG, "find number: " + contact.getNumber());
Log.d(TAG, "find numberType: " + contact.getNumberType());
}
//cursor.close();
//Fetch email
cursor = contentResolver.query(
android.provider.ContactsContract.CommonDataKinds.Email.CONTENT_URI,
new String[]{COLUMN_EMAIL, COLUMN_EMAIL_TYPE},
COLUMN_CONTACT_ID + "='" + id + "'", n