簡體   English   中英

按下后退按鈕時完成所有活動

[英]Finish all activities when back button is pressed

我有一個 android 應用程序,它有 3 個活動。 對於第一個和第二個活動,我希望后退按鈕退出所有現有活動。

目前后退按鈕正在退出啟動它的活動,但如果在第二個活動上按下它,將顯示第一個活動,而不是退出應用程序,因為第一個活動會導致第二個活動。

我需要此功能的原因是因為第一個和第二個活動使用天文鍾計時器,當按下我想要的主頁按鈕時,它們會繼續運行。 但我需要一種方法來重置計時器以使用“后退”按鈕完全退出應用程序。

這是我的后退按鈕代碼,它出現在第一個和第二個活動中。

@Override
 public void onBackPressed() { // method for exit confirmation
  AlertDialog.Builder builder = new AlertDialog.Builder(BreakActivity.this);
  builder.setMessage("Are you sure you want to exit?")
         .setCancelable(false)
         .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int id) {
                  BreakActivity.this.finish();
             }
         })
         .setNegativeButton("No", new DialogInterface.OnClickListener() {
             public void onClick(DialogInterface dialog, int id) {
                  dialog.cancel();
             }
         });
  AlertDialog alert = builder.create();
  alert.show();

        }         
  };  

我研究了使用以下代碼的可能性:

intent = new Intent(this, FinActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent)
finish();

但是,我不確定應該在哪里實施,如果在按下 BACK 按鈕后顯示確認消息后選擇“是”,我真的只想結束所有應用程序(請參閱第一個代碼片段)。

將不勝感激為使這項工作提供任何幫助!

謝謝

@Rob 當您從活動 1 導航到 2 和 2 到 3 並有意使用完成時 function

 i=new Intent(Main_Menu.this, ABC.class);
          finish();
         startActivity(i);

它會殺死你將從 go 到下一個活動的活動,然后當你按下后退按鈕時,它會將你帶出應用程序,因為堆棧中沒有活動

你可以用這個

        finish();
        Intent intent = new Intent(Intent.ACTION_MAIN); 
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
        intent.addCategory(Intent.CATEGORY_HOME); 
        startActivity(intent);

請注意一件事總是避免 system.exit 從應用程序中退出,這是不推薦的,可能會導致各種問題

https://groups.google.com/forum/?fromgroups#!topic/android-developers/Y96KnN_6RqM

關閉應用程序並在 Android 上啟動主屏幕

使用這行代碼:

System.exit(1);

//The integer 1 is just a return code.

如何在 android 中關閉整個應用程序

您可以使用-

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

不要調用任何 System.exit 或其他東西。 Android 架構是為流程的自我管理而構建的。 Android 本身決定何時終止應用程序進程。 當您手動終止您的應用程序時,您正在為用戶設備創建額外的開銷。

嘗試手動重置您的計時器並修改您的應用架構。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM