Start a service and register the ContentObserver to this server
Here is a sample code I did which will listen to any changes in the Contacts.CONTENT_URI and notify the user
This is the service
public class ContactObserverService extends Service implements ContactObserver.OnUpdate {
private ContactObserver contactObserver ;
public ContactObserverService() {
}
@Override
public void onCreate(){
super.onCreate();
contactObserver = new ContactObserver(this);
Toast.makeText(this,"Service Started",Toast.LENGTH_SHORT).show();
this.getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI,false,contactObserver);
}
@Override
public void onDestroy() {
if( contactObserver !=null )
{
this.getContentResolver().unregisterContentObserver(contactObserver);
}
super.onDestroy();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// The service is starting, due to a call to startService()
return START_STICKY;
}
@Override
public void onUpdate(Uri uri) {
NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setContentTitle("Contact Update Notifier")
.setContentText(uri.getQuery())
.setSmallIcon(R.drawable.images);
NotificationManager manager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
The ContentObserver class is
public class ContactObserver extends ContentObserver {
private OnUpdate onUpdate;
public interface OnUpdate{
void onUpdate(Uri uri);
}
public ContactObserver(OnUpdate onUpdate) {
super(new Handler());
this.onUpdate = onUpdate;
}
@Override
public void onChange(boolean selfChange) {
this.onChange(selfChange, null);
}
@Override
public void onChange(boolean selfChange, Uri uri) {
// this is NOT UI thread, this is a BACKGROUND thread
uri.getQueryParameterNames();
onUpdate.onUpdate(uri);
}
}