Search code examples
androidbroadcastreceiverandroid-application-class

How to unregister broadcast receiver from an Application Class?


I register broadcast receiver in Android's Application Class,but now my question is where to unregister that broadcast ?

public class MyApplication extends Application 

{

@Override
public void onCreate() {
     ..... 
     // OTHER INITIALIZATIONS
     initNetworkBR();
} 
private void initNetworkBR() {

      br = new BroadcastReceiver() {
        ....
      };
      IntentFilter filter = new IntentFilter();
      filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
      registerReceiver(br, filter);
   }
}

Solution

  • One suggestion is in your launcher activity or desired activity unregister that like this:

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ((MyApplication) getApplication()).unregisterReceiver();
    }
    

    And implement unregisterReceiver method in MyApplication class:

    public void unregisterReceiver() {
         unregisterReceiver(br);//your broadcast
    }