Java – Register and Unregister the BroadcastReceiver in Application Class

androidandroid-lifecycleapplication-lifecyclejava

I have a broadcast receiver Which is registered in the onCreate() method of Android Applcation class but How to unRegister the same

example

public class MyApplication extends Application {


@Override
public void onCreate() {
    super.onCreate();
    registerReceiver(broadcastReceiver, new IntentFilter("TIMEZONE_CHANGED"));
}

In the above code I have registered it in the application onCreate() method and there is no onDestroy() / onStop() method in the Application class to unregister the broadcastReceiver.

How to achieve it

Best Answer

You don't need to unregister if you'd like to listen for the entire time the app is running. From the docs (as of today):

Context-registered receivers receive broadcasts as long as their registering context is valid. For an example, if you register within an Activity context, you receive broadcasts as long as the activity is not destroyed. If you register with the Application context, you receive broadcasts as long as the app is running.

(https://developer.android.com/guide/components/broadcasts.html)