Android - Confirm app exit with toast

后端 未结 6 681
滥情空心
滥情空心 2020-12-08 23:33

I\'m new to Android development and I want it so when the user presses the back button on the main activity, a toast message appears with a \"confirm exit by pressing the ba

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 00:24

    I would just save the time of the backpress and then compare the time of the latest press to the new press.

    long lastPress;
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if(currentTime - lastPress > 5000){
            Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG).show();
            lastPress = currentTime;
        }else{
            super.onBackPressed();
        }
    }
    

    You can also dismiss the toast when the app the back press is confirmed (cred @ToolmakerSteve):

    long lastPress;
    Toast backpressToast;
    @Override
    public void onBackPressed() {
        long currentTime = System.currentTimeMillis();
        if(currentTime - lastPress > 5000){
            backpressToast = Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_LONG);
            backpressToast.show();
            lastPress = currentTime;
        } else {
            if (backpressToast != null) backpressToast.cancel();
            super.onBackPressed();
        }
    }
    

提交回复
热议问题