我想要做的是注册一个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);
}
}
}
}