Android: content observer's "onChange()" method is called multiple times

Vivek picture Vivek · May 17, 2011 · Viewed 10.3k times · Source

I am using a content observer for content://sms. I am writing all the messages to a text file in SD card. But the onChange() method in the content observer is called multiple times and the same message is written multiple times to the text file. How to avoid this? Also I want to know if having the content observer will slow down the phone.

Answer

garmax1 picture garmax1 · Jun 7, 2011

You need to override deliverSelfNotifications() to return true.

class ObserverSms extends ContentObserver {
private Context mContext;

public ObserverSms(Context context, Handler handler) {
    super(handler);
    mContext = context;
}

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

@Override
public void onChange(boolean selfChange) {
    super.onChange(selfChange);
    MyLog.logDebugInConsole(TAG, "Sms Database Changed");
}
}