Android: How to send and receive data through SMS messages

android, sms

Solution

The correct way to do this would be by using sendDataMessage from SmsManager class. Here's a little code (SMSSender):

SmsManager smsMgr = SmsManager.getDefault();
smsMgr.sendDataMessage(phoneNumber, null,
            (short) myApplicationPort, messageString.getBytes(), sentIntent, deliveryIntent);

Here's another little code (SMSReceiver):

    Bundle bundle = intent.getExtras();
    if (bundle != null) {
        Object[] pdusObj = (Object[]) bundle.get("pdus");
        SmsMessage[] messages = new SmsMessage[pdusObj.length];

        // getting SMS information from PDU
        for (int i = 0; i < pdusObj.length; i++) {
            messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
        }

        for (SmsMessage currentMessage : messages) {
            if (!currentMessage.isStatusReportMessage()) {

                String messageBody = currentMessage.getDisplayMessageBody();

                    byte[] messageByteArray = currentMessage.getPdu();

                    // skipping PDU header, keeping only message body
                    int x = 1 + messageByteArray[0] + 19 + 7;

// I'm not sure about this last line, as I'm not converting the bytes back to string, so test it out
                    String realMessage = new String(messageByteArray, x, messageByteArray.length-x);

Here's what you should add to your AndroidManifest.xml:

 <receiver android:name=".SMSReceiver">
   <intent-filter>
     <action android:name="android.intent.action.DATA_SMS_RECEIVED" />
     <data android:scheme="sms" />
     <data android:host="localhost" />
     <data android:port="12345" /><!-- this number should be the same as the `myApplicationPort` from above!!! -->
   </intent-filter>
 </receiver> 

Problem

I want to send some data (NOT MULTIMEDIA) through an SMS message in Android. Can this be done? I just want to send a very small amount of data from one phone to another, as XML or something.

Original source