-2

I have a Wordpress based news application. To make things faster I have bought a template which served most of needs. But in the app when i press back button on home or any first level screens it exits from the app.

How can I implement Exit only when the user presses back button twice?

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

0

Try this,

private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.
    private long mBackPressed;

    @Override
    public void onBackPressed()
    {
        if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) 
        { 
            super.onBackPressed(); 
            return;
        }
        else { Toast.makeText(getBaseContext(), "Tap back button in order to exit", Toast.LENGTH_SHORT).show(); }

        mBackPressed = System.currentTimeMillis();
    }
Mujammil Ahamed
  • 1,454
  • 4
  • 24
  • 50
  • 3
    Same comment as other post. Don't duplicate answers. http://stackoverflow.com/a/22332291/2308683 – OneCricketeer Aug 02 '16 at 07:25
  • @cricket_007 this is the right link . I would appreciate if OP would google once before asking here . Not trying to discourage but it's always better to look for answers before posting – VarunJoshi129 Aug 02 '16 at 07:28
  • @user3164647 Yes, that's why when you post a question here it gives you suggestions for other questions with similar titles. – OneCricketeer Aug 02 '16 at 07:31
0

After having to implement the same behaviour many times, decided to come up with an android library for it. DoubleBackPress Android Library, takes care of all the hassle, and provides easy templates to work with.

Example GIF of similar behavioural requirements.

First, add the dependecy to your application :

dependencies {
    implementation 'com.github.kaushikthedeveloper:double-back-press:0.0.1'
}

Now, the implementation :

// set the Action to occur on DoubleBackPress
DoubleBackPressAction doubleBackPressAction = new DoubleBackPressAction() {
    @Override
    public void actionCall() {
        // TODO : your code to exit the application
    }
};

// setup DoubleBackPress behaviour
DoubleBackPress doubleBackPress = new DoubleBackPress()
        .withDoublePressDuration(3000)                         //msec - timeout
        .withDoubleBackPressAction(doubleBackPressAction);

@Override
public void onBackPressed() {
    doubleBackPress.onBackPressed();
}
Kaushik NP
  • 6,733
  • 9
  • 31
  • 60