I had used the following code to show an alert dialog when Hardware home button is pressed.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
System.out.println("KEYCODE_HOME");
showDialog("'HOME'");
return true;
}
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
System.out.println("KEYCODE_BACK");
showDialog("'BACK'");
return true;
}
if ((keyCode == KeyEvent.KEYCODE_MENU)) {
System.out.println("KEYCODE_MENU");
showDialog("'MENU'");
return true;
}
return false;
}
void showDialog(String the_key){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("You have pressed the " + the_key + " button. Would you like to exit the app?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
finish();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("CoderzHeaven.");
alert.show();
}
@Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
public void onUserLeaveHint() {
super.onUserLeaveHint();
System.out.println("HOMEEEEEEEEE");
}
This works fine in api version less than 14. But in higher versions app gets crashed showing an error- "Window cannot be changed after a window is added". And i came to know the error is due to this line
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
When i put this line in comment the alert dialog is not showing. Is there anyway to show alert dialog in higher versions?