Wednesday, May 1, 2013

Broadcast Reciever in Android


Broadcast  Reciever

A broadcast receiver listens for relevant broadcast messages to trigger an event. Some
examples of broadcasted events already sent from the OS are

Battrey Low
SMS Recieved
Boot Completed   etc


Type of Broadcasts: 

  • Normal broadcasts are completely asynchronous. All receivers of the broadcast are run in an undefined order, often at the same time.
  • Ordered broadcasts are delivered to one receiver at a time. As each receiver executes in turn, it can propagate a result to the next receiver, or it can completely abort the broadcast so that it won't be passed to other receivers. The order receivers run in can be controlled with the android:priority attribute of the matching intent-filter; receivers with the same priority will be run in an arbitrary order. 

Registering Broadcast Receivers in  Manifest  file


All Broadcast Receivers must be registered in Android Manifest file.

here I will discuss about two Broadcast

BOOT_COMPLETED   :  is delivered when device finish Booting process  
SMS_RECEIVED      :   is delivered when da new SMS is Recieved.

BOOT_COMPLETED


 <receiver android:name=".BootReceiver">
                        <intent-filter>
                                <action android:name="android.intent.action.BOOT_COMPLETED" />
                                <category android:name="android.intent.category.HOME" />
                        </intent-filter>
   </receiver>


SMS_RECEIVED



 <receiver android:name=".SMSReciever">
            <intent-filter  android:priority="1000">
                <action android:name="android.provider.Telephony.SMS_RECEIVED" />
              
            </intent-filter>

 </receiver>


We  also need to declare following permission  in manifest  to Receive these Broadcasts

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


Now we need to create  Java class to handle these events.
For this we need to Extend  BroadcastReceiver    class and override   onReceive()  method.

inside onReceive() method we write the code to handle the events  like  when a new SMS received or Device  finish Booting Process.

BroadcastReceiver Example:

In this example we have cerated a BroadcastReceiver which will receive the SMS

first we Implement SMSReciever class
in this , we will extract the Message Body and the Senders Contact Number from received SMS

here variable  messageReceived will contain the message body.

BroadCastReceiver Class


public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        String messageReceived = "";            
        if (bundle != null)
        {
            //---retrieve the SMS message received---
           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]);                
                messageReceived += msgs[i].getMessageBody().toString();
                messageReceived += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, messageReceived, Toast.LENGTH_SHORT).show();
        }                         
    }
}
  
To get the Sender's Number use 
msgs.getOriginatingAddress ()     
 
 
More Post  following:  
1: Configuring Eclipse for Android Development 2: Understanding Android Manifest File of your android app 3: Understanding Layouts in Android 4: Using Buttons and EditText in Android  5:  Using CheckBoxes in Android  6:  Sending Data from One Activity to Other in Android 7Using AutoCompleteTextView in Android 8: How to Send SMS in AndroidHow To Receive SMS 10: Notifications In Android 11: How To Vibrate The Android Phone 12: Working With Alert Dialog 13: Adding Radio Buttons In Dialog 14:  Adding Check Boxes In Dialog 15: Creating Customized Dialogs in Android 16: Using TimePickerDialog and DatePickerDialog In android 17: Using Telephony Manager In Android 18: How To Handle Incoming Calls in Android 19: How to Forward an Incoming Call In Android 20 :Working With Menu: Creating Option Menu 21: Working With Menu: Creating Context Menu In Android
 
 

No comments:

Post a Comment