Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know which specific contact was updated in android?

I am able to get a generic notification "that there was a change to the contacts DB", but I want to know the specific record that was inserted, updated, or deleted.

I don't want to use Look-up URI concept because I don't want to set look-up URI for every contact individually. I want a generic solution that I can know when any contact is updated or deleted.

like image 987
user446366 Avatar asked May 03 '12 12:05

user446366


People also ask

How do I select and display my phone number from a contact list on Android?

Open your Contacts app and tap the Options button (three dots), and select Contacts Manager. On the next screen, tap on Contacts to display from the menu. Next, if you only want contacts with a phone number, tap on Phone.


1 Answers

You can implement an Service to watch the database status.

import android.app.Service;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.IBinder;
import android.provider.ContactsContract;

public class ContactService extends Service {

private int mContactCount;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();
    mContactCount = getContactCount();
    this.getContentResolver().registerContentObserver(
            ContactsContract.Contacts.CONTENT_URI, true, mObserver);
}

private int getContactCount() {
    Cursor cursor = null;
    try {
        cursor = getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null,
                null);
        if (cursor != null) {
            return cursor.getCount();
        } else {
            return 0;
        }
    } catch (Exception ignore) {
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    return 0;
}

private ContentObserver mObserver = new ContentObserver(new Handler()) {

    @Override
    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        final int currentCount = getContactCount();
        if (currentCount < mContactCount) {
            // DELETE HAPPEN.
        } else if (currentCount == mContactCount) {
            // UPDATE HAPPEN.
        } else {
            // INSERT HAPPEN.
        }
                    mContactCount = currentCount;
    }

};

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;
}

@Override
public void onDestroy() {
    super.onDestroy();
    getContentResolver().unregisterContentObserver(mObserver);
 }

}
like image 104
Changwei Yao Avatar answered Oct 26 '22 06:10

Changwei Yao