Save data in Broadcast receiver

2020-02-06 18:21发布

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条回答
Summer. ? 凉城
2楼-- · 2020-02-06 18:27

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.

查看更多
爷的心禁止访问
3楼-- · 2020-02-06 18:42

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.

查看更多
Rolldiameter
4楼-- · 2020-02-06 18:51

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.

查看更多
▲ chillily
5楼-- · 2020-02-06 18:51

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];
//...
}
查看更多
淡お忘
6楼-- · 2020-02-06 18:53

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.

查看更多
登录 后发表回答