Sunday, October 4, 2009

Sending SMS in Android

In this tutorial I am going to explain sending text message from one android mobile to another.

The UI of our application contains just two Editexts, one for sender's number and another for the message body. Then one "SEND" button.

I am going to demonstrate this by opening two different emulators(5554 & 5556). The phone number is the number that we see on top left side of the emulator, ie, here, 5554 & 5556 respectively.

Launch the SMS application on both emulators and start SMSing. You will get the notifcation on top of other emulator.


Now, how to implement the SMS Application. The main part of the application is the method sendSMS() and it takes two parameters, Sender's number and the content of the SMS.

sendSMS() contains, one object of PendingIntent and a BroadCastReceiver to send SMS.
PendingIntent contains an Intent and a target action and the return object can be handed on a different application, so that, the action that we described can be performed at a later stage. Then, the BroadcastReceiver to broadcast our SMS, textmessage.

The sourcecode for sendSMS() is,


public void sendSms(String phoneNumber, String message) {
String SENT = "SMS_SENT";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(
SENT), 0);
// after SMS sending
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}

}
}, new IntentFilter(SENT));

SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, sentPI,
null);
}



We need to do one last thing, we have to put permission in Manifest file for sending and receiving SMS as,


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


In this, emulator, 5554, sending a message to 5556.





and, emulator 5556, replying to 5554 as,

1 comment:

Androidians