Friday, December 20, 2013

Android: Saving SMS data into DB

We can send the SMS by using the below API.
    SmsManager.getDefault().sendTextMessage()

But it is not saved into the conversation list.
For this reason, we can't know what message is sent.

Now, I wanna let you know how to save it.

1. Add <uses-permission>

    <uses-permission android:name="android.permission.SEND_SMS" />
    <uses-permission android:name="android.permission.WRITE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />


2. Add Code
    public class TestActivity extends Activity {

        public static final int MESSAGE_TYPE_ALL    = 0;
        public static final int MESSAGE_TYPE_INBOX  = 1;
        public static final int MESSAGE_TYPE_SENT   = 2;
        public static final int MESSAGE_TYPE_DRAFT  = 3;
        public static final int MESSAGE_TYPE_OUTBOX = 4;
        public static final int MESSAGE_TYPE_FAILED = 5; // for failed outgoing messages
        public static final int MESSAGE_TYPE_QUEUED = 6; // for messages to send later



       @Override
        protected void onCreate(Bundle savedInstanceState) {

             ContentValues values = new ContentValues();

             values.put("address",  m_phoneNumber.replace("-", ""));
             values.put("body",       m_smsMessage);
             values.put("protocol",  MESSAGE_TYPE_SENT);
             getContentResolver().insert(Uri.parse("content://sms/sent"), values);

    In this point, "content://sms/sent" is really really important.
    Please take a look at the below picture.
    The left side is MT SMS and right side is MO SMS.

    "content://sms/sent"   : Save as MO SMS
    "content://sms/inbox" : Save as MT SMS


No comments:

Post a Comment