Android 中有没有同步获取服务的方法?

发布于 2024-10-21 12:55:26 字数 134 浏览 1 评论 0原文

我需要在Android中同步获取一个服务。我确信它已经在运行,我只需要在我的适配器中访问它即可。我应该在服务可用后传递一个引用,还是可以使用 context.getService(...) 的效果来获取它?推荐的解决方案是什么?

I need to grab a service synchronously in Android. I'm sure it's already running, I just need to access it in my adapter. Should I just pass a reference once the service becomes available, or can I use something to the effect of context.getService(...) to get it? What is the recommended solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

如日中天 2024-10-28 12:55:26

我相信您有一个创建和销毁适配器的活动。因此,适配器的生命周期应该与您的活动的生命周期相匹配。结论是在创建适配器时将服务的引用传递给适配器,因为它是绑定和取消绑定服务的活动。 :-)

I believe you have an activity where the adapter is created and destroyed. Therefore the adapter's lifecycle should match the lifecycle of your activity. The conclusion would be to pass a reference of the service to the adapter on its creation, as it is the activity that binds and unbinds the service. :-)

孤蝉 2024-10-28 12:55:26

您感兴趣的是提供绑定服务的概念。查看 Service SDK 页面上的本地服务示例示例:

http://developer.android.com/reference/android/app/Service.html

此示例演示如何绑定到您创建的服务,以便您可以获得对其的长期引用并直接调用当你受到约束时。当您以这种方式绑定/取消绑定到服务时,您也不必担心显式调用启动和停止。仅当至少有一个组件绑定到该服务时,该服务才会运行。

希望有帮助!

What you are interested in is the concept of making a bound service. Take a look at the Local Service Sample example on the Service SDK page:

http://developer.android.com/reference/android/app/Service.html

This example shows how to bind to a service you create so you can get a standing reference to it and make direct calls to it while you are bound. When you bind/unbind to a service in this fashion, you also do not have to worry about calling start and stop explicitly. The service is only running as long as there is at least one component bound to it.

Hope that helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文