0

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?

Chowdary102
  • 106
  • 2
  • 12

2 Answers2

3

Technically you cann't override home button. If you still interested, you could try putting this in your main activity in AndroidManifest.xml

<activity
...
android:launchMode="singleTask">
<intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
    <category android:name="android.intent.category.HOME" />
    <category android:name="android.intent.category.DEFAULT" />
    ....
</intent-filter>

samsad
  • 1,336
  • 1
  • 10
  • 15
-1

You should check it threads. It should run on the runOnUiThread

marcel
  • 315
  • 4
  • 10