游戲中常常需要監聽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鍵的處理了!