Content class Onchange function called more than once

I use contentObserverto track content sms content provider, I put a tag Log.d()for debugging, and the tag is logcatviewed more than once, which means the identifier is onchange()as many times as I can to prevent this. I implemented an 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);
    }
}

}


+3
source share
3 answers

Only recommendation: register the content observer using the onResume method and unregister onPause.

+1
source

SMS- , SMS- , 3 , , , ?

SMS-, SMS. "-1" .

0

You need to override deliverSelfNotifications () to return true.

class contentObserver extends ContentObserver { private Context mContext;

    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);
    }

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

All Articles