监听android home按键

大家可能或多或少在开发过程中遇到过监听HOME键的需求,但是使出了浑身解数也不一定能够监听到,当然除开系统开发的童鞋哈,下面给大家介绍的方法我在项目中已经测试过了,是可行的,方法就是利用广播来实现。代码如下:

  1. class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {
  2. static final String SYSTEM_REASON = "reason";
  3. static final String SYSTEM_HOME_KEY = "homekey";//home key
  4. static final String SYSTEM_RECENT_APPS = "recentapps";//long home key
  5. @Override
  6. public void onReceive(Context context, Intent intent) {
  7. String action = intent.getAction();
  8. if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
  9. String reason = intent.getStringExtra(SYSTEM_REASON);
  10. if (reason != null) {
  11. if (reason.equals(SYSTEM_HOME_KEY)) {
  12. // home key处理点
  13. } else if (reason.equals(SYSTEM_RECENT_APPS)) {
  14. // long home key处理点
  15. }
  16. }
  17. }
  18. }
  19. }
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里面注册该广播:

  1. receiver = new HomeKeyEventBroadCastReceiver();
  2. registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
receiver = new HomeKeyEventBroadCastReceiver();
registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));

也需要在onDestroy里面解除该广播哦!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值