Broadcast receiver in android

A broadcast receiver is a component which allows us to register for system or application events. All registered receivers for an event will be notified by Android once this event happens.

Android system periodically broadcast messages about things that are happening, such as the battery status changed, the Wi-Fi came on, or the phone’s orientation changed. You can pick up these state changes and perform actions after intercepting them and all this is done using broadcast receivers. Broadcast receivers receive and react to broadcasts generated by system or apps .

The below sample code depicts a broadcast receiver that call LockerActivity.class when  “android.intent.action.SCREEN_OFF” is intercepted.


BroadcastReceiver  broadcastReceiver=new BroadcastReceiver() {

//This method is called when the BroadcastReceiver is receiving an Intent broadcast

@Override

public void onReceive(Context context, Intent paramIntent) {

String str=paramIntent.getAction();//Retrieve the general action to be performed

//screen is OFF

if ((!"android.intent.action.SCREEN_ON".equals(str)) || ("android.intent.action.SCREEN_OFF".equals(str)))

{

Intent localIntent1 = new Intent(context, LockerActivity.class);//locker class called

//If set, this activity will become the start of a new task on this history stack.

context.startActivity(localIntent1);//starting activity

}

}

};

// Register a BroadcastReceiver to be run in the main activity thread. The receiver will be //called with any broadcast Intent that matches filter, in the main application thread.

registerReceiver(broadcastReceiver,intentfilter);

BroadcastRecievers do not have a UI but they start activities based on broadcast announcements.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s