Showing posts with label quit android application. Show all posts
Showing posts with label quit android application. Show all posts

Monday, October 14, 2013

Code to Quit or Exit Android Application

Question
I have an application where on the home page I have buttons for navigation through the application.
On that page I have a button "EXIT" which when clicked should take the user to the home screen on the phone where the application icon is.
How can I do that?
Solution
Android's design does not favor exiting an application by choice, but rather manages it by the OS. You can bring up the Home application by its corresponding Intent:
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
I added the following code to my quitGame function in my MainActivity.java file and it worked
 /** Called when the user clicks the Quit Game button */ 
 public void quitGame(View view) 
{
        // Do something in response to button
 Intent intent = new Intent(Intent.ACTION_MAIN);
 intent.addCategory(Intent.CATEGORY_HOME); 
 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
 startActivity(intent); 
 } //end function quitGame