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.

Tinggalkan Balasan

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

Logo WordPress.com

You are commenting using your WordPress.com account. Logout /  Ubah )

Foto Google+

You are commenting using your Google+ 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

%d blogger menyukai ini: