How to exit from the application and show the home screen?

AndroidExitBack Button

Android Problem Overview


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?

Android Solutions


Solution 1 - Android

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);

Solution 2 - Android

May be you can try something like this

Suppose in our application, we have a number of activities(say ten) and we need to exit directly from this activity. What we can do is, create an intent and go to the root activity and set flag in the intent as

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

also, add some extra like boolean to the intent

intent.putExtra("EXIT", true);

Then in root activity, check the value of the boolean and according to that call finish(), in the onCreate() of the root activity

if (getIntent().getBooleanExtra("EXIT", false)) {
 finish();
}

Solution 3 - Android

System.exit(0);

Is probably what you are looking for. It will close the entire application and take you to the home Screen.

Solution 4 - Android

This works well for me.
Close all the previous activities as follows:

	Intent intent = new Intent(this, MainActivity.class);
	intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	intent.putExtra("Exit me", true);
	startActivity(intent);
	finish();

Then in MainActivity onCreate() method add this to finish the MainActivity

	setContentView(R.layout.main_layout);
	
	if( getIntent().getBooleanExtra("Exit me", false)){
		finish();
		return; // add this to prevent from doing unnecessary stuffs
	}

Solution 5 - Android

first finish your application using method finish();

and then add below lines in onDestroy for Removing Force close

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();

Solution 6 - Android

If you want to end an activity you can simply call finish(). It is however bad practice to have an exit button on the screen.

Solution 7 - Android

Some Activities actually you don't want to open again when back button pressed such Splash Screen Activity, Welcome Screen Activity, Confirmation Windows. Actually you don't need this in activity stack. you can do this using=> open manifest.xml file and add a attribute

> android:noHistory="true"

to these activities.

<activity
    android:name="com.example.shoppingapp.AddNewItems"
    android:label="" 
    android:noHistory="true">
</activity>

OR

Sometimes you want close the entire application in certain back button press. Here best practice is open up the home window instead of exiting application. For that you need to override onBackPressed() method. usually this method open up the top activity in the stack.

@Override
public void onBackPressed(){
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);

}

OR

In back button pressed you want to exit that activity and also you also don't want to add this in activity stack. call finish() method inside onBackPressed() method. it will not make close the entire application. it will go for the previous activity in the stack.

@Override
public void onBackPressed() {
  finish();
}

Solution 8 - Android

It is not recommended to exit your Android Application. See this question for more details.

The user can always quit your app through the home button or in the first activity through the back button.

Solution 9 - Android

(I tried previous answers but they lacks in some points. For example if you don't do a return; after finishing activity, remaining activity code runs. Also you need to edit onCreate with return. If you doesn't run super.onCreate() you will get a runtime error)

Say you have MainActivity and ChildActivity.

Inside ChildActivity add this:

Intent intent = new Intent(ChildActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
return true;

Inside MainActivity's onCreate add this:

@Override
public void onCreate(Bundle savedInstanceState) {

	mContext = getApplicationContext();

	super.onCreate(savedInstanceState);

	if (getIntent().getBooleanExtra("EXIT", false)) {
		finish();
		return;
	}
    // your current codes
    // your current codes
}

Solution 10 - Android

There is another option, to use the FinishAffinity method to close all the tasks in the stack related to the app.

See: https://stackoverflow.com/a/27765687/1984636

Solution 11 - Android

When u call finish onDestroy() of that activity will be called and it will go back to previous activity in the activity stack... So.. for exit do not call finish();

Solution 12 - Android

Here's what i did:

SomeActivity.java

 @Override
    public void onBackPressed() {
            Intent newIntent = new Intent(this,QuitAppActivity.class);
            newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(newIntent);
            finish();
    }

QuitAppActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      finish();
}

Basically what you did is cleared all activities from the stack and launch QuitAppActivity, that will finish the task.

Solution 13 - Android

You can just add moveTaskToBack(true) in your exit button's onClickedListener to minimize the application.

Hope it helps.

Solution 14 - Android

Add following lines after finish(); in onDestroy():

android.os.Process.killProcess(android.os.Process.myPid());
super.onDestroy();

Solution 15 - Android

I tried exiting application using following code snippet, this it worked for me. Hope this helps you. i did small demo with 2 activities

first activity

public class MainActivity extends Activity implements OnClickListener{
	private Button secondActivityBtn;
	private SharedPreferences pref;
	private SharedPreferences.Editor editer;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        secondActivityBtn=(Button) findViewById(R.id.SecondActivityBtn);
        secondActivityBtn.setOnClickListener(this);
        
        pref = this.getSharedPreferences("MyPrefsFile", MODE_PRIVATE);
		editer = pref.edit();

		if(pref.getInt("exitApp", 0) == 1){
			editer.putInt("exitApp", 0);
			editer.commit();
			finish();
		}
    }
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SecondActivityBtn:
			Intent intent= new Intent(MainActivity.this, YourAnyActivity.class);
			startActivity(intent);
			break;
		default:
			break;
		}
	}
}

your any other activity

public class YourAnyActivity extends Activity implements OnClickListener {
	private Button exitAppBtn;
	private SharedPreferences pref;
	private SharedPreferences.Editor editer;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_any);

		exitAppBtn = (Button) findViewById(R.id.exitAppBtn);
		exitAppBtn.setOnClickListener(this);

		pref = this.getSharedPreferences("MyPrefsFile", MODE_PRIVATE);
		editer = pref.edit();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.exitAppBtn:
			Intent main_intent = new Intent(YourAnyActivity.this,
					MainActivity.class);
			main_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(main_intent);
			editer.putInt("exitApp",1);
			editer.commit();
			break;
		default:
			break;
		}
	}
}

Solution 16 - Android

I did it with observer mode.

Observer interface

public interface Observer {
public void update(Subject subject);
}

Base Subject

public class Subject {
private List<Observer> observers = new ArrayList<Observer>();

public void attach(Observer observer){
	observers.add(observer);
}

public void detach(Observer observer){
	observers.remove(observer);
}

protected void notifyObservers(){
	for(Observer observer : observers){
		observer.update(this);
	}
}
}

Child Subject implements the exit method

public class ApplicationSubject extends Subject {
public void exit(){
	notifyObservers();
}
}

MyApplication which your application should extends it

public class MyApplication extends Application {

private static ApplicationSubject applicationSubject;

public ApplicationSubject getApplicationSubject() {
            if(applicationSubject == null) applicationSubject = new ApplicationSubject();
	return applicationSubject;
}

}

Base Activity

public abstract class BaseActivity extends Activity implements Observer {

public MyApplication app;

@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	app = (MyApplication) this.getApplication();
	app.getApplicationSubject().attach(this);
}

@Override
public void finish() {
	// TODO Auto-generated method stub
            app.getApplicationSubject().detach(this);
	super.finish();
}

/**
 * exit the app
 */
public void close() {
	app.getApplicationSubject().exit();
};

@Override
public void update(Subject subject) {
	// TODO Auto-generated method stub
	this.finish();
}

}

let's test it

public class ATestActivity extends BaseActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
	// TODO Auto-generated method stub
	super.onCreate(savedInstanceState);
	close(); //invoke 'close'
}
}

Solution 17 - Android

if you want to exit application put this code under your function

public void yourFunction()
{
finishAffinity();   
moveTaskToBack(true);

}



//For an instance, if you want to exit an application on double click of a 
//button,then the following code can be used.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 2) {
        // do something on back.
        From Android 16+ you can use the following:

        finishAffinity();
        moveTaskToBack(true);
    }

    return super.onKeyDown(keyCode, event);
}

Solution 18 - Android

100% works fine. this is code for Exit your app onClick (Method)

    Button exit = (Button)findViewById(R.id.exitbutton);

    exit.setOnClickListener(new View.OnClickListener() {

        @Override

        public void onClick(View view) {

            finish();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
            Toast.makeText(getApplicationContext(), "Closed Completely and Safely", Toast.LENGTH_LONG).show();
           
        }
    });

Solution 19 - Android

Maybe my code can hepls (Main_Activity.java):

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.finish();
        exit(0);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)  {
        switch(keyCode)    {
            case KeyEvent.KEYCODE_BACK:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("My application").setMessage("Keep playing?").setIcon(R.drawable.icon);
                // Go to backgroung
                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { moveTaskToBack(true); }
                });
                // Exit from app calling protected void onDestroy()
                builder.setNegativeButton("CLOSE APPLICATION", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { onDestroy(); }
                });
                // Close this dialog
                builder.setNeutralButton("CANCEL", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { dialog.cancel(); }
                });
                AlertDialog dialog = builder.create();
                dialog.show();
                return true;
        }
        return false;
    }

Solution 20 - Android

This is the easiest one

finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);

This will close the app and without destroying the methods services this task will be completed.

Solution 21 - Android

You can use finish(); moveTaskToBack(true); and System.exit(1); to quit your application.

public void onBackPressed() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setTitle("Exit Application?");
    alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                            moveTaskToBack(true);
                            android.os.Process.killProcess(android.os.Process.myPid());
                            System.exit(1);
                        }
                    })

            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    dialog.cancel();
                }
            });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}

Solution 22 - Android

If you want to exit from your application. Then use this code inside your button pressed event. like:

public void onBackPressed()
{
    moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());
    System.exit(1);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionpoojan9118View Question on Stackoverflow
Solution 1 - AndroidognianView Answer on Stackoverflow
Solution 2 - AndroidKartik DomadiyaView Answer on Stackoverflow
Solution 3 - AndroidNdupzaView Answer on Stackoverflow
Solution 4 - AndroidLazy NinjaView Answer on Stackoverflow
Solution 5 - Androiduser1699548View Answer on Stackoverflow
Solution 6 - AndroidChristianView Answer on Stackoverflow
Solution 7 - AndroidBruceView Answer on Stackoverflow
Solution 8 - AndroidJanuszView Answer on Stackoverflow
Solution 9 - AndroidtranteView Answer on Stackoverflow
Solution 10 - AndroidsiviView Answer on Stackoverflow
Solution 11 - AndroidIshamView Answer on Stackoverflow
Solution 12 - AndroidIrshuView Answer on Stackoverflow
Solution 13 - Androidpatel dhruvalView Answer on Stackoverflow
Solution 14 - AndroidRamanathanView Answer on Stackoverflow
Solution 15 - AndroidAmol Sawant 96 KuliView Answer on Stackoverflow
Solution 16 - AndroidHunterView Answer on Stackoverflow
Solution 17 - AndroidDila GurungView Answer on Stackoverflow
Solution 18 - AndroidVivek AkkaldeviView Answer on Stackoverflow
Solution 19 - AndroidBokili ProductionView Answer on Stackoverflow
Solution 20 - AndroidSambhav. KView Answer on Stackoverflow
Solution 21 - AndroidCodemakerView Answer on Stackoverflow
Solution 22 - AndroidPir Fahim ShahView Answer on Stackoverflow