Monday, March 26, 2012

Implementing Broadcast Receiver in Android

broadcast receiver is a component that responds to system-wide broadcast announcements. Many broadcasts originate from the system—for example, a broadcast announcing that the screen has turned off, the battery is low, or a picture was captured. Applications can also initiate broadcasts—for example, to let other applications know that some data has been downloaded to the device and is available for them to use. Although broadcast receivers don't display a user interface, they may create a status bar notification to alert the user when a broadcast event occurs. More commonly, though, a broadcast receiver is just a "gateway" to other components and is intended to do a very minimal amount of work. For instance, it might initiate a service to perform some work based on the event.

               We can simply implement broadcast receivers in applications .If you don't need to send broadcasts across applications, consider using this class with LocalBroadcastManager instead of the more general facilities described below. This will give you a much more efficient implementation (no cross-process communication needed) and allow you to avoid thinking about any security issues related to other applications being able to receive or send your broadcasts. 


Here a simple example for registering and sending a broadcast.



For receiving a broadcast
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 IntentFilter filter = new IntentFilter("LOGOUT_BROADCAST");
     registerReceiver(logoutReceiver, filter);

}

private BroadcastReceiver logoutReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context arg0, Intent arg1) {
                      // to do 
  }
};
@Override
 protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(logoutReceiver);
 }
For sending a broadcast
Intent intent = new Intent("LOGOUT_BROADCAST",null);
context.sendBroadcast(intent);

No comments:

Post a Comment