android 屏蔽home鍵操作

來源:互聯網
上載者:User

1 重寫onAttachedToWindow

public void onAttachedToWindow() {  
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}

 

2 重寫onKeyDown

public boolean onKeyDown(int keyCode, KeyEvent event) {  
switch (keyCode) {
case KeyEvent.KeyEvent.KEYCODE_HOME:
Log.i(TAG,"KEYCODE_HOME");
return true;
}
return super.onKeyDown(keyCode, event);
}

3 android源碼 

因為android系統自己對home鍵在PhoneWindowManager中做了處理,不會返回到上層應用。查看原始碼:

\frameworks\policies\base\phone\com\android\internal\policy\impl\PhoneWindowManager.java 1089行

        if (code == KeyEvent.KEYCODE_HOME) {

// If a system window has focus, then it doesn't make sense
// right now to interact with applications.
WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;
if (attrs != null) {
final int type = attrs.type;
if (type == WindowManager.LayoutParams.TYPE_KEYGUARD
|| type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {

// the "app" is keyguard, so give it the key
return false;
}
final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;
for (int i=0; i<typeCount; i++) {
if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {
// don't do anything, but also don't pass it to the app
return true;
}
}
}

 

4 Dialog

如果在Activity彈出dialog,在Activity設定以上2個方法是沒辦法屏蔽的。 
其實,原理是一樣的,只是地方不一樣而已。 

final Dialog dialog = new Dialog(this);  
dialog.setContentView(R.layout.mydailog);
dialog.show(); //show應在setType之前,否則報錯
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);

dialog.setOnKeyListener(new android.content.DialogInterface.OnKeyListener(){
@Override
public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_HOME:
Log.i(TAG,"KEYCODE_HOME");
return true;
}
return false;
}
});

 

 

參考:

dialog,activity 屏蔽Home鍵詳解

WindowManager.LayoutParams

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.