10 November 2014

How to receive SMS in android BroadcastReceiver

In this post i will tell you how to receive SMS in your application.If your application need to receive sms from specific number this is the way we want to do.First you need to BroadcastReceiver to receive sms from background.
    First you need to add uses-permission to READ SMS.

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

Then This is the code line for receive SMS.

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.telephony.SmsManager;

import android.telephony.SmsMessage;

import android.util.Log;

import android.widget.Toast;

public class ReceiveSms extends BroadcastReceiver {

    final SmsManager sms = SmsManager.getDefault();

    public void onReceive(Context context, Intent 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();

        int duration = Toast.LENGTH_LONG;

        Toast toast = Toast.makeText(context,

                            "senderNum: "+ senderNum + ", message: " + message, duration);

                    toast.show();
                }
            }

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

        }

    }

}


And Finally you have to Add your receiver in manifest file(Inside application tags).You must be add android:priority="500" other wise it will not work.

<receiver android:name="com.example.HomeControlSystem.ReceiveSms">
      <intent-filter android:priority="500">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
      </intent-filter> </receiver>

Happy coding..

No comments:

Post a Comment