tl;dr: Is the approach at the bottom of this question a reasonable approach to exiting an Android application?
I maintain an Android music player application. Source.
I've gotten some requests for an 'exit button to be integrated into the player. Issue. I've added an exit option to the menu of each Activity, e.g.
I've tried a few approaches to exiting the application, including:
- Send an intent with an "exit" extra to my first Activity reference.
- Broadcast an "exit" message as described here.
Both of these approaches had some issues. The first approach never worked - I'd call startActivity as described in the example, but the intent received by the Activity never included my "exit" flag.
The second approach worked most of the time, but if I allowed Android to destroy Activities on my back stack, then clicked exit, the activities would be re-launched (apparently after receiving the "exit" broadcast). I could consistently re-create this problem by using the developer option to destroy all Activities immediately after they leave the view.
The approach I settled on was to broadcast an "exit" message and explicitly launch the home screen:
if (id == R.id.action_exit) {
// I had issues just broadcasting the "exit" intent
// if the other activities on the stack had finished,
// they were re-created, presumably *after* the broadcast had been sent
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("com.smithdtyler.ACTION_EXIT");
sendBroadcast(broadcastIntent);
// To make sure we exit, *first* send the broadcast (this makes sure the MusicPlaybackService shuts down)
// then launch the home screen
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(startMain);
finish();
return true;
}
The full source code to my exit approach is available here.
This approach has been working in testing, but I'm curious if there's a possible user configuration I could be overlooking where this could cause problems.