Home  >  Article  >  Java  >  How to Implement the \"Double Back Press to Exit\" Functionality in Android Activities?

How to Implement the \"Double Back Press to Exit\" Functionality in Android Activities?

DDD
DDDOriginal
2024-11-02 03:25:02556browse

How to Implement the

Handling Double Back Press to Exit Android Activities

Many Android apps employ the "double press back button to exit" functionality, prompting users with a toast message after the first press. While this behavior is prevalent, it's not an inherent feature provided by the Android platform.

Solution:

To implement double back press to exit in an activity, you can create a boolean flag (e.g., doubleBackToExitPressedOnce) to track the first back button press. Here's an example implementation:

<code class="java">private boolean doubleBackToExitPressedOnce = false;

@Override
public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }

    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();

    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    }, 2000);
}</code>

This code initializes the doubleBackToExitPressedOnce flag to false. When the back button is pressed, it checks the flag. If it's false, it means the user is pressing the back button for the first time, so it sets the flag to true and displays a toast message.

A handler is used to reset the flag back to false after 2 seconds. This allows the user to press the back button twice within 2 seconds to exit the activity. Otherwise, the flag will be reset, and the back button press will navigate back to the previous screen or close the activity as usual.

The above is the detailed content of How to Implement the \"Double Back Press to Exit\" Functionality in Android Activities?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn