Android 屏蔽home键

/*
*(方案1)
*屏蔽home键 设置窗体 
* */
public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; //用于屏蔽home键
//在onCreate()方法中设置
this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
//在onDestroy()中取消屏蔽
this.getWindow().clearFlags(FLAG_HOMEKEY_DISPATCHED);

/*
*(方案2)
* 在onCreate()方法中写
* 注册home键点击广播  
* 地图导航activity没有继承BaseActivity,如果在onResume中注册,onPause中释放,那么在地图导航界面按下home键将不会拉起
* */
registerHomeKeyReceiver();

@Override
protected void onDestroy() {
super.onDestroy();
//释放home键相关资源
unregisterHOMEReceiver();
}

/*
*创建一个home键的广播接受器
* 5.1 8.0 可实现按下home键后,5~6s后拉起
* */
private class HomeKeyEventReceiver extends 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键,程序到了后台
startActivity(new Intent(HomeBaseActivity.this,QueryActivity.class));
}else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){
//表示长按home键,显示最近使用的程序列表
}
}
}
}

/*
*注册home键点击广播
* */
private void registerHomeKeyReceiver() {
homeReceiver = new HomeKeyEventReceiver();
// 注册广播,注意action:Intent.ACTION_CLOSE_SYSTEM_DIALOGS,添加这个action才能监听到按下Home键发出的广播
registerReceiver(homeReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}

/*
* 解除home键监听广播
* */
private void unregisterHOMEReceiver(){
if(homeReceiver != null){
// 解除广播
unregisterReceiver(homeReceiver);
}
}

/*
* (方案3)
* 重写onKeyDown,屏蔽home键 适用于4.4 ,5.1及以上不起作用
* */
@Override
public boolean onKeyDown( int keyCode, KeyEvent event) {
if (keyCode == event. KEYCODE_HOME) {
return true;
}
return super.onKeyDown(keyCode, event);
}

阅读更多
个人分类: Android
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭