How to Listen for Changes in Contact Database

how to listen for changes in Contact Database

I have deployed your example as it is and it works fine.

package com.test.contentobserver;

import android.app.Activity;
import android.database.ContentObserver;
import android.os.Bundle;
import android.provider.Contacts.People;

public class TestContentObserver extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyContentObserver contentObserver = new MyContentObserver();
getApplicationContext().getContentResolver().registerContentObserver(
ContactsContract.Contacts.CONTENT_URI,
true,
contentObserver);
}

private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}

@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d(this.class.getSimpleName(), "A change has happened");
}
}
}

Something else must be wrong...

Are you making the changes through the cursor the observer is registered with?

Check that with the Observer function deliverSelfNotifications(). (it returns false by default)

You may want to override that observer function with something like:

@Override
public boolean deliverSelfNotifications() {
return true;
}

how to listen to contacts changes in phonebook when app is terminated(Oreo)

You can use ContentObserver

Refer to this link

Use service to run in background for watching contact change

public class ContactWatchService extends Service {
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
try {
//Register contact observer
startContactObserver();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void startContactObserver(){
try{
//Registering contact observer
getApplication().getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true,new ContObserver(new Handler(),getApplicationContext()));
}catch (Exception e){
e.printStackTrace();
}
}

@Override
public void onCreate() {
// Start up the thread running the service. Note that we create a
// separate thread because the service normally runs in the process's
// main thread, which we don't want to block. We also make it
// background priority so CPU-intensive work will not disrupt our UI.
HandlerThread thread = new HandlerThread("ServiceStartArguments");
thread.start();

// Get the HandlerThread's Looper and use it for our Handler
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {

// For each start request, send a message to start a job and deliver the
// start ID so we know which request we're stopping when we finish the job
Message msg = mServiceHandler.obtainMessage();
msg.arg1 = startId;
mServiceHandler.sendMessage(msg);

// If we get killed, after returning from here, restart
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
// We don't provide binding, so return null
return null;
}
@Override
public void onDestroy() {
super.onDestroy();

try{
//Code below is commented.
//Turn it on if you want to run your service even after your app is closed
/*Intent intent=new Intent(getApplicationContext(), ContactWatchService.class);
startService(intent);*/
}catch (Exception e){
e.printStackTrace();
}
}
}

Register this as service in manifest

 <service
android:name=".service.syncAdapter.ContactWatchService"
android:enabled="true"
android:exported="false" />

ContactObserver

public class ContObserver extends ContentObserver {

Context context;


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

contactAdded(selfChange);
}

public void contactAdded(boolean selfChange) {
if (!selfChange) {
try {
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.READ_CONTACTS)
== PackageManager.PERMISSION_GRANTED) {
ContentResolver cr = context.getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
//moving cursor to last position
//to get last element added
cursor.moveToLast();
String contactName = null, photo = null, contactNumber = null;
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
if (pCur != null) {
pCur.moveToFirst();
contactNumber = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactName = pCur.getString(pCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

//here you will get your contact information


}
pCur.close();
}
cursor.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

}

Do not forget to add this in your manifest

 <uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />

finally start service

startService(new Intent(getBaseContext(), ContactWatchService.class));

How to listening contact changes in the phone book like adding a new contact,updating,deleting

Use ContentResolver

class MyObserver extends ContentObserver {
// left blank below constructor for this Contact observer example to work
// or if you want to make this work using Handler then change below registering //line
public MyObserver(Handler handler) {
super(handler);
}

@Override
public void onChange(boolean selfChange) {
this.onChange(selfChange, null);
Log.e("", "~~~~~~" + selfChange);
// Override this method to listen to any changes
}

@Override
public void onChange(boolean selfChange, Uri uri) {
//On Contact add/delete this method is fired
}
}

Register Observer like this

getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI, true, new MyObserver());

Tutorial available here



Related Topics



Leave a reply



Submit