How to know which specific contact was updated in android?

后端 未结 2 2059
遇见更好的自我
遇见更好的自我 2021-01-03 02:08

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.

相关标签:
2条回答
  • 2021-01-03 02:38

    I implemented this problem in the following way:

    During the installation of an app my local DB's Contact table is being initialized by the contacts of the given time. Then all the calls are being tracked by a CallListner : if user gets/makes calls I check if the number is in the current Phone Book of a user,if so I retrieve all contact information related to that number and update my local DB.

    0 讨论(0)
  • 2021-01-03 02:46

    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);
     }
    
    }
    
    0 讨论(0)
提交回复
热议问题