androidandroid-contentprovideronchangecontentobserver

How to check which ContentObserver triggers the onChange method?


What I want to do is to have a Service with more than one ContentObserver registered and check which ContentObserver triggers onChange() to do specific reactions. I dont know if I just have to include a if/else inside the onchange(), or Overwrite it to each ContentObserver, in either cases I wouldnt know exactly how to do it. Thanks in advance for any help.

public class SmsObserverService extends Service {

private String BABAS = "babas";
@Override
public void onCreate() {

    Handler handler = new Handler();

    this.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, new SmsObserver(handler));

    //Second observer
    this.getContentResolver().registerContentObserver(Uri.parse("CallLog.Calls.CONTENT_URI"), true, new SmsObserver(handler));

}


@Override
public IBinder onBind(Intent intent) {
    // TODO Put your code here
    return null;
}


public class SmsObserver extends ContentObserver{

    public SmsObserver(Handler handler) {
        super(handler);


    }
    @Override
    public void onChange(boolean selfChange) {          
        super.onChange(selfChange);

        //Where I should check somehow which ContentObserver triggers the onChange


        //This code to the sms log stuff, the call log part will be included
        //when I find out how to check whic observer trigerred the onChange
        Uri uri = Uri.parse("content://sms/");
        Cursor cursor = getApplicationContext().getContentResolver().query( uri, null, null, null, null);
        cursor.moveToNext();


        String body = cursor.getString(cursor.getColumnIndex("body"));
        String add = cursor.getString(cursor.getColumnIndex("address"));
        String time = cursor.getString(cursor.getColumnIndex("date"));


        String protocol = cursor.getString(cursor.getColumnIndex("protocol"));

        if(protocol == null){
            Toast.makeText(getApplicationContext(), "Enviada para: " +add + ", Hora: "+time +" - "+body, Toast.LENGTH_SHORT).show();
            Log.i(BABAS, "Enviada para: "+add +" " +"Time: "+time +" - "+body);
        }else{
            Toast.makeText(getApplicationContext(), "Recebida de: "+add + ", Hora: "+time +" - "+body, Toast.LENGTH_SHORT).show();
            Log.i(BABAS, "Recebida de: "+add +" " +"Time: "+time +" - "+body);
        }

    }

}

}


Solution

  • I'd simply extend ContentObserver and add whatever I am missing there.