程序员人生 网站导航

home键监听、屏蔽和模拟home键

栏目:互联网时间:2014-10-10 08:00:00
 
/** * 模拟按home键 * 程序退到后台运行 * @param context */ private void imitatePressHome(Context context) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.addCategory(Intent.CATEGORY_HOME); context.startActivity(intent); } /** * 注册home键监听 * @param context */ private void registerHomeReceiver(Context context) { context.registerReceiver(mHomeKeyEventReceiver, new IntentFilter( Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); } /** * home键处理 */ private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() { String SYSTEM_REASON = "reason"; String SYSTEM_HOME_KEY = "homekey"; String SYSTEM_HOME_KEY_LONG = "recentapps"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_REASON); if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) { //表示按了home键,程序到了后台 Toast.makeText(context, "home pressed", 1000).show(); }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){ //表示长按home键,显示最近使用的程序列表 Toast.makeText(context, "home long pressed", 1000).show(); } } } }; /** * home键屏蔽 */ @Override public void onAttachedToWindow() { // TODO Auto-generated method stub this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD); super.onAttachedToWindow(); }


在4.0 以后,无论是在onCreate()还是onAttachedToWindow()中都不能重设window的Type,想用此法屏蔽Home键无效!
4.0以上执行这段代码会报java.lang.IllegalArgumentException: Window type can not be changed after the window is added.至于怎么屏蔽,现在网上还没有很好的解决办法,mtk的到是有解决办法,其他平台的就不行了....除非修改底层框架
mtk的解决办法:
public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000;
在onCreate中执行
this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
------分隔线----------------------------
------分隔线----------------------------

最新技术推荐