簡體   English   中英

使用后退按鈕離開 android 應用程序

[英]Leaving android app with back button

我希望我的 android 應用程序的用戶在進行某個活動時按回鍵時離開我的應用程序。 這可以做到嗎?

一個好方法是等待一秒鍾

private boolean             _doubleBackToExitPressedOnce    = false;

@Override
public void onBackPressed() {

    Log.i(TAG, "onBackPressed--");
    if (_doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    this._doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Press again to quit", Toast.LENGTH_SHORT).show();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {

            _doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}

您可以嘗試這樣的事情(顯示確認退出的對話框):

        @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();
                                    System.exit(0);
                                }
                            }).setNegativeButton("No", null).show();
                }

必須注意的是,在下面的評論中提到不建議使用System.exit退出應用程序。 一種更“正確”的方式可能是廣播一個背壓意圖,如果您的應用程序的活動收到該意圖完成自己。

你可以嘗試這個

public void onBackPressed() {
    moveTaskToBack(true);
}

把它放在你Manifest的每個活動中:

<activity android:name=".MyActivity" 
          android:noHistory="true">
</activity>

在您的Activity按下后退:

@Override
protected void onBackPressed() {
    if (this.isFinishing()){ 
        finish();
        super.onBackPressed();
    }
}

我知道這是一個老帖子。 但是這對我來說可能會有所幫助,因為我想要在他們的應用程序中實現相同的功能。

用於識別雙背的解決方案可以通過計算兩次背壓之間的時間來完成。 如果差異小於2秒(即2000毫秒),那么您可以接受雙重按下並退出應用程序。 否則顯示Toast消息。

簡單的實現是:

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

代碼可以在此鏈接中找到

您可以在活動中覆蓋onBackPressed()並在其中執行任何操作。 以下是按下后退時退出應用程序的代碼:

@Override
public void onBackPressed(){
  Intent intent = new Intent(Intent.ACTION_MAIN);
  intent.addCategory(Intent.CATEGORY_HOME);
  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);
}

看起來你所要求的會破壞后退按鈕的目的和應用程序的預期流程。 用戶希望按下后退按鈕將它們返回到上一個活動屏幕。

如果要使用后退按鈕終止整個應用程序,每次使用startActivity()時都要調用finish()。 這會在您離開時關閉當前活動,因此如果用戶按下后退按鈕,他們將離開您的應用。

考慮使用FLAG_ACTIVITY_CLEAR_TOP意圖標志來控制應用程序的活動堆棧,而不是覆蓋后退按鈕行為。

如果已設置,並且正在啟動的活動已在當前任務中運行,則不會啟動該活動的新實例,而是將關閉其上的所有其他活動,並將此Intent傳遞給(現在開啟) top)舊活動作為新的意圖。

例如,考慮一個由活動組成的任務:A,B,C,D。如果D調用帶有解析為活動B組件的Intent的startActivity(),則C和D將完成,B接收給定的Intent ,導致堆棧現在是:A,B。

使用上面的例子。 它將實現如下:從活動D:

Intent intent = new Intent(context, B.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

首先,你想要關閉你的應用程序是完全奇怪的,因為通常如果用戶離開你的應用程序,android處理剩下的應用程序,並根據設備的內存狀態決定是關閉還是保持暫停狀態,並且它做得很好在它上面,這意味着你不應該擔心它。

但是,如果您想要關閉您的應用程序,以防只有一個活動正在運行(在您的情況下按下后退按鈕)關閉該活動將關閉整個應用程序。 我的意思是,如果你使用intent傳輸到當前活動並且沒有關閉先前的活動,則使用this.finish()僅關閉當前活動並返回上一個暫停的活動,否則它將關閉整個應用程序。 考慮一個活動可能使用fragmet並且片段可以沒有布局的事實。 然后看起來應用程序在它仍在運行時關閉。

但是如何使用硬件返回鍵來完成你的工作呢? 你需要這樣做

@Override
public void onBackPressed()
{
    if(/* check a condition to make sure you are in that certain activity */)
    {
        Process.killProcess(Process.myPid()); 
    }
    else
    {
        super.onBackPressed();
    }
}

祝好運

我使用這種方法在Back press上留下一個應用程序:

@Override
public void onBackPressed() {
enter code here
    finish();
}

您可以在 onBackPressed() 方法中使用 moveTaskToBack() 來退出應用程序。

@Override
public void onBackPressed() {
    moveTaskToBack(true);
}

你可以通過覆蓋后退按鈕來實現任何目的。

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        // Do whatever you want with your activity
        // And for closing the whole app, you can use System.exit() which is absolutely not recomended
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
@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) {
                 Intent intent = new Intent(Intent.ACTION_MAIN);
                  intent.addCategory(Intent.CATEGORY_HOME);
                  intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                  startActivity(intent);
             }
         }).setNegativeButton("No", null).show();

    }

這是一個現成的方法來管理backPressed(),一次按兩次並調用確認對話框:

/**
 * Overrides Back Pressed Button handler.
 * Single continuous press custom clear in your activity.
 * Double continuous press - confirmation dialog to close all activities and exit to Android.
 */
@Override
public void onBackPressed() {

if (isBackPressedTwice) {

  new AlertDialog.Builder(this)
    .setCancelable(false)
    .setIcon(
      R.drawable.exit)
    .setTitle(
      getString(
        R.string.exit))
    .setMessage(
      getString(
        R.string.close_application))
    .setNegativeButton(
      getString(
        R.string.no),
      null)
    .setPositiveButton(
      getString(
        R.string.yes),
      new DialogInterface.OnClickListener() {
        @Override
        public void onClick(
          DialogInterface dialog,
          int which) {

          finishAffinity();

          return;
        }
      })
    .show();
} else {
  // Custom activity clearing operations.
}

this.isBackPressedTwice = true;

new Handler().postDelayed(
  new Runnable() {
    @Override
    public void run() {

      isBackPressedTwice = false;
    }
  },
  1000);
}

暫無
暫無

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

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