Search code examples
androidnotificationsbroadcastreceiverintentservice

How to notify Activity about changes in global variable in Application?


I have a IntentService that updates a global variabel in a extended Application class. In several of mine Activities I need to know when the variable is changed. Do I have to implement a BroadcastReceiver in all my Activities(and send a intent from my service) or is there a simpler way to notify my activities?

Thank you!


Solution

  • Yes, BroadcastReceivers were designed for just this. That said, why not just make a single parent class which has a BroadcastReceiver and all the associated logic? Then the only thing your other activities have to do is simply inherit from that parent class.

    Note that you should also set some sort of global variable in persistent storage (like a shared preference) every time you send our a Broadcast. That way, if one of your activities isn't in the foreground when the Broadcast is sent, it can check the variable in persistent storage when it comes back in the onResume() method and act accordingly.