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?
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!
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With