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!

11 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. Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
    industrial course in chennai

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. Thanks for sharing and i think it's very useful content so please keep sharing such type of content.

    Understanding Lifecycle in Android Activity

    ReplyDelete
  7. Hello Beautiful people?
    I think you are looking perfect logo design for your company right?
    Buy a logo 5O% off. Custom Logo

    ReplyDelete