如何在Java中实现双击返回键退出并分阶段显示Snackbar对话框
Double Back Press to Exit Implementation in Java Android
Got it, let's walk through a straightforward implementation that matches your exact requirements:
Step-by-Step Code Implementation
First, add these variables to your Activity class to track the back press timing and current Snackbar:
private long mFirstBackPressedTime = 0; private Snackbar mCurrentSnackbar;
Then override the onBackPressed() method to handle the double back press logic:
@Override public void onBackPressed() { // Dismiss any active Snackbar before showing a new one if (mCurrentSnackbar != null && mCurrentSnackbar.isShown()) { mCurrentSnackbar.dismiss(); } long currentTime = System.currentTimeMillis(); // Check if we're within the 2-second window after first back press if (currentTime - mFirstBackPressedTime < 2000) { // Show confirmation Snackbar with action button mCurrentSnackbar = Snackbar.make( findViewById(android.R.id.content), "do you want to exit ?", Snackbar.LENGTH_LONG ).setAction("YES", v -> { // Exit the app gracefully finishAffinity(); // Closes all related activities // For older API versions (pre-16), use finish() with appropriate intent flags }); mCurrentSnackbar.show(); // Reset the timer to avoid repeated triggers mFirstBackPressedTime = 0; } else { // First back press: show prompt to press again mCurrentSnackbar = Snackbar.make( findViewById(android.R.id.content), "press back again to exit", Snackbar.LENGTH_LONG ); mCurrentSnackbar.show(); // Record the time of the first press mFirstBackPressedTime = currentTime; } }
Key Details Explained
- Timing Check: We use
mFirstBackPressedTimeto track when the first back press happens. If the second press comes within 2000ms (2 seconds), we trigger the confirmation Snackbar. - Snackbar Management:
mCurrentSnackbarensures we don't have overlapping Snackbars—we dismiss any active one before showing a new message. - Graceful Exit:
finishAffinity()is used instead ofSystem.exit(0)because it follows Android's lifecycle rules, properly closing all activities associated with your app. - Snackbar Duration:
Snackbar.LENGTH_LONGdefaults to ~2 seconds, which aligns perfectly with your requirement.
Notes
- If you're implementing this in a Fragment, replace
findViewById(android.R.id.content)with your Fragment's root view (e.g.,getView()). - Make sure your app has the AndroidX Snackbar dependency (most modern projects do, but if not, add it to your
build.gradle).
内容的提问来源于stack exchange,提问作者user11098644
相关产品推荐
相关产品推荐

