android应用中监听按下HOME键

本文探讨了在Android应用中判断应用是否被置于后台的方法,分析了onUserLeaveHint()方法的误用,并介绍了如何使用Intent.FLAG_ACTIVITY_NO_USER_ACTION来避免误触发通知,以及提供了一种简化判断应用后台状态的实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近项目中有个需求,就是判断我们的应用是否被置于后台,以前只是简单的以为在activty中判断onUserLeaveHint()是否被执行即可,这个是被该方法的说明给骗了,说明如下:

Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause callback.

This callback and onUserInteraction are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.

红色部分。后来经验证该方法在activity之间跳转时也被执行,这样就明显达不到要求啦。

 

还有就是API中虽然后KeyEvent.KEYCODE_HOME,但是根本就监听不到。

 

目前网上常用的做法是,构造一个ArrayList<Activity> list = new ArrayList<Activity>();然后再onresume()中添加到该list中,在onstop()中判断list中所有activity的onstop()是否被执行,哇。。。很是繁琐。

 

下面是我发现的一种做法,简单方便:

重点还是在onUserLeaveHint()上,再加上Intent.FLAG_ACTIVITY_NO_USER_ACTION,

If set, this flag will prevent the normal android.app.Activity.onUserLeaveHint callback from occurring on the current frontmost activity before it is paused as the newly-started activity is brought to the front.

Typically, an activity can rely on that callback to indicate that an explicit user action has caused their activity to be moved out of the foreground. The callback marks an appropriate point in the activity's lifecycle for it to dismiss any notifications that it intends to display "until the user has seen them," such as a blinking LED.

If an activity is ever started via any non-user-driven events such as phone-call receipt or an alarm handler, this flag should be passed to Context.startActivity, ensuring that the pausing activity does not think the user has acknowledged its notification.

 

OK,剩下的我就不多说了。。。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值