In this video it shows the code to check exit confirmation on clicking back button in Android App. Basically, for this implementation it follows below two steps:
- Override OnBackPressedCallback method.
- Create and Show AlertDialog
I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com
Complete source code and other details:
package com.programmerworld.exitconfirmationonbackbuttonpress;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
@Override
public void handleOnBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
alertDialogBuilder.setMessage("Do you want to exit?");
alertDialogBuilder.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finishAndRemoveTask();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
return insets;
});
}
}
No changes in any other code or file.
Screenshots:
On Clicking No
On Clicking Yes
Project Folder:
Complete Project can be accessed at the below link by paying USD 9.
https://drive.google.com/file/d/1EzqfnsL7-ugoRUaOiJK_lVpHKpDu-tCp/view?usp=drive_link
Excerpt:
The provided content demonstrates how to implement an exit confirmation on back button press in an Android app. The key steps include overriding the OnBackPressedCallback method and creating/showing an AlertDialog. The provided source code showcases the necessary implementation within the MainActivity class. In addition, screenshots and a link to purchase the complete project for $10 are included.