Emergency Responder SMS Example


Build your own Android App Dev Empire

Get Instant Access

In this example, you'll create an SMS application that turns an Android phone into an emergency response beacon.

Once finished, the next time you're in unfortunate proximity to an alien invasion or find yourself in a robot-uprising scenario, you can set your phone to automatically respond to your friends' and family members' pleas for a status update with a friendly message (or a desperate cry for help).

To make things easier for your would-be saviors, you'll use location-based services to tell your rescuers exactly where to find you. The robustness of SMS network infrastructure makes SMS an excellent option for applications like this for which reliability and accessibility are critical.

1. Start by creating a new EmergencyResponder project that features an EmergencyResponder Activity.

package com.paad.emergencyresponder;

import java.io.IOException; import java.util.ArrayList; import java.util.Locale;

import java.util.concurrent.locks.ReentrantLock;

import java.util.List;

import android.app.Activity;

import android.app.PendingIntent;

import android.content.Context;

import android.content.Intent;

import android.content.IntentFilter;

import android.content.BroadcastReceiver; import android.content.SharedPreferences; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.telephony.SmsMessage;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.ArrayAdapter;

import android.widget.Button; import android.widget.CheckBox; import android.widget.ListView;

public class EmergencyResponder extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

2. Add permissions for finding your location as well as sending and receiving incoming SMS messages to the project manifest.

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.paad.emergencyresponder"> <application android:icon="@drawable/icon"


<activity android:name=".EmergencyResponder" android:label="@string/app_name"> <intent-filter>

<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>

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


3. Modify the main.xml layout resource. Include a ListView to display the list of people requesting a status update, and a series of buttons for sending response SMS messages. Use external resource references to fill in the button text; you'll create them in Step 4.

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:id="@+id/labelRequestList" android:layout_width="fill_parent" android:layout_height="wrap_content"

android:text="These people want to know if you're ok" android:layout_alignParentTop="true"

<LinearLayout android:id="@+id/buttonLayout"

xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="5px"

android:layout_alignParentBottom="true"> <CheckBox android:id="@+id/checkboxSendLocation" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Include Location in Reply"/> <Button android:id="@+id/okButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/respondAllClearButtonText"/> <Button android:id="@+id/notOkButton" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/respondMaydayButtonText"/> <Button android:id="@+id/autoResponder" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Setup Auto Responder"/> </LinearLayout> <ListView android:id="@+id/myListView" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_below="@id/labelRequestList" android:layout_above="@id/buttonLayout"/> </RelativeLayout>

4. Update the external strings.xml resource to include the text for each button and default response messages to use when responding, including "I'm safe'' or "I'm in danger'' messages. You should also define the incoming message text to use when your phone detects requests for status responses.

<?xml version="1.0" encoding="utf-8"?> <resources>

<string name="app_name">Emergency Responder</string> <string name="respondAllClearButtonText">I am Safe and Well </string>

<string name="respondMaydayButtonText">MAYDAY! MAYDAY! MAYDAY! </string>

<string name="respondAllClearText">I am safe and well. Worry not! </string>

<string name="respondMaydayText">Tell my mother I love her. </string>

<string name="querystring">are you ok?</string>


5. At this point, the GUI will be complete, so starting the application should show you the screen in Figure 12-2.

6. Create a new Array List of Strings within the EmergencyResponder Activity to store the phone numbers of the incoming requests for your status. Bind the Array List to the List View, using an Array Adapter in the Activity's onCreate method, and create a new ReentrantLock object to ensure thread safe handling of the Array List.

Take the opportunity to get a reference to the checkbox and to add Click Listeners for each of the response buttons. Each button should call the respond method, while the Setup Auto Responder button should call the startAutoResponder stub.

ReentrantLock lock; CheckBox locationCheckBox; ArrayList<String> requesters; ArrayAdapter<String> aa;

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

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

private void wireUpControls() {

locationCheckBox = (CheckBox)findViewById(R.id.checkboxSendLocation); ListView myListView = (ListView)findViewById(R.id.myListView);

int layoutID = android.R.layout.simple_list_item_1;

aa = new ArrayAdapter<String>(this, layoutID, requesters);


Button okButton = (Button)findViewById(R.id.okButton); okButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) {

respond(true, locationCheckBox.isChecked());

Button notOkButton = (Button)findViewById(R.id.notOkButton); notOkButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) {

Prepared for ASHLEE KABAT, email: [email protected] Order number: 56760408 This PDF is for the purchaser's personal use in accordance with the Wrox Terms of Service and under US copyright as stated on this book's copyright page. If you did not purchase this copy, please visit www.wrox.com to purchase your own copy.

VdffijliJ 7:17 PM

Emergency Responder rhese people want lo know if you're ok

Include Location in Reply


Setup AuUJ ReSfja lldi-r


respond(false, locationCheckBox.isChecked());

Button autoResponderButton =

(Button)findViewByld(R.id.autoResponder); autoResponderButton.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { startAutoResponder();

public void respond(boolean _ok, boolean _includeLocation) {} private void startAutoResponder() {}

7. Next, implement a Broadcast Receiver that will listen for incoming SMS messages.

7.1. Start by creating a new static string variable to store the incoming SMS message intent action.

public static final String SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";

7.2. Then create a new Broadcast Receiver as a variable in the EmergencyResponder Activity. The receiver should listen for incoming SMS messages and call the requestReceived method when it sees SMS messages containing the "are you safe'' String you defined as an external resource in Step 4.

BroadcastReceiver emergencyResponseRequestReceiver = new BroadcastReceiver() { @Override public void onReceive(Context _context, Intent _intent) { if (_intent.getAction().equals(SMS_RECEIVED)) {

String queryString = getString(R.string.querystring);

Bundle bundle = _intent.getExtras(); if (bundle != null) {

Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < pdus.length; i++) messages[i] =

SmsMessage.createFromPdu((byte[]) pdus[i]);

for (SmsMessage message : messages) {

if (message.getMessageBody().toLowerCase().contains (queryString)) requestReceived(message.getOriginatingAddress());

public void requestReceived(String _from) {}

8. Update the onCreate method of the Emergency Responder Activity to register the Broadcast Receiver created in Step 7.

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);

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

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

Update the requestReceived method stub so that it adds the originating number of each status request's SMS to the "requesters" Array List.

public void requestReceived(String _from) { if (!requesters.contains(_from)) { lock.lock(); requesters.add(_from); aa.notifyDataSetChanged(); lock.unlock();

The Emergency Responder Activity should now be listening for status request SMS messages and adding them to the List View as they arrive. Start the application and send SMS messages to the device or emulator on which it's running. Once they've arrived they should be displayed as shown in Figure 12-3.

Now update the Activity to let users respond to these status requests.


Emergency J?es p d n d er rhese people want lo know If you're ok

Was this article helpful?

0 0
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


  • stefan
    How to display sms by listview android example?
    8 years ago
  • gandolfo bergamaschi
    How to use an android phone as an emergency beacon?
    8 years ago

Post a comment