如何在按后退键时保持 Android Activity 运行

发布于 2024-11-01 07:23:00 字数 138 浏览 5 评论 0原文

我有一个活动,本质上是启动一个倒计时器。我需要它在使用其他 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

情话墙 2024-11-08 07:23:00

您必须使用服务,您可以在此处阅读文档。

You have to use a Service, you can read the documentation here.

夏末 2024-11-08 07:23:00

当活动不可见时,不应执行任何操作。它们基本上是 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.

桃气十足 2024-11-08 07:23:00

它被一些开发人员称为严重的“黑客”,但我已经成功检查了后退按钮是否被按下,以便成功清理我的项目。我最近将大部分代码移至 onPause() 事件,因为它是在按下后退按钮后应用程序关闭之前调用的。但是,如果这确实是您想要的,那就是您的程序,这是我使用的代码:

if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    killAndReturnParams(0);         
}

同样,这种方法之前已经被讨论过,但我很确定这是因为您不应该以任何原因覆盖后退按钮。用户应该能够在任何应用程序中使用后退按钮随时返回。

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:

if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
    killAndReturnParams(0);         
}

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.

昇り龍 2024-11-08 07:23:00
@Override
public void onBackPressed() {
    mActivity.moveTaskToBack(true);
}
@Override
public void onBackPressed() {
    mActivity.moveTaskToBack(true);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文