20.08.2016 Views

Professional Android 4 Application Development

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

728 x CHAPTER 17 TELEPHONY AND SMS<br />

12. In emergencies it’s important that messages get through. Improve the robustness of the application<br />

by including auto-retry functionality. Monitor the success of your SMS transmissions<br />

so that you can rebroadcast a message if it doesn’t successfully send.<br />

12.1 Start by creating a new public static String in the Emergency Responder Activity to be<br />

used within Broadcast Intents to indicate the SMS has been sent.<br />

public static final String SENT_SMS =<br />

“com.paad.emergencyresponder.SMS_SENT”;<br />

12.2 Update the respond method to include a new PendingIntent that broadcasts the<br />

action created in the previous step when the SMS transmission has completed. The<br />

packaged Intent should include the intended recipient’s number as an extra.<br />

Intent intent = new Intent(SENT_SMS);<br />

intent.putExtra(“recipient”, to);<br />

PendingIntent sentPI =<br />

PendingIntent.getBroadcast(get<strong>Application</strong>Context(),<br />

0, intent, 0);<br />

// Send the message<br />

sms.sendTextMessage(to, null, response, sentPI, null);<br />

12.3 Implement a new Broadcast Receiver to listen for this Broadcast Intent. Override its<br />

onReceive handler to confirm that the SMS was successfully delivered; if it wasn’t,<br />

put the intended recipient back onto the requester Array List.<br />

private BroadcastReceiver attemptedDeliveryReceiver = new<br />

BroadcastReceiver() {<br />

@Override<br />

public void onReceive(Context _context, Intent _intent) {<br />

if (_intent.getAction().equals(SENT_SMS)) {<br />

if (getResultCode() != Activity.RESULT_OK) {<br />

String recipient = _intent.getStringExtra(“recipient”);<br />

requestReceived(recipient);<br />

}<br />

}<br />

}<br />

};<br />

12.4 Finally, register and unregister the new Broadcast Receiver by extending the onResume<br />

and onPause handlers of the Emergency Responder Activity:<br />

@Override<br />

public void onResume() {<br />

super.onResume();<br />

IntentFilter filter = new IntentFilter(SMS_RECEIVED);<br />

registerReceiver(emergencyResponseRequestReceiver, filter);<br />

}<br />

IntentFilter attemptedDeliveryfilter = new IntentFilter(SENT_SMS);<br />

registerReceiver(attemptedDeliveryReceiver,<br />

attemptedDeliveryfilter);

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!