Search code examples
androidandroid-fragmentsandroid-broadcastreceiverandroid-sharedpreferences

Saving status in broadcast receiver to be later used in the UI


I have a broadcast receiver that keeps track of some external events and acts upon them as required. And I also have a fragment in my application that shows a status summary of what the last event/status is/was.

Now I am currently using a shared preference to save this status in the receiver and then a onSharedPreferenceChange Listener to update the fragment if it is currently being viewed.

I am in a debate with myself if I should be doing it this way? Or register a broadcast receiver with the fragment when it starts instead of using a shared preference.

But the problem I then have is that the fragment will be unable to get the current status when it opens and won't know what is happening until another event is broadcast.

Is this an appropriate use of shared preferences? The status will change anywhere from once every few seconds to 30+ seconds.

And one would use the broadcast receiver in the fragment if an update/status change was received every second or less?


Solution

  • Even if you used a BroadcastReceiver, you would still need to get the initial event/status info from somewhere. Therefore, you need to persist the event/status info no matter what. Since you probably only need to persist a few values (and do not need to access them that frequently), using SharedPreferences is a perfectly reasonable approach.