Skip to content

Instantly share code, notes, and snippets.

@bmutinda
Created August 4, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bmutinda/8f869c4fae6d02737ac9 to your computer and use it in GitHub Desktop.
Save bmutinda/8f869c4fae6d02737ac9 to your computer and use it in GitHub Desktop.
SMS Receiver
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<application>
<--- other declarations stuff -->
<!-- Broadcast receiver -->
<receiver android:name="com.myproject.SMSReceiver" >
<intent-filter android:priority="1000" >
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
</application>
/**
* Created by Mutinda Boniface on 7/12/2015.
*/
public class SMSReceiver extends BroadcastReceiver {
public static final String TAG = "SMSRelay";
public final String ACTION_SMS_RECEIVED = "android.provider.Telephony.SMS_RECEIVED";
public final String ACTION_PHONE_STATE_CHANGED = "android.intent.action.PHONE_STATE";
@Override
public void onReceive(Context context, Intent intent) {
String action = this.getIntentAction( intent );
SmsMessage[] smsMessages = null;
/**
* Handles any incomming message to the Device
*/
if (action.equalsIgnoreCase(ACTION_SMS_RECEIVED)) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
smsMessages = new SmsMessage[pdus.length];
/**
* Get all the messages received save them somewhere so that
* nothing gets lost if an exception is thrown in any of the
* message processing
*/
for (int i = 0; i < smsMessages.length; i++) {
smsMessages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
}
for (int i = 0; i < smsMessages.length; i++) {
String messageSender = smsMessages[i]
.getOriginatingAddress();
String messageBody = smsMessages[i].getMessageBody();
Log.e(TAG, "Message => "+messageSender+" : "+messageBody );
}
//abortBroadcast();
}
}
Log.e(TAG, smsMessages.toString() );
}
/**
* @param intent
* @return intent action
*/
private String getIntentAction(Intent intent) {
return intent.getAction();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment