How to Double Click on Back Button Twice to Exit App in Android

In some android games and app, when a user wants to exit the app or game a pop up will appear and ask the user to press the back button a number of times to exit the app.

In some cases, this is to prevent unexpected app exit. The code below illustrates how to double click back button twice to exit an app in android

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();

    private int k = 0;

    protected void onCreate(Bundle savedInstanceState) {

        Button buttonEffect = (Button)findViewById(;
        buttonEffect.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Button clicked ", Toast.LENGTH_SHORT).show();

    protected void onStart() {
        k = 0;

    public void onBackPressed() {
        if(k == 1) {
            Toast.makeText(MainActivity.this,"Click one more time to exist app", Toast.LENGTH_SHORT).show();
        } else {
            //exit app to home screen
            Intent homeScreenIntent = new Intent(Intent.ACTION_MAIN);

android backPressed button

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.


Add a Comment