user3218332
user3218332

Reputation:

Exit android app on back pressed

I am building an Android App. How to exit an Android App when back is pressed. Android version is 2.3.3 and above. The Android App goes to previous activity which i don't want.

Upvotes: 40

Views: 127010

Answers (17)

KBoek
KBoek

Reputation: 5985

As onBackPressed is deprecated since SDK 33, here's how I implemented Sujith Royal's suggestion (also thanks to @ianhanniballake and @Zain for their answer here - see under UPDATE)

override fun onCreate(savedInstanceState: Bundle?) {
  onBackPressedDispatcher.addCallback(object: OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
      finishAffinity()
      finish()

      exitProcess(0)
    }
  })
}

Upvotes: 0

SwimmingHigh
SwimmingHigh

Reputation: 31

A solution for the case when you want to prevent your app from going back to the Splash Screen when back is pressed on Main Activity, I add finish() after the intent launcher when I start the Main Activity.

startActivity(new Intent(SplashScreen.this, MainActivity.class));
finish();

Now when you press back on MainActivity, it will exit the app.

Upvotes: 0

in AndroidManifest.xml if you write in Activity tag

android:noHistory="true"

if we backpressed this activity there is no history my app like click home button, app is background

Upvotes: 0

Robin Singh
Robin Singh

Reputation: 1

As per user experience, pressing back should never exit the application. An alertDialog should come which asks the user if they want to exit the application or they wants to stay on the application. Here is the code :

@Override
    public void onBackPressed() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("DO YOU REALLY WANT TO EXIT ??")
                .setCancelable(false)
                .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        FirstActivity.super.onBackPressed();
                    }
                })
                .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

Upvotes: 0

Prajwal Waingankar
Prajwal Waingankar

Reputation: 2728

moveTaskToBack() is now Deprecated

Use :

moveTaskToBack(true);

Upvotes: 5

murat.bingol
murat.bingol

Reputation: 15

you can exit app wtih this code.

@override public void onBackPressed()

{

finishAffinity();

System.exit(0);

}

Upvotes: 0

Bruce
Bruce

Reputation: 8869

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

android:noHistory="true"

to these activities.

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

OR

Sometimes you want to close the entire application on a certain back button press. Here the best practice is to open up the home window instead of exiting the application. For that, you need to override the onBackPressed() method. Usually, this method opens 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

On back button pressed you want to exit that activity and also you don't want to add this to the activity stack. Call finish() inside the onBackPressed() method. It will not close the entire application, it will just go to the previous activity in the stack.

onBackPressed() - Called when the activity has detected the user's press of the back key.

public void onBackPressed() {
  finish();
}

Upvotes: 47

Haider Malik
Haider Malik

Reputation: 1771

// Finish current activity
// Go back to previous activity or closes app if last activity
finish()

// Finish all activities in stack and app closes
finishAffinity()

// Takes you to home screen but app isnt closed 
// Opening app takes you back to this current activity (if it hasnt been destroyed)
Intent(Intent.ACTION_MAIN).apply {  
    addCategory(Intent.CATEGORY_HOME)
    flags = Intent.FLAG_ACTIVITY_NEW_TASK
    startActivity(this)
}

Upvotes: 9

Waqas Shah
Waqas Shah

Reputation: 115

Kotlin:

 override fun onBackPressed() {
        val exitIntent = Intent(Intent.ACTION_MAIN)
        exitIntent.addCategory(Intent.CATEGORY_HOME)
        exitIntent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        startActivity(exitIntent)
    }

Other codes have problems, some does not work and some needs API classification.

Upvotes: 5

Sujith Royal
Sujith Royal

Reputation: 822

I found an interesting solution which might help.

I implemented this in my onBackPressed()

finishAffinity();
finish();

FinishAffinity removes the connection of the existing activity to its stack. And then finish helps you exit that activity. Which will eventually exit the application.

Upvotes: 28

Tara
Tara

Reputation: 2648

I know its too late, but no one mentioned the code which i used, so It will help others.

this moveTaskToBack work as same as Home Button. It leaves the Back stack as it is.

 public void onBackPressed() {
 //  super.onBackPressed();
    moveTaskToBack();
  }

Upvotes: 25

Duan Bressan
Duan Bressan

Reputation: 625

If you have more than one screen in history and need all other ones to be ignored. I recommend using this:

@Override
public void onBackPressed() {

    finish();

}

Upvotes: 9

Deep Adhia
Deep Adhia

Reputation: 392

Pop Up

     @Override
     public void onBackPressed() {
     new AlertDialog.Builder(this)
       .setTitle("Really Exit?")
       .setMessage("Are you sure you want to exit?")
       .setNegativeButton(android.R.string.no, null)
       .setPositiveButton(android.R.string.yes, new OnClickListener() {

    public void onClick(DialogInterface arg0, int arg1) {
    WelcomeActivity.super.onBackPressed();
        }
    }).create().show();

}

Set Class to Top of App and no history

Intent launchNextActivity;
launchNextActivity = new Intent(B.class, A.class);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);                  

launchNextActivity.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivity(launchNextActivity);

enter code here Double back press

private static long back_pressed;
@Override
public void onBackPressed(){
if (back_pressed + 2000 > System.currentTimeMillis()){
super.onBackPressed();
}
else{
Toast.makeText(getBaseContext(), "Press once again to exit", 
Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}

}

Upvotes: 3

Andr&#233; Luiz Reis
Andr&#233; Luiz Reis

Reputation: 2333

You can clear all the back stack doing this.

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

Upvotes: 40

Simon
Simon

Reputation: 471

Just use the code finish(); under your intent to close the activity. So, It will not appear again. This solved mine.

startActivity(new Intent(SplashActivity.this, MainActivity.class));
finish();

Upvotes: 0

A.Wie
A.Wie

Reputation: 499

Try this

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

}

Upvotes: 47

Dimmerg
Dimmerg

Reputation: 2138

In normal way you shouldn't close app - user will moves it to back by pressing home or closing your activities by pressing back.

But you can use this tips:

1) Close old activities after starting the new ones if they not needed in back stack:

startActivity(newActivityIntent);
finish();

2) You can move task to back (instead of close) if you need http://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)

3) If you are really need it, you can use System.exit(0) but it's strongly not recommended and usually says that you have application's architecture problems.

Upvotes: 5

Related Questions