0

我想要做的是注册一个Service以上的ContentObserver并检查哪些ContentObserver触发器onChange()来做特定的反应。我不知道我是否只需要在 中包含 if/else onchange(),或者Overwrite在每个中包含一个 if/else ContentObserver,在任何一种情况下,我都不知道该怎么做。提前感谢您的帮助。

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

    }

}

}

4

2 回答 2

0

我会简单地扩展ContentObserver并添加我在那里缺少的任何东西。

于 2012-09-16T14:26:49.637 回答
0
mObserver = new ContentObserver(new Handler(Looper.getMainLooper())) {

                @Override
                public void onChange(boolean selfChange, Uri uri) {
                    super.onChange(selfChange, uri);

                    }
                }
            };

您可以使用上述方法检查uri

于 2019-08-22T15:11:19.147 回答