0

I'm declaring a broadcastReceiver in my AppWidgetProvider onUpdate() method. The broadcast receiver would listen to connectivity changes.

IntentFilter intentFilter = new IntentFilter(connectivityChange);
context.getApplicationContext().registerReceiver(mReceiver, intentFilter);

Does a new broadcastReceiver get created every time my onUpdate() method launches?

If so, how do I unregister the previous broadcast, so that I don't have dozens of broadcastReceivers?

context.getApplicationContext().unregisterReceiver(mReceiver);

does not work, as the AppWidgetProvider loses the instance of the mReceiver.

EDIT: I cannot declare the receiver in the manifest, as the connectivity change action was disabled in the manifest for the most recent Android API levels, so i have to register it programatically

Nicolae Stroncea
  • 587
  • 2
  • 6
  • 17

2 Answers2

0

Solution: Answer. Yes, registering a BroadcastReceiver in onUpdate(), will register a new one every time. I solved the issue of creating too many Broadcastreceivers by creating one in OnEnabled(), as that code only runs when the first widget is created.

Here's how I'm planning to unregister the broadcastReceiver I created in onEnabled. I will add the intent filter:ACTION_APPWIDGET_DISABLED to the broadcastReceiver when registering it. In the OnReceive() method of the custom broadcastReceiver I will execute:

@Override
public void onReceive(Context context, Intent intent){
    if(intent.getAction().equals("ACTION_APPWIDGET_DISABLED"){
        context.unregisterReceiver(this);
    }
    else{
        ...
        //Rest of my method
    {

{
Nicolae Stroncea
  • 587
  • 2
  • 6
  • 17
0

This is really bad idea to listen connectivity changes in AppWidgetProvider because he has same lifetime as BroadcastReceiver. AppWidgetProvider is a BroadcastReceiver on steroids, but if you register receiver dynamically in onEnabled(), your instance of AppWidgetProvider will live really shortly, so you will not get any real callbacks of connectivity changes after some time. Better option you can find here.

HeyAlex
  • 1,666
  • 1
  • 13
  • 31