Search code examples
javaandroidbroadcastreceiverandroid-broadcastandroid-appwidget

How to unregister BroadcastReceiver from AppWidgetProvider?


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


Solution

  • 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
        {
    
    {