Search code examples
androidserviceandroid-8.0-oreoandroid-11

Unable to bind to service after moving to Android 11


I have two applications. One that is a foreground service that does not use any of the permissions introduced in Android 11 (camera, location etc). I have client apps that connect to my service. In android 8 this connection works, however when in the Android 11 environment calls to context.BindService() always return false.

Here is the service manifest:

<service
            android:name="com.mypackage.myService"
            android:enabled="true"
            android:exported="true"
            tools:ignore="ExportedService">
        </service>

Here is my connection function used in the client:

fun connect(context: Context): Boolean {
    Intent().also {
        it.component = ComponentName(
            context.getString(R.string.middleware_package),
            context.getString(R.string.middleware_service)
        )
        val bound = context.bindService(it, connection, Context.BIND_AUTO_CREATE)

        if (!bound) {
            Log.e(LOG_TAG, "Unable to connect to service. Is the service installed?")
        }
        return bound
    }
}

In the android docs for bindService() it states it will return false "if the system couldn't find the service or if your client doesn't have permission to bind to it." Since my service does not use any of the new android 11 permissions I'm assuming it now is not finding the service properly? How can this be?


Solution

  • You will need to add a <queries> element to the manifest of your client app, identifying the service app.

    In this sample app with an application ID of com.commonsware.android.r.embed.server, I have a bound service.

    In this sample client app, I added these lines to the manifest to allow the client app to bind to the service app:

      <queries>
        <package android:name="com.commonsware.android.r.embed.server" />
      </queries>