在Android中调用finish()后,应用程序不会关闭。

3
我正在开发一个应用程序,在其中有一个对话框,当我单击退出按钮时,我想关闭应用程序,但有时应用程序不会结束并返回到我的第一个活动。我不知道该怎么做。
相同的代码:
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
        alertDialog.setMessage(context.getResources().getString(R.string.app_close_dialog_msg));
        alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes, new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dismiss();
                ((Activity) context).finish();
                //((Activity) context). moveTaskToBack(true);
                System.exit(0);
                android.os.Process.killProcess(android.os.Process.myPid());



            }
        });

你在主活动中重写了 onBackPressed() 吗? - Mohammed Farhan
4个回答

2

不要

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

Intent _intentOBJ= new Intent(Intent.ACTION_MAIN);
    _intentOBJ.addCategory(Intent.CATEGORY_HOME);
    _intentOBJ.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    _intentOBJ.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(_intentOBJ);

@AndroidDeveloper 我已经修正了代码。请尝试这种方式。 - IntelliJ Amiya
但是它重新打开的是我退出时的应用程序,而不是从开始。为什么? - Android Developer
@AndroidDeveloper 应用关闭意味着从视图中“隐藏”,而不是删除。 - IntelliJ Amiya
我希望应用程序在退出后可以从闪屏页重新打开。 - Android Developer
@AndroidDeveloper 据我所知,这是不可能的。 - IntelliJ Amiya
但是可以使用 -- System.exit(0); android.os.Process.killProcess(android.os.Process.myPid()); - Android Developer

1
如果您的minSdk >= 16,则尝试调用ActivityCompat.finishAffinity(activity);,这将关闭应用程序中的所有活动。

0

不要添加系统的killprocess方法,而是要添加finishaffinity()方法来退出应用程序。以下是代码:

AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
   alertDialog.setMessage(context.getResources().

getString(R.string.app_close_dialog_msg));
    alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes,new

OnClickListener() {
    public void onClick (DialogInterface dialog,int which){
        dismiss();
        ((Activity) context).finishAffinity();

    }
});

0
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getContext());
alertDialog.setMessage(context.getResources().getString(R.string.app_close_dialog_msg));
alertDialog.setPositiveButton(R.string.app_close_dialog_msg_yes, new OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {       
            switch (which) {
                case DialogInterface.BUTTON_POSITIVE:
                    finish();
                    break;
             }
        }

这将会起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接