gpt4 book ai didi

android - 如果应用程序在后台,如何不启动 Activity

转载 作者:行者123 更新时间:2023-11-29 19:41:37 25 4
gpt4 key购买 nike

在我的应用程序中,我有两个 Activity,A 和 B。A 下载一些数据并在下载数据时启动 Activity B - 这是通过 BroadcastReceiver 完成的,其 onReceive() 方法通过 BroadcastReceiver 启动 B一个 Intent 。

我的问题是,当我的应用程序进入后台,而数据仍在下载时(例如,我启动我的应用程序,然后快速单击“主页”按钮,或使用方形“切换”按钮切换应用程序),我的下载数据后,应用程序会返回前台……很烦人。

到目前为止,我已经尝试在 Intent 上添加标志和设置操作以避免这种情况,包括 intent.setAction(Intent.ACTION_SCREEN_ON),这可能接近答案:它在运行 API 16 但不是我的运行 API 22 的设备。

最佳答案

通常,人们使用服务在后台执行操作。服务没有 UI(原因很明显)。根据定义,Activity 是前台任务 - 您看到的行为正是应该发生的。

我强烈建议不要尝试将 Activity 变成服务。当您可以使用专为您寻求的目的而设计的 Android 功能时,您将在整个应用程序生命周期内工作。

这是一个快速资源,我建议您阅读更多关于服务的内容:

https://developer.android.com/training/best-background.html

The BroadcastReceiver for an Activity receives and processes Intent objects even when your app is in the background, but doesn't force your app to the foreground. If you want to notify the user about an event that happened in the background while your app was not visible, use a Notification. Never start an Activity in response to an incoming broadcast Intent.

关于android - 如果应用程序在后台,如何不启动 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38576814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com