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.

public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage(“Are you sure want to exit?”)
.setPositiveButton(“Exit”, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_MAIN);
.setNegativeButton(“Cancel”, null)


Change the Xxxx fo your activity name.

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:


You are commenting using your account. Logout /  Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout /  Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout /  Ubah )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d blogger menyukai ini: