Android:如何检测“后退”按钮是否会退出应用程序(即这是堆栈上留下的最后一个活动)?
我想警告用户如果后按将完成堆栈上的最后一个活动,从而退出应用程序。我想弹出一个小面包并在接下来的几秒钟内检测到第二次后按,然后调用 finish()
。
我已经使用 onBackPressed()
编写了后按检测代码,但我找不到明显的方法来查看后堆栈上还剩下多少活动。
谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
reddit is fun 应用程序执行此操作 通过重写 onKeyDown 方法:
The reddit is fun app does this by overriding the onKeyDown method:
droid-fu 库通过检查正在运行的任务堆栈并查看下一个任务是否是安卓主屏幕。请参阅 https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/activities/BetterActivityHelper.java。
但是,我只会将这种方法用作最后的手段,因为它非常老套,无法在所有情况下工作,并且需要额外的权限才能获取正在运行的任务列表。
The droid-fu library does this by checking the stack of running tasks and seeing if the next task is the android home screen. See
handleApplicationClosing
at https://github.com/kaeppler/droid-fu/blob/master/src/main/java/com/github/droidfu/activities/BetterActivityHelper.java.However, I would only use this approach as a last resort since it's quite hacky, won't work in all situations, and requires extra permissions to get the list of running tasks.