gpt4 book ai didi

android - 为什么不能直接访问本地服务?

转载 作者:行者123 更新时间:2023-11-29 01:39:42 25 4
gpt4 key购买 nike

据我所知,只能通过 IBinderMessengerAIDL 从 Activity 访问服务。

为什么不能直接调用服务实例的方法,例如, Activity ?

例如,当服务启动时,让服务将其实例保存在一个单例中,然后由 Activity 访问,允许它们直接调用服务的方法?

最佳答案

From what I can tell, a Service can only be accessed from an Activity via an IBinder, Messenger or AIDL.

这取决于您定义为“访问”的内容。 startService() 也可用于指示服务执行某些操作。

Why can a service instance's methods not be directly called by, for example, an activity?

Android 的组件模型是围绕松散耦合和可替换实现而设计的,其中替换可能是本地的或远程的。

此外,a service should only be running when it is actively delivering value to the user .因此,很多时候服务还没有运行,无论如何 Activity 都需要启动或绑定(bind)到服务。

例如,IntentService 只能通过 startService() 进行交互,因为 IntentService 只会在有命令时运行(通过 startService() 提供)进行处理。

最后,Service 的主要作用是作为操作系统的标记,让操作系统知道进程仍在工作,即使它在后台也是如此。 “让我们将 Service 填充到单例中”的模式表明您在所讨论的对象不一定是 Service 的情况下使用该服务。仅仅因为一个对象是单例并不意味着它需要是一个Service。因此,您需要坐下来确保您首先确切地知道为什么要使用服务,以及这是否最适合用户。

For example, when the service is started, have the service save its instance in a singleton which would then be accessed by Activitys, allowing them to directly call the service's methods?

没有什么能阻止您这样做。我不会——我将使用 startService() 和事件总线进行通信。而且,虽然在技术上可以做您想做的事,但它是否明智和可靠完全取决于服务的用例以及与该服务的通信。

关于android - 为什么不能直接访问本地服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25525595/

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