游戏中常常需要监听Android HOME键,当HOME键下压时,往往需要做一些状态保存,音效停止等操作,那么如何做,才能监听到HOME键呢?我们知道HOME是系统键,app中无法通过onKey这些函数来处理。要妥善的处理HOME键,首先需要看看HOME键下压时,系统做了些什么。
一、HOME键之来龙去脉
请见下图:
二、app中对于HOME键广播事件的接收
首先,自定义一个BroadcastReceiver:
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处理点
} else if (reason.equals(SYSTEM_RECENT_APPS)) {
// long home key处理点
}
}
}
}
}
其次,生成且注册之
receiver = new HomeKeyEventBroadCastReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
这样,我们就可以在app中进行HOME键的处理了!