Android 如何在一次单击和两次单击时返回到上一个活动如何退出应用程序?

Android 如何在一次单击和两次单击时返回到上一个活动如何退出应用程序?,android,navigation,fragment,Android,Navigation,Fragment,当我单击一次后退按钮时,它将移动到上一个屏幕,当我单击两次时,它将退出我的应用程序 我也尝试了很多问题,但无法解决我的问题,所以我在这里提出了一个问题 NAvigation.java @Override public void onBackPressed() { DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); if (drawer.isDrawerOpen(GravityCompa

当我单击一次后退按钮时,它将移动到上一个屏幕,当我单击两次时,它将退出我的应用程序

我也尝试了很多问题,但无法解决我的问题,所以我在这里提出了一个问题

NAvigation.java

   @Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    }
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    else {

        backButtonHandler();
        //   Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
    }

}


public void backButtonHandler() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(
            Navigation.this);
    // Setting Dialog Title
    alertDialog.setTitle("Leave application?");
    // Setting Dialog Message
    alertDialog.setMessage("Are you sure you want to leave the application?");
    // Setting Icon to Dialog
    alertDialog.setIcon(R.drawable.m_visit);
    // Setting Positive "Yes" Button
    alertDialog.setPositiveButton("YES",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    finish();
                }
            });
    // Setting Negative "NO" Button
    alertDialog.setNegativeButton("NO",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to invoke NO event
                    dialog.cancel();
                }
            });
    // Showing Alert Message
    alertDialog.show();
}
我尝试了这种方法,但这只是帮助我退出应用程序。

尝试这种逻辑

private int clickCount = 0;
private long delay = 100;
Timer timer = new Timer();
@Override
public void onBackPressed() {
  if (clickCount == 2) {
    timer.cancel();
    //operations to be performed on double click
  } else {
    clickCount++;
    timer.schedule(new TimerTask() {
      @Override public void run() {
        getActivity().runOnUiThread(new Runnable() {
          @Override public void run() {
            clickCount = 0;
            //operations to be performed on single click
          }
        });
      }
    }, delay);
  }
}

在单击
延迟
字段

其不工作之间设置您想要的延迟。。当我按下single tym back按钮时,dailog显示出来,但我想显示两次dailog。我添加的代码只是一个示例。当用户双击后退按钮时,将执行
if
块,而
else
块的
run()
方法将在单击时执行。所以,在单击和双击时添加您想要的任何操作。