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);
}
}
}
Just a recommendation: register the content observer on the onResume method and unregister it on the onPause.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With