Saturday, October 8, 2011

Listening incoming sms message in Android

The following code shows "how to get notification when android mobile receive a message"

We will use only Broadcast Receiver's method not any URI query or something else.


So let's create a simple android app, then delete default Activity and create new java class
which extends Broadcast-receiver  look like this

SMSNotification.java
  
package com.rdc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;


public class SMSNotification extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

Toast.makeText(context,"Wow! we got a Message :)",Toast.LENGTH_SHORT).show();

Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if(bundle != null){
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for(int i=0; i<msgs.length;i++){
msgs[i]= SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from: " +msgs[i].getOriginatingAddress();
str +="\n"+"Message is:";
str += msgs[i].getMessageBody().toString();
str +="\n";
}

Log.v("Debug", str);
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}


AndroidManifest.xml
  
























output is like this

cheers!!

I'd love to hear your thoughts!

Labels: , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home