Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onchange function of the content observer class being called more than once

Tags:

android

I am using a contentObserver to monitor the content of the sms content provider, I have put a Log.d() tag for debugging and the tag in the logcat is being seen more than once meaning the onchange() id being called more than once, how do I prevent this from happening. I have implemented the observer in a service running in the background. Here is the code

package com.messageHider;

 import android.app.Service;
 import android.content.ContentResolver;
 import android.content.Intent;
 import android.database.ContentObserver;
 import android.database.Cursor;
 import android.net.Uri;
 import android.os.Handler;
 import android.os.IBinder;
 import android.util.Log;
 import android.widget.Toast;

 public class smsSentService extends Service {
ContentResolver contentResolver;
Uri uri=Uri.parse("content://sms/");
Handler handler;
@Override
public IBinder onBind(Intent arg0) {
    return null;
}
@Override
public void onCreate() {
    contentResolver=getContentResolver();
    contentResolver.registerContentObserver(uri, true, new contentObserver(handler));
    Log.d("SENTSERVICE", "Service created");
    super.onCreate();
}
@Override
public void onStart(Intent intent, int startId) {
    Log.d("SENTSERVICE", "Service started");
    super.onStart(intent, startId);
}
@Override
public void onDestroy() {
    super.onDestroy();
}
public class contentObserver extends ContentObserver
{
    public contentObserver(Handler handler) {
        super(handler);

    }
    @Override
    public void onChange(boolean selfChange) {
        Cursor cursor=contentResolver.query(uri, null, null, null, null);
        cursor.moveToFirst();
        String type=cursor.getString(cursor.getColumnIndex("type"));
        Log.d("THEMESSAGE", type);
        super.onChange(selfChange);
    }
}

}


like image 731
John Avatar asked Jan 24 '26 18:01

John


1 Answers

Just a recommendation: register the content observer on the onResume method and unregister it on the onPause.

like image 97
francas Avatar answered Jan 27 '26 07:01

francas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!