android 4.0.x Home键事件拦截与监听
在2.3.x 的主要做法如下,具体实现网上有很多文章
- @Override
- public void onAttachedToWindow() {
- this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
- super.onAttachedToWindow();
- }
代码移植到4.0.1后 this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); 这行报错,
错误提示:java.lang.IllegalArgumentException: Window type can not be changed after the window is added。
解决方案:通过系统log方式监听按键,但是必须是动态注册广播接收器,不能静态注册。具体代码如果:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/** 注册系统Log日志广播接收器 */
pressKeyLogRecevier();
}
/***
* Android4.0无法监听onKeyDown的Home键,所以通过系统log日志方式 注册系统log日志
*
*/
private void pressKeyLogRecevier() {
IntentFilter i = new IntentFilter();
i.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
this.registerReceiver(new InnerRecevier(), i);
}
/**
* <uses-permission android:name="android.permission.READ_LOGS"/>
*
* 添加系统Log日志,监听系统log日志判断是否按Home
* */
private class InnerRecevier extends BroadcastReceiver {
private final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
String reason = intent.getStringExtra("reason");
Log.i("TAG", "press=" + reason);
if (reason != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
writeConfig("isHome", true);
}
}
}
}
}