How to enable pressed back button to exit the app on android studio

When the user presses the back button, the application will display a confirmation dialog. I added this code outside onCreate. And it works well.

——————————————————–
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(“Are you sure want to exit?”)
.setPositiveButton(“Exit”, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
XxxxActivity.super.onBackPressed();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
finish();
}
})
.setNegativeButton(“Cancel”, null)
.show();
}

—————————-

Change the Xxxx fo your activity name.