ADVERTISEMENT

Android press back again to exit application

In this tutorial we are going to learn how to implement pressing back again to exit application. Am sure this is not the first time you are coming across this concept. Many apps tend to use this behavior to handle stuff in case user presses back button accidentally. I haven’t seen this concept annoying. Anyway let’s jump into the main business of the day.

You may also like:

1. Create New Project

Create new android application and name it PressBackAgainToExit, please note, you can name your application anything you want.

For this tutorial, there is no special permissions required so we will concentrate only with MainActivity.

MainActivity.java

package hacksmile.com.pressbackagaintoexit;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private static boolean userPressedBackAgain = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    }

    @Override
    public void onBackPressed() {
        if (!userPressedBackAgain) {
            Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
            userPressedBackAgain = true;
        } else {
            onBackPressed();
        }

        new CountDownTimer(3000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                userPressedBackAgain = false;
            }
        }.start();

    }
}


2. Explanation



First we have created a boolean variable userPressedBackAgain = false. This variable will enable us to know when user pressed back again. To detect when user presses back button, we overrided onBackPressed(). If the variable is false, update userPressedBackAgain = true, so that when user presses back within 3 seconds, the application will exit. We have created timer to make sure, if user delays for at least 3 seconds, system will request them to press back again.

Thant’s how simple it is. Please let me get your reactions in the commenting system below. Thanks



AdBlock Detected!
This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker or pausing adblock for this website.