標籤:
今天在遇到一個要屏蔽Home鍵的問題,研究一上午終於解決,方法記錄於下:
在Android2.3版本以下重寫以下方法就能屏蔽Home鍵:
public void onAttachedToWindow() { this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow();}
在Android4.0以上版本用onAttachedToWindow()方法會報錯,需要利用以下方法屏蔽:
public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //需要自己定義標誌public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);//關鍵代碼 setContentView(R.layout.main);}
再重寫onKeyDown方法即可:
@Overridepublic boolean onKeyDown( int keyCode, KeyEvent event) { if (keyCode == event. KEYCODE_HOME) { return true; } return super.onKeyDown(keyCode, event);}
在AndroidMainfest.xml需要加許可權:
<uses-permission android:name = "android.permission.DISABLE_KEYGUARD"/><!-- 屏蔽HOME鍵需要的許可權 -->
在設定檔中,在你使用了Notification的activity中加一個屬性android: android:launchMode="singleInstance"
Android開發_關於如何屏蔽Home鍵