大家可能或多或少在开发过程中遇到过监听HOME键的需求,但是使出了浑身解数也不一定能够监听到,当然除开系统开发的童鞋哈,下面给大家介绍的方法我在项目中已经测试过了,是可行的,方法就是利用广播来实现。代码如下:
- 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处理点
- }
- }
- }
- }
- }
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处理点
}
}
}
}
}
然后当然需要在onCreate里面注册该广播:
- receiver = new HomeKeyEventBroadCastReceiver();
- registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
receiver = new HomeKeyEventBroadCastReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
也需要在onDestroy里面解除该广播哦!