I'm just trying to understand android services and content observer.
So, I tried a program in which my activity starts the service, and in the service I register in the CONTACTS URI to receive notifications when changes to db contacts change.
I rum my program, and I see that this service extends to applications → running services. Now I am trying to add a contact, and my observer is notified. If I edit the contact again, it will not receive a notification. Its only the first time after the launch of my program, if I edit the contacts, the content observer receives a notification. For details, see below.
The main activity to start the service:
public class ContactChangeOberverServiceActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i("Start","Service");
startService(new Intent(this, MyService.class));
}
}
service:
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStart");
ContactObserverActivity observer = new ContactObserverActivity(new Handler());
observer.register(getApplicationContext());
return super.onStartCommand(intent, flags, startId);
}
public boolean deliverSelfNotifications() {
return true;
}
}
And the observer:
@Override
public void onChange(boolean selfChange) {
Log.e(TAG, "Onchange Called");
Intent intent = new Intent (ctx,ContactsExtractorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(intent);
}
/ TODO Auto-generated constructor stub
}
public void register(Context ctx) {
Log.e(TAG, "Registering");
this.ctx = ctx;
curval = ctx.getContentResolver().query(
ContactsContract.Contacts.CONTENT_URI, projection, null, null,
null);
curval.registerContentObserver(new ContactObserverActivity(
new Handler()));
Log.e(TAG, "Registered");
}
, . .