gpt4 book ai didi

android - 关于Android中UI线程上运行服务的问题

转载 作者:太空狗 更新时间:2023-10-29 15:38:34 26 4
gpt4 key购买 nike

我在一些地方读到服务在 UI 线程上运行(并且可以阻止它),但我不确定它到底是如何工作的。我的服务不需要与 UI 交互,但我确实需要能够处理来自 Activity 的并发请求,所以我不能使用 IntentService。所以我有几个问题:

  1. 如果服务是从一个线程中启动的,它是否仍会阻塞 UI?

  2. 如果服务中的所有工作都在一个线程中完成,它是否还会阻塞 UI?

  3. 如果我有多个 Activity 向同一个服务发送数据,这将如何工作?例如, Activity A 最初运行 startService(),它启动服务并使其完成一系列工作。当服务运行时, Activity B 需要向服务发送更多工作,因此它运行一个或一个 startService()。因此,同一个服务实例将处理来自两个 Activity 的 Intent ,但它们中的每一个都会受到该服务的影响吗?即使服务最初是在 Activity A 中启动的,每个 Activity 是否都有 UI 被阻止的风险?

  4. 是否有类似 IntentService 的东西,它在 UI 的“外部”运行,但可以处理异步输入,而不是等待一个 intent 完成后再开始另一个?

最佳答案

My service has no need to interact with the UI, but I do need to be able to process concurrent requests from activities, so I can't use the IntentService.

实际上,这听起来与您希望使用 IntentService 执行的操作完全一样。

If the service was started from within a thread, would it still block the UI?

是的,从哪里开始服务并不重要。与 UI 在同一线程中运行的服务是指服务的回调入口点(即 onCreate、onDestroy、onBind 等)。它们始终在应用的主线程中运行。

If all the work inside the service is done inside a thread, would it still block the UI?

不,事实上这是推荐的方法。 IntentService 通过自动为您创建一个工作线程并将 Intent(s) 交给线程来处理,从而为您简化了这一过程。如果您使用自己的线程池并将它们与进入的 Intent 一起排队,您可以完成同样的事情。请注意,您必须小心不要在池中创建太多线程,否则您可能会使系统不堪重负。

How does this work if I have multiple activities sending data to the same service? For example, activity A initially runs startService(), which starts the service and makes it do a bunch of work. While the service is running, acrivity B needs to send more work to the service, so it runs anorhter startService(). So, the same service instance will be processing intents from both activities, but do each of them get affected by that service? Does each activity run the risk of the UI being blocked, even though the service was originally started inside activity A?

我认为这可能是混淆的一部分。服务在属于服务包的进程的主线程中运行。来自其他包的 Activity 不会被阻止,除非出于某种原因它们专门等待某种类型的回复等。 Intent 本质上是进程间通信 (IPC) 消息,它位于由框架管理的特殊 IBinder 管道之上。 Intent 通过 Binder 发送并排队到内部处理程序,最终由框架用于在适当的回调中调用您的 Activity/Service/BroadcastReceiver。

Is there anything like an IntentService that runs 'outside' of the UI, but can handle asynchronous input instead of waiting for one intent to finish before starting another?

不,不是开箱即用的。但是,正如我上面提到的,您可以使用线程池甚至使用 AsyncTask 来完成此操作。请记住,您必须根据服务的生命周期管理线程和 AsyncTask 对象,因为这些东西不是生命周期感知的。

关于android - 关于Android中UI线程上运行服务的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20334699/

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