我已經實現了一個ContentObserver,使用這種方法,我只能夠被通知如果一個聯繫人發生變化Android如何檢測聯繫人列表已更改?
但我不知道哪個聯繫人被添加,刪除或更新?
!有什麼建議麼 ?我如何知道哪個特定聯繫人被修改?
我通過使用以下方法獲取所有聯繫人列表。
public void readContacts() {
System.out.println(" reading contact ");
String phoneNumber = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
String name = cursor.getString(cursor
.getColumnIndex(DISPLAY_NAME));
// int id =
// Integer.parseInt(cursor.getString(cursor.getColumnIndex(
// HAS_PHONE_NUMBER)));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
System.out.println(" CONTACT NAME : " + name);
Contact_Name.add(name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
phoneCursor.moveToNext();
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
System.out.println(" CONTACT number : " + phoneNumber);
phoneNumber = phoneNumber.replaceAll("\\s", "");
// phoneNumber = phoneNumber.substring(phoneNumber.length()
// - 10);
// System.err.println("Mobile no."+phoneNumber);
Contact_Number.add(phoneNumber);
phoneCursor.close();
}
output.append("\n");
}
}
}
並且我正在觀察聯繫人列表正在通過regestring並使用以下代碼進行更改。
this.getContentResolver().registerContentObserver(
ContactsContract.Contacts.CONTENT_URI, true, mObserver);
private ContentObserver mObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
final int currentCount = getContactCount();
if (currentCount < mContactCount) {
System.out.println(" Deleted contact");
} else if (currentCount == mContactCount) {
System.out.println(" upated contact");
} else {
System.out.println(" inserted contact");
}
mContactCount = currentCount;
}
};
爲什麼'mObserver'的'registerContentObserver'後的聲明? – Manu 2014-09-05 12:41:29
@Manu我已經在我的代碼中完美地聲明瞭這一點。這裏只有我在registerContentObserver – 2014-09-05 12:43:15