BroadcastReceiver Life Cycle — Static Variables

2019-02-10 00:52发布

问题:

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.

回答1:

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).



回答2:

Or you could of course declare the static vars within your activity class.