2014-10-27 74 views
0

我已經使用下面的代碼來顯示按下硬件主頁按鈕時的警告對話框。如何在按下硬件主頁按鈕時顯示警報對話框?

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

當我把這條線在評論警報對話框不顯示。 無論如何在更高版本中顯示警報對話框?

回答

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

您應該檢查它threads。它應該在runOnUiThread上運行

相關問題