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
You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().
An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest. xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.
To stop receiving broadcasts, call unregisterReceiver(android. content. BroadcastReceiver) . Be sure to unregister the receiver when you no longer need it or the context is no longer valid.
Use unregisterReceiver(BroadcastReceiver receiver) in your onPause() to unregister the Broadcast receiver. For a Service: Remove the receiver tag from the manifest file. You can then register your Broadcast receiver with the same method in the onCreate() and unregister in the onDestroy() .
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)
you should create a BaseActivity.
Example
public class BaseActivity extends AppCompatActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerReceiver(broadcastReceiver, new IntentFilter("TIMEZONE_CHANGED")); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(broadcastReceiver); } }
And MainActivity extend BaseActivity
example:
public class MainActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With