Saving data in a broadcast receiver

I want to save a hash table in a broadcast receiver. If I understand that the BroadcastReceiver life cycle can currently be killed by destroying my member variables. What would be the ideal strategy for getting a hash table from a previous onReceive run in BroadcastReceiver?

+1
source share
5 answers

There are two ways to use BroadcastReceiver , and you did not indicate what you are using.

One for the receiver registered with some other component - for example, Activity - through registerReceiver() . This receiver will work as long as it is registered, and therefore its data can last more than one call onReceive() . The component that registered the receiver will be responsible for storing data.

Another is to register the recipient in the manifest. Those for the quoted passage in cdonner's answer will leave after one call to onReceive() . Your recipient will need to save their data, database, flat file, or something else.

+12
source

One possible solution is to make this card static. This looks normal for recipients registered in the manifest, since it only has one receiver at a time.

 static HashMap<String> hashMap; static { hashMap.put("key1","string1"); } 

The same trick can be used to register the handler to receive feedback from the receiver.

+2
source

From Android Reference:

The BroadcastReceiver object is valid only for the duration of the onReceive call (Context, Intent). As soon as your code returns from this function, the system considers the object finished and no longer active.

It doesn't seem like you want to work. Actitivy, which registers the recipient, will have to take care of this, or you can save your hash table in the database.

0
source

A better strategy would be to use a database to store your data in a table instead of any type of memory card.

Thus, it does not matter if the user disconnects and then turns on the phone again, your data from previous calls will still be available.

0
source

drag the data into the Object class, and then raise it to the desired class object :-)

 public void onReceive(Context context, Intent intent) { HashMap map = (HashMap) bundle.get("KEY"); Object[] data=map.get(mapKey); XXXX xxxx=data[0]; //... } 
0
source

All Articles