BroadcastReceiver Life Cycle
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).
或者你当然可以在你的活动课上声明静态变量。
链接地址: http://www.djcxy.com/p/52910.html