Friday, 25 November 2011

Android Boot Broadcast Receiver

Android has something call broadcasts , broadcasts are android's way of implementing OS/Phone events like


  1. Android boot is completed
  2. Android charger is plugged in 
  3. Android charger is disconnected
  4. Android is powered off 
  5. Android time-zone is changed
So , broadcasts can really help us in making out applications function to any ans even more of the above events .
So , for the sake of this tutorial we will be seeing only the Boot completed broadcast event . For this  we follow  the following steps :

  1. Add permission to receive boot completed broadcast in AndroidManifest.xml
  2. Add a receiver to receive the broadcast event AndroidManifest.xml
  3. Implement the receiver
STEP 1

Adding permission to get the boot completed broadcast is simple , just add the following in the android manifest file 



Here , instead of android.permission.RECEIVE_BOOT_COMPLETED you can add other broadcast receivers , for more broadcast receivers you can refer here .

STEP 2
Add the following in android manifest :


    
      
    

Here , BootReceiver is the class that will be called when we receive the Boot Completed broadcast .

STEP 3
Last task is to implement the receiver that is create a class that extends BroadcastReceiver
Look at the following code , its self explanatory :

public class BootReceiver extends BroadcastReceiver 
{
 // Do the stuff when the android has booted
 @Override
 public void onReceive(Context context, Intent intent) {
  
  Toast.makeText(context, "Greetings from Tapan Thaker", Toast.LENGTH_LONG).show();
  //Log it
     Log.d("Boot Receiver","The Broadcard event has been received");
 }

}
And now , some snapshots :)


 
You can see the action performed by our application (ie logging )

You can find the project file HERE

No comments:

Post a Comment