I'd like to maintain a hash table in a broadcast receiver. If I understand BroadcastReceiver's life cycle currently it could get killed wiping out my member variables. What would be the ideal strategy for retrieving a hash table from a previous run of onReceive in the BroadcastReceiver?
From the Android Reference:
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.
Does not sound like what you want to do will work. The Actitivy that registers the receiver will have to take care of this, or you could persist your hash table to the database.
There are two ways to use a BroadcastReceiver
, and you did not indicate which you are using.
One for a receiver registered by some other component -- like an Activity
-- via registerReceiver()
. This receiver will live for as long as it is registered, and so its data may last for more than one onReceive()
call. The component that registered the receiver would be responsible for persisting the data.
The other is to register your receiver in the manifest. Those, per the quoted passage in cdonner's answer, will go away after a single onReceive()
call. Your receiver will need to persist its data itself, to a database, flat file, or whatever.
Your best strategy would be to use a database to store your data in a table instead of any type of in memory Map.
That way it wouldn't matter if the user turned off and then turned the phone back on again, your data from previous calls would still be available.