如何在按下硬件主页按钮时显示警告对话框?

时间:2014-10-27 10:34:39

标签: android alertdialog

按下硬件主页按钮后,我使用以下代码显示警告对话框。

@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");
}

这在api版本低于14时工作正常。但在更高版本中,应用程序崩溃显示错误 - “添加窗口后窗口无法更改”。我开始知道错误是由于这一行

this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);

当我在评论中添加此行时,警报对话框未显示。 反正有没有在更高版本中显示警告对话框?

2 个答案:

答案 0 :(得分:3)

从技术上讲,你无法覆盖主页按钮。 如果您仍然感兴趣,可以尝试将其放入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>

答案 1 :(得分:-1)

您应该检查threads。它应该在runOnUiThread上运行

相关问题