Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Detect SMS Outgoing, Incorrect Count

I am trying to make an application to count the number of outgoing SMS messages from a phone. Presently I have the following code:

private void listenForSMS(){
    Log.v("SMSTEST", "STARTED LISTENING FOR SMS OUTGOING");
    Handler handle = new Handler(){};

    SMSObserver myObserver = new SMSObserver(handle);

    ContentResolver contentResolver = getContentResolver();
    contentResolver.registerContentObserver(Uri.parse("content://sms"),true, myObserver);
}

private class SMSObserver extends ContentObserver{

    int count = 0;
    String lastMessage = null;

    public SMSObserver(Handler handler) {
        super(handler);
    }

    public void onChange(boolean selfChange) {
        super.onChange(selfChange);

        Log.v("SMSTEST", "HIT ON CHANGE");

        Uri uriSMSURI = Uri.parse("content://sms");
        Cursor cur = getContentResolver().query(uriSMSURI, null, null,
                     null, null);
        cur.moveToNext();
        String protocol = cur.getString(cur.getColumnIndex("protocol"));
        if(protocol == null){
            count++;
            Log.v("SMSTEST", "SMS SENT: count: " + count);
            String content = cur.getString(cur.getColumnIndex("body"));

        }else{
            Log.v("SMSTEST", "SMS RECIEVED");
        }
    }
}

When I send a one page SMS message, onChange is called 3 times. When I send a two page SMS message, onChange is called 4 times. 3 page message, called 5 times; And so on.

NOTE: I have tried other variations of Uri.parse("content://sms"), such as "content://sms/sent", and nothing other than "content://sms" has gotten onChange to be called.

How can I uniquely distinguish an outgoing SMS message and get an accurate count of the number of SMS messages sent?

like image 903
Joshua Abrams Avatar asked Aug 10 '11 14:08

Joshua Abrams


2 Answers

Note that, when you send a SMS message, it will save the status of message. To solve it, you check the type of that records int type = c.getInt(c.getColumnIndex("type")); 3 times onchange():
1st : type = 6
2nd : type = 4
3rd : type = 2 (success)
then you can increase your counter.
This case is applied for 1 recipient only.
If there are much more 1 recipient, need to requery "thread_id" and "seen" to get the type. You can check how many message are sent success.
Good luck!

like image 113
kevin Avatar answered Oct 20 '22 10:10

kevin


I found a solution to my problem. SMSs and MMSs can be uniquely distinguished by their _id value.

Uri uriSMSURI = Uri.parse("content://sms");
    Cursor cur = getContentResolver().query(uriSMSURI, null, null,
                 null, null);
    cur.moveToNext();
String id = cur.getString(cur.getColumnIndex("_id"));
like image 23
Joshua Abrams Avatar answered Oct 20 '22 11:10

Joshua Abrams