Android - Listen for incoming SMS messages
Get the latest m3-rc37a version of android
Here’s a screen shot

Setup the Android Manifest with the permission and the Intent Receiver
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.apache.sms">
<uses-permission id="android.permission.RECEIVE_SMS" />
<application>
<receiver class="SMSApp">
<intent-filter>
<action android:value="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
</manifest>
Code a simple Intent Listener
package org.apache.sms;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentReceiver;
import android.os.Bundle;
import android.provider.Telephony;
import android.util.Log;
import android.telephony.gsm.SmsMessage;
public class SMSApp extends IntentReceiver {
private static final String LOG_TAG = "SMSApp";
/* package */ static final String ACTION =
"android.provider.Telephony.SMS_RECEIVED";
public void onReceiveIntent(Context context, Intent intent) {
if (intent.getAction().equals(ACTION)) {
StringBuilder buf = new StringBuilder();
Bundle bundle = intent.getExtras();
if (bundle != null) {
SmsMessage[] messages = Telephony.Sms.Intents.getMessagesFromIntent(intent);
for (int i = 0; i < messages.length; i++) {
SmsMessage message = messages[i];
buf.append("Received SMS from ");
buf.append(message.getDisplayOriginatingAddress());
buf.append(" - ");
buf.append(message.getDisplayMessageBody());
}
}
Log.i(LOG_TAG, "[SMSApp] onReceiveIntent: " + buf);
NotificationManager nm = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
nm.notifyWithText(123, buf.toString(),
NotificationManager.LENGTH_LONG, null);
}
}
private void appendData(StringBuilder buf, String key, String value) {
buf.append(", ");
buf.append(key);
buf.append('=');
buf.append(value);
}
}
Running the sample
- Install the APK using “adb install SMSApp.apk” as usual
- Open a telnet session to localhost at port 5554 and type “sms send +5085551212 hello” to simulate an sms message
Download Source and APK from here - SMSApp.zip
About this entry
You’re currently reading “Android - Listen for incoming SMS messages,” an entry on Show me the code! - By Davanum Srinivas
- Published:
- 12.15.07 / 10am
- Category:
- Uncategorized
- Tags:
13 Comments
Jump to comment form | comments rss [?] | trackback uri [?]