Android double click the implementation method to exit

  • 2020-06-15 10:10:40
  • OfStack

This article illustrates the implementation of Android's double-click exit. Share to everybody for everybody reference. Specific implementation methods are as follows:

Method 1:

Override the onBackPressed method to directly listen for the return key (2.0 or above is recommended for higher versions)

@Override  
public void onBackPressed() { 
     
       long currentTime = System.currentTimeMillis();   
       if((currentTime-touchTime)>=waitTime) {   
        // let Toast Display time and wait time are the same  
           Toast.makeText(this, " then 1 Time to quit ", (int)waitTime).show();   
           touchTime = currentTime;   
       }else {   
           finish();   
       }   
}

Method 2: (Recommended)

long waitTime = 2000;    
long touchTime = 0;  
@Override 
public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if(event.getAction() == KeyEvent.ACTION_DOWN && KeyEvent.KEYCODE_BACK == keyCode) {   
        long currentTime = System.currentTimeMillis();   
        if((currentTime-touchTime)>=waitTime) {   
            // let Toast Display time and wait time are the same  
            Toast.makeText(this, " then 1 Time to quit ", (int)waitTime).show();   
            touchTime = currentTime;   
        }else {   
            finish();   
        }   
        return true;   
    }   
    return super.onKeyDown(keyCode, event);   
}

I hope this article has been helpful for your Android programming.


Related articles: