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 launchclearTaskactivity 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 theLAUNCHERactivity, with clear history.
So, what would be the best way to respond to the described scenario?
Have all your activities extend from a
MyActivityclass which has aBroadcastReceivermember: mChangeReceiver.Have
MyActivityregister mChangeReceiver inonCreate(and unregister inonDestroy), to theLOGIN_ACCOUNTS_CHANGEDintent.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
onAccountChangedmethod called and will refresh their GUI.