Monday, February 10, 2014

Broadcast Receiver in Android with sample demo on SMS_RECEIVED

Broadcast receiver is one of the important component of Android. It's event based which receives event and based on that event it performed.So we also called it receiver.
So for all registered receivers for particular event will be notified by Android when that event happens.
For-example applications can register for the ACTION_BATTERY_LOW system event which is fired when battery getting low.
So now I am creating a sample Project in which I am registering for the event "Telephony.SMS_RECEIVED" on my mobile so when any SMS will come it will show you toast message on your mobile.Just follow the steps to implement this demo project.

Step-1:Create ActivityBroadcastIncomingSMS.java

package com.oxyandroid;

import android.os.Bundle;
import android.app.Activity;


public class BroadcastIncomingSMS extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

}

Step-2:create main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="OxyAndroid : You will get SMS toast here" />


</RelativeLayout>


Step-3: Create ReceiverForSMS.java class which extends BroadcastReceiver

package com.oxyandroid;

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 ReceiverForSMS extends BroadcastReceiver {

// Get the object of SmsManager
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) {

/*Note-

A PDU is a "protocol discription unit", which is the industry format for an SMS message. because SMSMessage reads/writes them you shouldn't need to disect them. A large message might be broken into many, which is why it is an array of objects.Apart from this we declare Intent-Filter in android-manifest file from there we r getting object of that intent.
*/

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

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

SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String senderPhoneNo = sms.getDisplayOriginatingAddress();

       String Mymsg = sms.getDisplayMessageBody();

       Log.i("SmsReceiver", "senderPhoneNo: "+ senderPhoneNo + "; Message: " + Mymsg);     
      
Toast.makeText(context, "senderPhoneNo: "+ senderPhoneNo + ", Message: " + Mymsg, Toast.LENGTH_LONG).show();


              } 

} catch (Exception e) {
e.printStackTrace();

}
}

}


Step-4:create AndroidManifest.xml 

We have to create receiver in side this xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.oxyandroid"
    android:versionCode="1"
    android:versionName="1.0" >
       <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="17" />
    
    <uses-permission android:name="android.permission.RECEIVE_SMS"/>
    <uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.oxyandroid.BroadcastIncomingSMS">
            
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <receiver android:name="com.oxyandroid.ReceiverForSMS">   
            <intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
 
        </receiver>
        
    </application>
   


</manifest>

No comments:

Post a Comment