Android – 用烤面包确认应用程序退出

我是Android开发的新手,我想这样做,所以当用户按下主活动的退button时,会出现一个Toast消息,并带有“再次按下返回button确认退出”消息。 我将如何做到这一点? 这是我迄今为止:

@Override public void onBackPressed() { // TODO Auto-generated method stub super.onBackPressed(); Toast s = Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG); s.show(); wait(); public boolean onBackPressed() { finish(); } } 

Solutions Collecting From Web of "Android – 用烤面包确认应用程序退出"

我只是保存后期的时间,然后比较最新的新闻媒体的时间。

 long lastPress; @Override public void onBackPressed() { long currentTime = System.currentTimeMillis(); if(currentTime - lastPress > 5000){ Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG).show(); lastPress = currentTime; }else{ super.onBackPressed(); } } 

您也可以在应用程序确认后按下敬酒(cred @ToolmakerSteve):

 long lastPress; Toast backpressToast; @Override public void onBackPressed() { long currentTime = System.currentTimeMillis(); if(currentTime - lastPress > 5000){ backpressToast = Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG); backpressToast.show(); lastPress = currentTime; } else { if (backpressToast != null) backpressToast.cancel(); super.onBackPressed(); } } 
 private long mLastPress = 0; const int TOAST_DURATION = 5000; Toast onBackPressedToast; @Override public void onBackPressed() { long currentTime = System.currentTimeMillis(); if (currentTime - mLastPress > TOAST_DURATION) { onBackPressedToast = Toast.makeText(this, R.string.press_once_again_to_exit, Toast.LENGTH_SHORT); onBackPressedToast.show(); mLastPress = currentTime; } else { if (onBackPressedToast != null) { onBackPressedToast.cancel(); //Difference with previous answer. Prevent continuing showing toast after application exit. onBackPressedToast = null; } super.onBackPressed(); } } 

在我的情况下完美工作

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

在新版本中,您可以使用快餐栏而不是烤面包片。

 import android.support.design.widget.Snackbar; ... Snackbar.make(content, "Click BACK again to exit", Snackbar.LENGTH_SHORT).setAction("Action", null).show(); ...