androidcontentobserver

Stop Android ContentObserver From Being Registered Multiple Times


For some reason my android ContentObserver is being registered multiple times. The ContentObserver is defined as an inner class in my main Activity. It is then instantiated and registered in my onCreate() method.

I think that onCreate() is being called multiple times, as well as my main Activity in general being instantiated multiple times. To prevent this, I've tried adding a launchMode to my Android Manifest, but it doesn't seem to have worked:

<activity android:name=".MainActivity"
    android:label="@string/app_name"
    android:launchMode="singleInstance">

I've also tried unregistering Oberservers before registering in my onCreate, but I think because it's a new instance of my main Activity, it doesn't do anything.

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    this.contentResolver = this.getApplicationContext().getContentResolver();
    this.myObserver = new MyObserver(this.contentResolver);

    this.contentResolver.unregisterContentObserver(this.myObserver);
    this.contentResolver.registerContentObserver(MainActivity.myObserveUri, true, this.myObserver);
}

private class MyObserver extends ContentObserver {
    public MyObserver(ContentResolver contentResolver) {
        super(null);
        //My Code
    }
}

Any ideas for how I can prevent this from happening? I also have a runnable and a handler created in my main Activity that I have set to run periodically, which is experiencing the same problem. Ideally, a fix would solve that problem as well. I'm pretty sure the underlying issue is that my main Activity is being instantiated more than once, but since launchMode didn't fix it I'm not sure where to turn next.

Any help is greatly appreciated. Thanks


Solution

  • You need to grasp the underlying issue, which is the Android Activity lifecycle Then you could tackle some of this with Singletons if needed (which I doubt).