【问题标题】:App does not close after calling finish() in android在android中调用finish()后应用程序没有关闭
【发布时间】:2017-11-21 06:44:18
【问题描述】:

我正在开发一个应用程序,其中有一个对话框,当我单击退出按钮时,我想关闭应用程序,但有时应用程序无法完成并返回到我的第一个活动。我不明白该怎么处理。

相同的代码

    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() 是不是最重要的?

标签: android android-layout android-studio android-fragments android-alertdialog


【解决方案1】:

不要

  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 我已经修改了代码。试试这个方法。
  • 但它正在重新打开我退出的应用程序。不是从一开始。为什么?
  • @AndroidDeveloper 应用程序关闭意味着 HIDE 从视图中。不删除
  • 我希望该应用在退出后从启动画面打开
  • @AndroidDeveloper 它不可能 AFAIK
【解决方案2】:

如果您的 minSdk >= 16,请尝试调用 ActivityCompat.finishAffinity(activity);,这应该会关闭您应用的所有活动

【讨论】:

    【解决方案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) {       
                switch (which) {
                    case DialogInterface.BUTTON_POSITIVE:
                        finish();
                        break;
                 }
            }
    

    这会起作用。

    【讨论】:

      【解决方案4】:

      不要添加系统 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();
      
          }
      });
      

      【讨论】:

        猜你喜欢
        • 2012-11-23
        • 2013-10-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多