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.
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.
来源:https://stackoverflow.com/questions/6299283/broadcastreceiver-life-cycle-static-variables