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.


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

You may also like to read

Exit from Activity with twice “Back” b... When we are doing some important operation or work on activity and it may possible that by mistake we pressed "back" button. Then what?? This will sim...
DevFestAhm – GDGAhmedabad 2015 – Aweso... Google Developer Group is Open for all including students, newbies, developers and anyone for all who are interested in Google technologies. It is Guj...
Read Logs programmatically in Android In this blog you will learn how to read logs programmatically in Android and used for bug report purposes. Its easy to read logs from Logcat an...
RecyclerView in Android Studio – Part 1 What is RecyclerView? RecyclerView is advanced version of ListView. It is designed to work with large scale of data with better performance and mem...
Share on Facebook0Share on Google+4Tweet about this on TwitterShare on LinkedIn0Share on Reddit0Pin on Pinterest0Share on Tumblr0Email this to someone