I'm using a ContentObserver to detect outgoing messages. The problem is that onChange() fires three times whenever a message is sent. I've been looking through some answers on SO and it appears to be because three tables are updated each time a message is sent.
Luckily each message comes with a unique id but I can't quite figure out how to best filter out messages with the same id. I tried some different approaches but they all seem to fail.
Does anyone know a good way of doing this?
My ContentObserver looks like this
private class OutgoingSMS extends ContentObserver {
public OutgoingSMS(Handler handler) {
super(handler);
}
@Override
public boolean deliverSelfNotifications(){
return true;
}
@Override
public void onChange(boolean selfChange){
super.onChange(selfChange);
Uri smsuri = Uri.parse("content://sms/sent");
Cursor cursor = mContext.getContentResolver().query(smsuri, null, null, null, null);
String outgoingSMS = null;
if (cursor != null && cursor.moveToFirst()){
try{
cursor.moveToFirst();
String type = cursor.getString(cursor.getColumnIndex("type"));
if (type.equals("2")){
outgoingSMS = cursor.getString(cursor.getColumnIndex("address"));
String subString = outgoingSMS.substring(0, 3);
}
}
catch (CursorIndexOutOfBoundsException e){
Log.e(Constants.TAG, "SMSHelper: outgoingSMS", e);
}
finally{
cursor.close();
}
//Filter out duplicate ids here.
if (outgoingSMS != null ){
long timestamp= getTime();
DataModel.getInstance(mContext).addLog(outgoingSMS), "sms", timestamp, 0, 1);
Log.d(Constants.TAG, "SMSHelper: outgoingSMS: " + outgoingSMS);
}
}
}
}