3

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

            }
        }
    }
}
Frederikkastrup
  • 243
  • 1
  • 3
  • 11
  • 1
    You can refer to this: [http://stackoverflow.com/questions/5787894/android-is-there-any-way-to-listen-outgoing-sms][1] [1]: http://stackoverflow.com/questions/5787894/android-is-there-any-way-to-listen-outgoing-sms – RussVirtuoso Oct 07 '13 at 08:36

0 Answers0