简体   繁体   English

Android-绑定到其他应用程序的服务

[英]Android - Bind to a service from an other app

I have written 2 applications. 我已经编写了2个应用程序。 MyServiceApplication and MyActivityApplication . MyServiceApplicationMyActivityApplication On boot I launch MyService which runs as a remote service. 在启动时,我启动MyService ,它作为远程服务运行。 I want MyActivityApplication to communicate with it however MyActivityApplication does not have access to MyServiceApplication classes. 我希望MyActivityApplication与它进行通信,但是MyActivityApplication无法访问MyServiceApplication类。 All the examples I see online band an activity to a service in the following way: 我在网上看到的所有示例都通过以下方式将活动绑定到服务:

bindService(new Intent(Binding.this, MyService.class), mConnection, Context.BIND_AUTO_CREATE);

My Application needs to communicate with MyService . 我的应用程序需要与MyService进行通信。 The code is based off Google's MessengerService example. 该代码基于Google的MessengerService示例。

The trouble as I mentioned earlier is that the service I'm trying to bind to was started by an other application whose sole purpose is to start this service. 如前所述,我要绑定到的服务是由另一个应用程序启动的,该应用程序的唯一目的是启动该服务。

Is there a way to do this where I can keep both applications independent? 有没有一种方法可以使两个应用程序保持独立? The idea is that I will have a second, third and fourth application all of whom may communicate with the same service. 我的想法是,我将拥有第二,第三和第四应用程序,它们都可以与同一服务通信。

您应该在服务和应用程序之间有一个共享库,该共享库定义了用于与绑定服务进行通信的接口。

UPDATE: 更新:
This solution and code example was valid at the time it was written at: 2015 该解决方案和代码示例在编写时于2015年有效。
Please look for other solution relevant for this day. 请寻找与今天有关的其他解决方案。

ORIGINAL ANSWER: 原始答案:
You can define an intent-filer for your service with a specific action and bind to this service with intent assigned to this action. 您可以使用特定操作为您的服务定义一个Intent-Filer,并使用分配给该操作的Intent绑定到该服务。

MyServiceApplication: MyServiceApplication:

<service android:name=".MyService">
      <intent-filter>
        <action android:name="com.some.action.NAME" />
      </intent-filter>
</service>

MyActivityApplication: MyActivityApplication:

bindService(new Intent("com.some.action.NAME"), serviceConnection, Context.BIND_AUTO_CREATE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM