Android Tutorial

(avery) #1

By : Ketan Bhimani


402 

Now that the application has the SmsManager, sending SMS is as
simple as a single call:

sms.sendTextMessage(“9995551212”, null, “Hello!”, null, null);


The application does not know if the actual sending of the SMS was
successful without providing a PendingIntent to receive the
broadcast of this information. The following code demonstrates
configuring a PendingIntent to listen for the status of the SMS:

Intent msgSent = new Intent(“ACTION_MSG_SENT”);
final PendingIntent pendingMsgSent =
PendingIntent.getBroadcast(this, 0, msgSent, 0);
registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
int result = getResultCode();
if (result != Activity.RESULT_OK) {
Log.e(“telephony”,
“SMS send failed code = “ + result);
pendingMsgReceipt.cancel();
} else {
messageEntry.setText(““);
}
}
}, new IntentFilter(“ACTION_MSG_SENT”));


The PendingIntent pendingMsgSent can be used with the call to the
sendText Message(). The code for the message-received receipt is
similar but is called when the sending handset receives
acknowledgment from the network that the destination handset
received the message.

If we put all this together with the preceding phone number
formatting EditText, a new entry field for the message, and a
button, we can create a simple form for sending an SMS message.
The code for the button handling looks like the following:

Button sendSMS = (Button) findViewById(R.id.send_sms);
sendSMS.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

Free download pdf