Show confirmation dialog on back pressed event in android

Introduction

In this article i am going to explain about how to show confirmation dialog on back pressed event in android. In my previous articles i have explained about Android Signature Pad ExampleConvert speech to text in android with example code,Android contact picker example and Android Shared Preference Example.

Need for confirmation dialog

Nowadays it is a common practice to prompt for confirmation before exiting the app. And also it is much needed to avoid accidentally closing the app.

Create new project

To demonstrate how to show confirmation dialog on back pressed event in android i have created a new project called showalertdialogonexit. Refer Create a new project in android studio for creating new project.

Implementation

After creating the new project in the MainActivity.java file in the onBackPressed() method i have added the code to show confirmation dialog on back pressed event in android. Below is the complete code of MainActivity.java.

Below is the activity_main.xml file content.

Demo

Now if you run the application you will see the below output.

Output 1 of Show confirmation dialog on back pressed event in android Output 2 of Show confirmation dialog on back pressed event in android

Sourcecode

You can download the source code of how to show confirmation dialog on back pressed event in android from the below link.

Sourcecode of send email programmatically in android

 

 

 

If you like this article share your feedback in comments.

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!