Double tap back button to exit app – Android

double_tap_exit

Double tap to exit – Android Programming

It is always good to have this feature double-click to exit. Because sometimes when someone is in your main activity, they may touch the back button unintentionally. So by implementing this feature one cannot exit from the app with just one tap on the back button. They have to tap twice to exit the app.

double_tap_exit

Let’s see how it’s done. Let’s create a simple project with just one activity. There won’t be anything on the activity layout. We will add just a TextView, which does nothing.

Now when someone taps the back button a toast will be displayed with a message “Please tap again to exit“. But they have to tap twice the back button within a given time period. Generally 2 or 3 seconds.

More Android tutorials :

Share app link – Android Programming

Working with SharedPreferences – Android

Now that you know what we are going to do, Go to Android Studio and create a project. Name it whatever you want.

There is nothing much in our activity layout file. It looks like this –

Go to your activity class, in our case, it is MainActivity.java. And override onBackPressed method.

The above method is called when someone taps the back button.

This is our final code –

So we have taken a boolean variable “mPressedOnce” and set it to false.

Now when someone presses the back button the onBackPressed method is called. Inside onBackPressed, we have an if condition. The condition is, call super.onBackPressed only when mPressedOnce == true.

When someone clicks the back button, mPressedOnce is set to true.

Then the toast displays “Press BACK again to exit“. Now mPressedOnce is true and the if condition gets executed.

We are also setting 2 seconds time interval or 2 seconds interval from the last back pressed. If the user doesn’t tap the back key within 2 seconds the mPressedOnce is set to false again.

As of now, everything thing is good if you have only one activity or calling finish() when switching activities. But there may be a situation when you don’t want to call finish() when switching activities. In this case, the app won’t  be closed if there is any other activity in the back stack. Rather on double click, the activity which has not finished yet or still in the back stack will open.

To clear all the unfinished activities (previous activities) and exit from the app completely, we will call the method finishAffinity() of Activity class. Update your onBackPressed code with the below code –

So as you can see here we have used finishAffinity(). What this does is, it finishes the current activity as well as all the previous activities.

Note – It was added in API level 16. So it won’t work below 16.

That’s all. Change the time interval according to your need and run the project.

 

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *