I have a BroadcastReceiver class. I have some static variables declared whose value is updated in side the onReceive() method. As per my knowledge static variable will keep it's value across the onReceive calls. Is there any possibility when I will loose those values(Like my class will be unloaded resetting the static variables)? These are basically some temporary variables I need to be available for multiple onReceive calls.
A BroadcastReciever life cycle ends (ie stop receiving broadcast) when you unregister it. usually you would do this in the onPause/onStop method.
And that was all about creating broadcast receivers statically. The main difference in working between the static and dynamic receivers is that the static receivers will run if the application is running/not running. But the dynamic receivers will run if the application is running.
Static mostly used when you want to listen to an event all the time & dynamic may be used when one of the screen of your application is open and unregister that receiver once app is closed.
onReceive. This method is called when the BroadcastReceiver is receiving an Intent broadcast. During this time you can use the other methods on BroadcastReceiver to view/modify the current result values.
From the documentation for BroadcastReceiver Lifecycle...
A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent). Once your code returns from this function, the system considers the object to be finished and no longer active.
This isn't going to make the use of static variables practical in the sense that things will be cleaned up quickly by the system. I'd try using SharedPreferences
by calling...
context.getSharedPreferences("MyReceiver", MODE_PRIVATE)
...in the receiver's onReceive(...)
method (replace "MyReceiver"
with some name which makes sense to your app).
Or you could of course declare the static vars within your activity class.
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