简体   繁体   中英

How to show alert dialog when hardware Home button is pressed?

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?

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM