February 16, 2016

Yesterday I was going through one of the Android app named 9GAG, while exiting the app I was asked to hit the back button twice to exit. I found this functionality really interesting. So, in this tutorial I’m going to implement that functionality.
Below I’ll be providing a simple Activity Class, with a normal layout with a simple Hello World.

package post.technoblog.presstwicetoleave;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;

public class PressTwiceActivity extends Activity {
    // # milliseconds, desired time passed between two back presses.
    private static final int TIME_INTERVAL = 3000;
    private long mBackPressed;

    protected void onCreate(Bundle savedInstanceState) {

    public void onBackPressed() {
        if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
        } else {
            Toast.makeText(getBaseContext(), "Tap twice to leave", Toast.LENGTH_SHORT).show();

        mBackPressed = System.currentTimeMillis();

In this program, I’m calculating the time interval between the first tap and the second tap. I’ve take a TIME_INTERVAL as 3 seconds, if the time interval between your first tap and second tap is more than 3 seconds, then you will be prompted the toast message again. On the other hand if the time interval between your first tap and second tap is in between 3 seconds, then only you will be able to exit the app. implementing this in your application is a good habbit.