Sunday, April 3, 2011

Registering a broadcast receiver from widget

A broadcast receiver is a class which extends "BroadcastReceiver" and which is registered as a receiver in an Android Application via the AndroidManifest.xml or via code.

BroadcastReceiver registration is quite simple for and application. This example will show you how to register it from widget.

Es an example we will register receiver for ACTION_TIME_TICK intent.

We do not need to register it on AndroidManifest.xml because ACTION_TIME_TICK intent can't be registered in manifest.

First of all you need to create a BroadcastReceiver class instance.

private BroadcastReceiver HelloReceiver = new BroadcastReceiver(){

     @Override
     public void onReceive(Context context, Intent intent) {
   
          //do something on receive
  
     }
  
};

Register our receiver in WidgetProvider class onUpdate method.

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetId) {
  
     context.getApplicationContext().registerReceiver(this.HelloReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
   
     //do other actions such as update widget... 
}

The main point of this example that we are using a context.getApplicationContext() method to get a context instead of context that passed to onUpdate()

Have a nice code!

4 comments:

  1. This is completely unreliable. Android will terminate your process whenever it wants after the onUpdate() method returns, causing the BroadcastReceiver and Application to both vanish.

    ReplyDelete
  2. Thanks for your comment, but currently it works perfect for me :) And I didn't find a better solution for now!

    ReplyDelete
  3. Thanks Yaroslav Martsynyuk, Please tell me how to unregister?

    ReplyDelete
  4. Amazing blog about the various informative information on the programming languages. Android Training in Bangalore

    ReplyDelete