Search code examples
androidback-buttononbackpressed

how can i add multiple click on back pressed button


How can I add multiple backpressed button like when i press back button that show me PRESS DOUBLE CLICK TO EXIT after toast message when i click double on press button then the app exit... i did this method but its just twice to exit the app i want to implement 3 times

    if (doubleBackToExitPressedOnce){
        super.onBackPressed();
        doubleBackToExitPressedOnce = false;

    }

    else {
        doubleBackToExitPressedOnce = true;
        Toast.makeText(this, "Double Press to exit", Toast.LENGTH_SHORT).show();
    }

Solution

  • I would suggest that way:

        int counter = 0;
    
    
        ....
    
        public void onBackPressed() {
                            counter++;
                            if(counter > 2){
                                System.exit(0);
                            }else{
                                Toast.makeText(this, "TRIPLE CLICK TO EXIT!", Toast.LENGTH_SHORT).show();  
                            }
    
                            final long DELAY_TIME = 3000L;
                            new Thread(new Runnable() {
                                public void run(){
                                    try {
                                        Thread.sleep(DELAY_TIME);
                                        counter = 0;
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).start();
    }