如何在按后退键时保持 Android Activity 运行
我有一个活动,本质上是启动一个倒计时器。我需要它在使用其他 Android 应用程序(例如 Gmail 和媒体播放器等)时继续运行。
当我点击后退按钮时,我的 Activity 似乎退出了。当用户单击后退/主页键等时,我需要做什么才能保持它运行。
I have an activity that essentially launches a CountDownTimer. I need this to continue running while using other Android apps, such as Gmail, and media players etc.
When I hit the back button, my Activity seems to quit. What do I need to do to keep it running when the user clicks the back/home keys etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须使用服务,您可以在此处阅读文档。
You have to use a Service, you can read the documentation here.
当活动不可见时,不应执行任何操作。它们基本上是 UI 组件。
您应该查看服务。它们可以作为后台进程运行并且不包含 UI。
Activities are not supposed to be doing anything when they are not visible. They are basically UI components.
You should be looking into services. These can run as a background process nd contain no UI.
它被一些开发人员称为严重的“黑客”,但我已经成功检查了后退按钮是否被按下,以便成功清理我的项目。我最近将大部分代码移至
onPause()
事件,因为它是在按下后退按钮后应用程序关闭之前调用的。但是,如果这确实是您想要的,那就是您的程序,这是我使用的代码:同样,这种方法之前已经被讨论过,但我很确定这是因为您不应该以任何原因覆盖后退按钮。用户应该能够在任何应用程序中使用后退按钮随时返回。
It's been referred to as a serious "hack" by a few developers, but I've successfully checked for the back button being pressed so as to successfully clean my project up. I've recently moved most of this code to
onPause()
event because it's called right before the app goes down after back button is pressed. However, if it's really what you desire, it's your program and here's the code I used:Again, this method has been talked down before, but I'm pretty sure it's because you're not supposed to override the back button for any reason. The user is supposed to be able to use the back button to return at any point, in any app.