android home键重写,屏蔽,模拟

来源:互联网 发布:阿里妈妈淘宝客 编辑:程序博客网 时间:2024/06/07 12:48

 1.屏蔽home键的两种方法:

                      (1) 在以前版本中重写

                    public void onAttachedToWindow() {

                         this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
                        super.onAttachedToWindow();

                    }

                        (2) 4.0以上版本:在setContentView(R.layout.activity_main)前添加this.getWindow().setFlags(0x80000000, 0x80000000)就可以(但部分机型会出现屏                                                                         幕黑屏或者其他问题)。

          然而上面的两种方法并不能百分之百的屏蔽home键,有些手机会被屏蔽例如华为p8,而oppo却没被屏蔽(到现在我并没有找到彻底屏蔽的办法)。               

2.重写监听home键的两种方法:

         (1)屏蔽home键(采用上面的方法)+重写onkeydown

          (2)广播

                      class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
               static final String SYSTEM_REASON = "reason";
               static final String SYSTEM_HOME_KEY = "homekey";// home key
               static final String SYSTEM_RECENT_APPS = "recentapps";// long home key


            @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 (reason != null) {
if (reason.equals(SYSTEM_HOME_KEY)) {
// home key处理点
Log.e("homekey", "home键被点击");
Toast.makeText(BaseActivity.this, "Home键被点击", Toast.LENGTH_SHORT).show();
} else if (reason.equals(SYSTEM_RECENT_APPS)) {
// long homekey处理点
Log.e("homekey", "长按home键");
Toast.makeText(BaseActivity.this, "Home键长按", Toast.LENGTH_SHORT).show();
}
   }
        }
           }
            }

 注册广播:

HomeKeyEventBroadCastReceiver   receiver = new HomeKeyEventBroadCastReceiver();
registerReceiver(receiver, new IntentFilter(
Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

3.模拟home键:

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
                  

0 0
原创粉丝点击