Monday, 25 July 2011

SMS Listener

How to listen for Incoming SMS and Retrieve it's content? Here is the solution:

public class SmsListener extends BroadcastReceiver{

    private SharedPreferences preferences;
   
    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    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]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

Note: In your manifest file add the BroadcastReceiver:

<receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

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

Note: Useful link-


1 comment:

  1. Nice Thread Tutorial, i am new in android , its help me a lot ...

    I have got some good links

    here
    at androidexample.com
    Incomming SMS Broadcast Receiver

    ReplyDelete