I'm trying to make an SMS observer for outgoing messages using the ContentObserver
. The code below works perfectly, but whenever I test this by sending a text message to a colleague, I get the output twice.
The Observer gets registered in a Service, like this:
SentSMSObserver sentSMSObserver = new SentSMSObserver(new Handler(), this);
getContentResolver().registerContentObserver(sentSMSObserver.CONTENT_SMS_URI, true, sentSMSObserver);
Whenever I send a textmessage to my own number, I only get the output once, which is really weird. As a Service is a Singleton (as far as my research has led me to believe), it's quite improbable there is a second instance of my observer.
public class SentSMSObserver extends ContentObserver {
private static final String CONTENT_SMS = "content://sms";
public final Uri CONTENT_SMS_URI = Uri.parse(CONTENT_SMS);
private Context context;
public SentSMSObserver(Handler handler, Context context) {
super(handler);
this.context = context;
}
@Override
public void onChange(boolean selfChange) {
Cursor cursor = context.getContentResolver().query(CONTENT_SMS_URI, null, null, null, null);
try {
if (cursor.moveToNext()) {
String protocol = cursor.getString(cursor.getColumnIndex("protocol"));
int type = cursor.getInt(cursor.getColumnIndex("type"));
if (protocol != null || type != Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT) {
return;
}
String to = cursor.getString(cursor.getColumnIndex("address"));
Date now = new Date(cursor.getLong(cursor.getColumnIndex("date")));
String message = cursor.getString(cursor.getColumnIndex("body"));
Log.e("sentmessage", to + " - " + now + " - " + message);
}
} finally {
cursor.close();
}
}
}
Logcat:
08-11 14:25:14.292 12574-12574/com.androidfun.smstest E/sentmessage﹕ +(deleted phone n°) - Mon Aug 11 14:25:10 CEST 2014 - Test
08-11 14:25:18.306 12574-12574/com.androidfun.smstest E/sentmessage﹕ +(deleted phone n°) - Mon Aug 11 14:25:10 CEST 2014 - Test