Search code examples
androidandroid-serviceandroid-service-bindingonserviceconnected

onServiceConnected() not called in second App


I have two apps which should bind to a Service. App 1 starts the service, if it is not already started.

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

Then it binds the service.

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

After that onServiceConnected will be called and the Activity will be finished and the service will be unbind. The service is still running("0" in bindService).

Until here everything is fine.

The code of the second App lookes exactly the same. But it does not start the service, because it already runs. The bindService returns true. So everything looks good. But the onServiceConnected never get called.

I found this: onServiceConnected() not called Looks like my Problem, but the activities are in the same App... I tried getApplicationContext.bindService but in the first App it throws an exception and does not bind my service, in the second it doesn't change anything. I guess I need more something like getSystemContext because the Activities are not in the same App.

In my ManifestFiles i put the following:

<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>

I hope someone can help me with this.

Best regards

Fabian


Solution

  • Here is how I resolved the Problem. And it doesn't matter which App starts first.

    The App checks if the service is running (https://stackoverflow.com/a/5921190/8094536) If it's not running I start the service. For that I set the componentName and start the Service:

    Intent intent = new Intent();
    ComponentName component= new ComponentName("com.example.firstApp", "com.example.tools.Listener");
    intent.setComponent(component);
    startService(intent);
    

    And than I bind it:

    this.bindService(intent, mConnection, 0)
    

    If the service is already running I set the componentName and directly bind it:

    Intent intent = new Intent();
    ComponentName component= new ComponentName("com.example.secondApp", "com.example.tools.Listener");
    intent.setComponent(component);
    this.bindService(intent, mConnection, 0)
    

    My AndoridManifest.xml looks like this:

        <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>
    

    Attention: Do not use android.permission.BIND_ACCESSIBILITY_SERVICE if you don't use a System App.

    Now both Apps are binded and onServiceConnected get called.

    Thanks to @pskink