How should an Android application respond to critical changes in the environment?
android
Solution
Have all your activities extend from a `MyActivity` class which has a `BroadcastReceiver` member: mChangeReceiver.
Have `MyActivity` register mChangeReceiver in `onCreate` (and unregister in `onDestroy`), to the `LOGIN_ACCOUNTS_CHANGED` intent.
Have the mChangeReceiver call some abstract method `onAccountChanged()` that all extending classes need to override and implement to reflect the change in the GUI.
That's it. Now, whenever the account changes, all your living activities will get their `onAccountChanged` method called and will refresh their GUI.
Problem
Let's say there's an application that creates an account in AccountManager. User explores the quite complicated activity graph of this application for a while, then goes to `Accounts and Sync` in Android Settings, removes the account and signs in (still being in `Accounts and Sync` as a different user. I have defined a receiver for `LOGIN_ACCOUNTS_CHANGED` broadcast and I'm able to shut down all services gracefully. But activities are still there, bearing the name of the first user in their header (UI gets messed up in a number of ways, but this one is the most obvious). So, the question is: what should be done about these orphan activities? - I could use something like `clearTaskOnLaunch`, but all activities are in the background when the change happens. - Set a flag in SharedPreferences and check in `onResume()` of each activity, then launch `clearTask` activity if needed? Too messy. - The best option I was able to come up with is to use `android.os.Process.killProcess(android.os.Process.myPid())` to kill all activities. This is not too graceful, but gets job done. The only side effect is that activity stack is still there, when the most reasonable thing seems to be to start from the `LAUNCHER` activity, with clear history. So, what would be the best way to respond to the described scenario?