Display Alert on Back button pressed in Android Studio

Some time in your application, it is needed to prompt user before taking back him to previous page or exit from application. In this article, we will see how you can prompt user on pressing back button.

Alert means to get user’s input when needed. Most of us played games and when we try to exit it by pressing “Back” button in Android phone, it ask for “Do you really want to exit?”.

So, in this article we are going to learn how to prevent user to exit from application without giving response.

Step 1

Create a new Project with following parameters.

alert back press 1

Step 2

Open your Main Activity file, in my case it is BackPressActivity.java and paste following code inside.

Let’s understand Alert Dialog and its different methods.

  1. builder.setCancelable(false); which means that user can’t cancel this dialog by pressing back again or touch outside the alert dialog box and dismiss it. So user has to press one of the options you have provided to him.
  2. builder.setMessage(“Do you want to Exit?”); Here you can write your own message which will be displayed to user in alert.
  3. builder.setPositiveButton will set a positive button in left side. Parameter will accept the name of that button as you can see in code is “Yes”.
  4. builder.setNegativeButton will set a negative button in right side. Parameter will accept the name of that button as you can see in code is “No”

When you set this button, you need to pass a listener which will be fired when user click one of the button.

Step 3

Run your application.

Summary

In this article, we learned “How to show Alert Dialog” and “Show dialog at BACK button pressed”.

Share on Facebook0Share on Google+4Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone