Auto Detect Mobile SMS through Broadcast Receiver

BroadcastReceiver smsBroadCastReceiver = new BroadcastReceiver() {

final SmsManager sms = SmsManager.getDefault();

public void onReceive(Context context, Intent intent) {

// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();

try {

if (bundle != null) {

final Object[] pdusObj = (Object[]) bundle.get("pdus");

for (int i = 0; i < pdusObj.length; i++) {

SmsMessage currentMessage = SmsMessage
.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage
.getDisplayOriginatingAddress();

String senderNum = phoneNumber;
String message = currentMessage
.getDisplayMessageBody();

Log.i("SmsReceiver", "senderNum: " + senderNum
+ "; message: " + message);

String msg = message.split(":")[1].trim();

if (msg.equalsIgnoreCase(randomCode)) {

if (mobileNo != null) {
<Write code authentication service call>
}
}
/*
* // Show Alert int duration = Toast.LENGTH_LONG;
* Toast toast = Toast.makeText(context,
* "senderNum: "+ senderNum + ", message: " +
* message, duration); toast.show();
*/

} // end for loop
} // bundle is null

} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" + e);

}
}
};
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
registerReceiver(smsBroadCastReceiver, intentFilter);

Share this

Related Posts

Previous
Next Post »