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?
5 Answers
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.

- 986,068
- 189
- 2,389
- 2,491
One possible solution is to make this map static. This seems ok for Receivers registered in the manifest, since there is only one receiver at a time.
static HashMap<String> hashMap;
static {
hashMap.put("key1","string1");
}
Same trick might be used to register a Handler to receive feedback from Receiver.

- 2,059
- 1
- 16
- 29
-
1Static works as long as you are certain the system doesn't kill the process, which it might do after the receiver returns if nothing else in that process is active. – satur9nine May 19 '12 at 02:34
-
Thanks, while it is probably not what the original question wanted, it is exactly what I need. A way to cache that data, so I only get the performance hit on first BroadcastReceiver invocation. – domen Nov 22 '13 at 20:32
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.

- 37,019
- 22
- 105
- 153
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.

- 3,904
- 1
- 22
- 17
downcast the data to Object class and then up-cast to required class object :-)
public void onReceive(Context context, Intent intent) {
HashMap map = (HashMap) bundle.get("KEY");
Object[] data=map.get(mapKey);
XXXX xxxx=data[0];
//...
}

- 399
- 2
- 5
- 22