How to exit the android application on backpress?

前端 未结 4 1368
夕颜
夕颜 2021-01-07 04:21

The situation could be like say, I\'ve 5 activities. Say Main activity, Activity 1, Activity 2, Activity 3 and Activity 4.

One can use the Activity 1,2,3 & 4 dir

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-07 05:02

    It is a good code practice to write double back press to exit Main Activity.

    boolean doubleBackToExitPressedOnce = false;
    
    @Override
    public void onBackPressed() {
    if (doubleBackToExitPressedOnce) {
        super.onBackPressed();
        return;
    }
    
    this.doubleBackToExitPressedOnce = true;
    Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
    
    new Handler().postDelayed(new Runnable() {
    
        @Override
        public void run() {
            doubleBackToExitPressedOnce=false;                       
        }
    }, 2000);
    

    }

提交回复
热议问题