我有两个应该绑定到服务的应用程序。 如果服务尚未启动,应用程序1将启动该服务。
startService(new Intent(this, Listener.class));
然后它绑定服务。
bindService(new Intent(this, Listener.class), mConnection, 0);
之后将调用onServiceConnected
并且活动将完成,服务将解除绑定。该服务仍在运行(" 0"在bindService中)。
直到这里一切都很好。
第二个App的代码看起来完全一样。但它没有启动服务,因为它已经运行。
bindService
返回true。所以一切都很好看。但是onServiceConnected
永远不会被调用。
我发现了这个:
onServiceConnected() not called
看起来像我的问题,但活动在同一个应用程序...
我尝试了getApplicationContext.bindService
但是在第一个应用程序中它抛出异常并且不绑定我的服务,在第二个它没有改变任何东西。
我想我需要更多像getSystemContext
这样的东西,因为活动不在同一个App中。
在我的ManifestFiles中,我提出以下内容:
<service
android:name="com.example.tools.Listener"
android:label="Listener"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >
<intent-filter>
<action android:name="com.example.tools.Listener" />
</intent-filter>
</service>
我希望有人能帮助我。
祝你好运
费边
答案 0 :(得分:0)
我认为您缺少要在AndroidManifest.xml中启动的服务的exported
属性
答案 1 :(得分:0)
以下是我解决问题的方法。 无论哪个应用程序首先启动都无关紧要。
应用程序检查服务是否正在运行(https://stackoverflow.com/a/5921190/8094536) 如果它没有运行我启动服务。为此,我设置了componentName并启动了服务:
Intent intent = new Intent();
ComponentName component= new ComponentName("com.example.firstApp", "com.example.tools.Listener");
intent.setComponent(component);
startService(intent);
而不是我绑定它:
this.bindService(intent, mConnection, 0)
如果服务已在运行,我设置componentName并直接绑定它:
Intent intent = new Intent();
ComponentName component= new ComponentName("com.example.secondApp", "com.example.tools.Listener");
intent.setComponent(component);
this.bindService(intent, mConnection, 0)
我的AndoridManifest.xml看起来像这样:
<service
android:name="com.example.tools.Listener"
android:label="Listener"
android:exported="true">
<intent-filter>
<action android:name="com.example.tools.Listener" />
</intent-filter>
</service>
注意:如果您不使用系统应用程序,请不要使用android.permission.BIND_ACCESSIBILITY_SERVICE
。
现在两个应用都已绑定,onServiceConnected
被调用。
感谢@pskink