【问题标题】:onServiceConnected() not called in second ApponServiceConnected() 未在第二个应用程序中调用
【发布时间】:2017-08-03 10:59:00
【问题描述】:

我有两个应该绑定到服务的应用程序。 应用 1 启动服务(如果尚未启动)。

startService(new Intent(this, Listener.class));

然后它绑定服务。

bindService(new Intent(this, Listener.class), mConnection, 0);

之后onServiceConnected 将被调用,Activity 将结束,服务将被解除绑定。服务仍在运行(bindService 中的“0”)。

直到这里一切都很好。

第二个 App 的代码看起来一模一样。但它不会启动服务,因为它已经运行。 bindService 返回真。所以一切看起来都很好。但是onServiceConnected 永远不会被调用。

我发现了这个: onServiceConnected() not called 看起来像我的问题,但活动在同一个应用程序中...... 我试过getApplicationContext.bindService,但在第一个应用程序中它抛出一个异常并且不绑定我的服务,在第二个它没有改变任何东西。 我想我需要更多类似getSystemContext 的东西,因为活动不在同一个应用程序中。

在我的 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>

我希望有人可以帮助我。

最好的问候

法比安

【问题讨论】:

  • “第二个App”如何创建Intent来启动“第一个”应用服务?
  • 你的“第二个应用程序”的代码是什么?你如何创建Intent
  • @pskink “第二个App”的代码与“第一个App”的代码相同。所以 Intent 是这样创建的“new Intent(this, Listener.class)”。该服务位于两个应用程序都引用的库中。
  • 如果您使用“应用二”中的new Intent(this, Listener.class) 那么您想如何在“应用一”中启动服务?
  • @pskink 我在两个应用程序中使用相同的代码来绑定服务。 “第一个应用程序”在绑定服务之前启动服务。 “第二个检查服务是否已经启动,而不仅仅是绑定服务。如果没有new Intent(this, Listener.class),我如何绑定它?

标签: android android-service android-service-binding onserviceconnected


【解决方案1】:

我认为您缺少要在 AndroidManifest.xml 中启动的服务的 exported 属性

【讨论】:

  • 不 android:exported="true" 在这种情况下也不会改变任何想法。
  • @Fabian 两个应用程序是否都使用相同的keystore 签名?
  • @Herry 我不这么认为。老实说,我不知道密钥库是什么以及我需要它。两个应用程序都实现了相同的库,并且在这个库中是服务。我也不管它先启动哪个应用程序......总是第一个应用程序进入 onServiceConnected 而第二个没有。
  • @fabian 有时一个Activity可以绑定到Service
【解决方案2】:

这是我解决问题的方法。 哪个 App 先启动并不重要。

应用程序检查服务是否正在运行 (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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    相关资源
    最近更新 更多