It is not possible for Home button click. Android doesn’t allow to override home button click methods. This is to avoid any hijacking of home button click which will avoid user to return to main home page of Android OS.
However, for back button this functionality can be implemented. In back button press, it can confirm before exiting the App.
Code snippet for the back button press is below. This code can be added in the onCreate method of the App’s MainActivity Class.
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?")
.setCancelable(true)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finishAndRemoveTask();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
});
Excerpt:
It’s not possible to override the Home button click on Android to prevent hijacking. However, you can implement a functionality for the back button press. A code snippet for handling the back button press in the MainActivity class is provided. It creates an alert to confirm exiting the app.