home鍵監聽、屏蔽和模擬home鍵
來源:程序員人生 發布時間:2014-10-10 08:00:00 閱讀次數:2817次
/**
* 模擬按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);
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈