Android:按下后退按钮时退出应用程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20591959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:06:31  来源:igfitidea点击:

Android: Quit application when press back button

androidexitback-button

提问by Elham Gdz

In my application i want exit from app when press back button, this my code:

在我的应用程序中,我想在按下后退按钮时退出应用程序,这是我的代码:

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                .setMessage("Are you sure you want to exit?")
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                }).setNegativeButton("No", null).show();
    }

it's work correctly but when i exit from app it does not exit completely and show empty page with my app logo and when i again press back button exit from app, How can i fix it???

它工作正常,但是当我退出应用程序时,它没有完全退出并显示带有我的应用程序徽标的空白页面,当我再次按下后退按钮退出应用程序时,我该如何解决???

EDIT :

编辑 :

I use this code instead of above but my app exit completely but i want it running at background and does not exit completely , how can i do it?

我使用此代码而不是上面的代码,但我的应用程序完全退出,但我希望它在后台运行并且没有完全退出,我该怎么做?

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
                .setMessage("Are you sure?")
                .setPositiveButton("yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Intent intent = new Intent(Intent.ACTION_MAIN);
                        intent.addCategory(Intent.CATEGORY_HOME);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    }
                }).setNegativeButton("no", null).show();
    } 

回答by Rachit Mishra

When you press back and then you finish your current activity(say A), you see a blank activity with your app logo(say B), this simply means that activity B which is shown after finishing A is still in backstack, and also activity A was started from activity B, so in activity, You should start activity A with flags as

当您按下返回键然后完成当前活动(例如 A)时,您会看到一个带有应用徽标的空白活动(例如 B),这仅意味着完成 A 后显示的活动 B 仍在后台,还有活动A 是从活动 B 开始的,因此在活动中,您应该使用以下标志启动活动 A

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

Now your activity A is top on stack with no other activities of your application on the backstack.

现在您的活动 A 位于堆栈顶部,您的应用程序的其他活动不在堆栈中。

Now in the activity A where you want to implement onBackPressed to close the app, you may do something like this,

现在,在您想要实现 onBackPressed 以关闭应用程序的活动 A 中,您可以执行以下操作,

private Boolean exit = false;
@Override
    public void onBackPressed() {
        if (exit) {
            finish(); // finish activity
        } else {
            Toast.makeText(this, "Press Back again to Exit.",
                    Toast.LENGTH_SHORT).show();
            exit = true;
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    exit = false;
                }
            }, 3 * 1000);

        }

    }

The Handler here handles accidental back presses, it simply shows a Toast, and if there is another back press within 3 seconds, it closes the application.

这里的 Handler 处理意外的后退,它只是显示一个Toast,如果在 3 秒内再次出现后退,它会关闭应用程序。

回答by Md. Ilyas Hasan Mamun

Try this:

尝试这个:

Intent intent = new Intent(Intent.ACTION_MAIN);
          intent.addCategory(Intent.CATEGORY_HOME);
          intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);//***Change Here***
          startActivity(intent);
          finish();
          System.exit(0);

回答by Tara

I had the Same problem, I have one LoginActivity and one MainActivity. If I click back button in MainActivity, Application has to close. SO I did with OnBackPressed method. this moveTaskToBack() work as same as Home Button. It leaves the Back stack as it is.

我有同样的问题,我有一个 LoginActivity 和一个 MainActivity。如果我在 MainActivity 中单击后退按钮,应用程序必须关闭。所以我用 OnBackPressed 方法做了。这个 moveTaskToBack() 和 Home Button 一样工作。它保持原样离开 Back 堆栈。

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

}

回答by Kanwaljit Singh

It means your previous activity in stack when you start this activity. Add finish();after the line in which you calling this activity.

这意味着当您开始此活动时,您之前在堆栈中的活动。finish();在您调用此活动的行之后添加。

In your all previous activity. when you start new activity like-

在您之前的所有活动中。当您开始新活动时,例如-

startActivity(I);

Add finish();after this.

finish();在此之后添加。

回答by Matti

In my understanding Google wants Android to handle memory management and shutting down the apps. If you must exit the app from code, it might be beneficial to ask Android to run garbage collector.

据我了解,谷歌希望 Android 处理内存管理和关闭应用程序。如果您必须从代码中退出应用程序,让 Android 运行垃圾收集器可能会有所帮助。

@Override
public void onBackPressed(){
    System.gc();
    System.exit(0);
}

You can also add finish() to the code, but it is probably redundant, if you also do System.exit(0)

您也可以将 finish() 添加到代码中,但它可能是多余的,如果您还执行 System.exit(0)

回答by Achmad Naufal Syafiq

nobody seems to have recommended noHistory="true" in manifest.xml to prevent certain activity to appear after you press back button which by default calling method finish()

似乎没有人在 manifest.xml 中推荐 noHistory="true" 以防止在您按下后退按钮后出现某些活动,默认情况下调用方法 finish()

回答by BloodLoss

try this

尝试这个

Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);

回答by Bivin

This one work for me.I found it myself by combining other answers

这个对我有用。我通过结合其他答案自己找到了

private Boolean exit = false;
@override
public void onBackPressed(){ 
    if (exit) {
        finish(); // finish activity
    } 
    else {
        Toast.makeText(this, "Press Back again to Exit.",
            Toast.LENGTH_SHORT).show();
         exit = true;
         new Handler().postDelayed(new Runnable() {

         @Override
         public void run() {
             // TODO Auto-generated method stub
             Intent a = new Intent(Intent.ACTION_MAIN);
             a.addCategory(Intent.CATEGORY_HOME);
             a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
             startActivity(a);
        }
    }, 1000);
}

回答by gian1200

Finish doesn't close the app, it just closes the activity. If this is the launcher activity, then it will close your app; if not, it will go back to the previous activity.

Finish 不会关闭应用程序,它只会关闭活动。如果这是启动器活动,那么它将关闭您的应用程序;如果没有,它将返回到之前的活动。

What you can do is use onActivityResult to trigger as many finish() as needed to close all the open activities.

您可以做的是使用 onActivityResult 根据需要触发尽可能多的 finish() 以关闭所有打开的活动。

回答by Shashika

Instead of finish()call super.onBackPressed()

而不是finish()打电话super.onBackPressed()