Info

5554321

[include Location in Reply

MAYDAY! MAvDAYI MAYDAY!

inup Aulo Respúndtr

FIGURE 12-3

Start by completing the respond method stub you created in Step 6. It should iterate over the Array List of status requesters and send a new SMS message to each. The SMS message text should be based on the response strings you defined as resources in Step 4. Fire the SMS using an overloaded respond method that you'll complete in the next step.

public void respond(boolean _ok, boolean _includeLocation) { String okString = getString(R.string.respondAllClearText); String notOkString = getString(R.string.respondMaydayText);

String outString = _ok ? okString : notOkString;

ArrayList<String> requestersCopy =

(ArrayList<String>)requesters.clone();

for (String to : requestersCopy)

respond(to, outString, _includeLocation);

private void respond(String _to, String _response, boolean _includeLocation) {}

12. Update the respond method that handles the sending of each response SMS.

Start by removing each potential recipient from the "requesters" Array List before sending the SMS. If you are responding with your current location, use the Location Manager to find it before sending a second SMS with your current position as raw longitude/latitude points and a geocoded address.

public void respond(String _to, String _response, boolean _includeLocation) { // Remove the target from the list of people we // need to respond to. lock.lock(); requesters.remove(_to); aa.notifyDataSetChanged(); lock.unlock();

SmsManager sms = SmsManager.getDefault(); // Send the message sms.sendTextMessage(_to, null, _response, null, null);

StringBuilder sb = new StringBuilder();

// Find the current location and send it // as SMS messages if required, if (_includeLocation) {

String ls = Context.LOCATION_SERVICE;

LocationManager lm = (LocationManager)getSystemService(ls); Location l =

lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

sb.append("I'm @:\n"); sb.append(l.toString() + "\n");

List<Address> addresses;

Geocoder g = new Geocoder(getApplicationContext(),

Locale.getDefault());

addresses = g.getFromLocation(l.getLatitude(), l.getLongitude(), 1);

Address currentAddress = addresses.get(O); if (currentAddress.getMaxAddressLineIndex() > 0) { for (int i = 0;

i < currentAddress.getMaxAddressLineIndex(); i++)

sb.append(currentAddress.getAddressLine(i)); sb.append("\n");

if (currentAddress.getPostalCode() != null) sb.append(currentAddress.getPostalCode());

ArrayList<String> locationMsgs =

sms.divideMessage(sb.toString()); for (String locationMsg : locationMsgs)

sms.sendTextMessage(_to, null, locationMsg, null, null);

13. In emergencies, it's important that messages get through. Improve the robustness of the application by including auto-retry functionality. Monitor the success of your SMS transmissions so that you can rebroadcast a message if it doesn't successfully send.

13.1. Start by creating a new public static String in the Emergency Responder Activity to be used as a local "SMS Sent'' action.

public static final String SENT_SMS = "com.paad.emergencyresponder.SMS_SENT";

13.2. Update the respond method to include a new PendingIntent that broadcasts the action created in the previous step when the SMS transmission has completed. The packaged Intent should include the intended recipient's number as an extra.

public void respond(String _to, String _response, boolean _includeLocation) { // Remove the target from the list of people we // need to respond to. lock.lock(); requesters.remove(_to); aa.notifyDataSetChanged(); lock.unlock();

SmsManager sms = SmsManager.getDefault();

Intent intent = new Intent(SENT_SMS); intent.putExtra("recipient", _to);

PendingIntent sent =

PendingIntent.getBroadcast(getApplicationContext(),

// Send the message sms.sendTextMessage(_to, null, _response, sent, null);

StringBuilder sb = new StringBuilder();

if (_includeLocation) {

[ ... existing respond method that finds the location ... ] ArrayList<String> locationMsgs =

sms.divideMessage(sb.toString()); for (String locationMsg : locationMsgs)

sms.sendTextMessage(_to, null, locationMsg, sentIntent, null);

13.3. Then implement a new Broadcast Receiver to listen for this broadcast Intent. Override its onReceive handler to confirm that the SMS was successfully delivered; if it wasn't, then put the intended recipient back onto the requester Array List.

private BroadcastReceiver attemptedDeliveryReceiver = new BroadcastReceiver() { ©Override public void onReceive(Context _context, Intent _intent) { if (_intent.getAction().equals(SENT_SMS)) { if (getResultCode() != Activity.RESULT_OK) {

String recipient = _intent.getStringExtra("recipient"); requestReceived(recipient);

13.4. Finally, register the new Broadcast Receiver by extending the onCreate method of the Emergency Responder Activity.

©Override public void onCreate(Bundle savedlnstanceState) { super.onCreate(savedlnstanceState); setContentView(R.layout.main);

lock = new ReentrantLock(); requesters = new ArrayList<String>(); wireUpControls();

IntentFilter filter = new IntentFilter(SMS_RECEIVED); registerReceiver(emergencyResponseRequestReceiver, filter);

IntentFilter attemptedDeliveryfilter = new IntentFilter(SENT_SMS); registerReceiver(attemptedDeliveryReceiver, attemptedDeliveryfilter);

All code snippets in this example are part of the Chapter 12 Emergency Responder project, available for download at Wrox.com.

This example has been simplified to focus on the SMS-based functionality it is attempting to demonstrate. Keen-eyed observers should have noticed at least two areas where it could be improved:

1. The Broadcast Receiver created and registered in Steps 7 and 8 would be better registered within the manifest to allow the application to respond to incoming SMS messages even when it isn't running.

2. The parsing of the incoming SMS messages performed by the Broadcast Receiver in Steps 7 and 9 should be moved into a Service, and executed on a background thread. Similarly, Step 13, sending the response SMS messages, would be better executed on a background thread within a Service.

The implementation of these improvements is left as an exercise for the reader based on the techniques you learned in Chapter 9.

Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide


Post a comment