i would like to show alertbox while user press back on phone.
so simply i use ::
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
try {
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
alertbox.setMessage("This is the alertbox!");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'Yes' button clicked", Toast.LENGTH_SHORT).show();
}
});
// set a negative/no button and create a listener
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Toast.makeText(getApplicationContext(), "'No' button clicked", Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
stopService(new Intent(this, BackServices.class));
finish();
} catch (Exception e) {
// TODO: handle exception
}
}
return super.onKeyDown(keyCode, event);
}
but problem is : when i press back alertbox show but it exit from application. i want stop exit from application until user press yes button.if user press no then get back to application
Well there are two things to make it possible
1.)
Remove
finish();from here, as it is the reason your activity gets close2.) Instead of
you can return false like this,