Friday, April 10, 2009

Binding to a service fails for child activities of an ActivityGroup

This is more of a beginner's help to other beginners. I couldn't find much about this on the internet, so I decided to speak up.

If your service connection doesn't open as expected and your LogCat complains in the following way:

Binding with unknown activity: android.os.BinderProxy@43535e18

you're most likely using an extension of ActivityGroup, which is most likely TabActivity.

For binding to MyService you probably use something like this:


Intent intent = new Intent(this, MyService.class);
if (!bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
throw new IllegalStateException("Binding to service failed " + intent);
}


It appears that if the context is a child activity from an ActivityGroup your binding is doomed.
I couldn't find any explanation to that fact at the moment. Maybe it's a bug or maybe it's a feature. The more important is to have a workaround.

The workaround is simple. Redesign it to have binding functionality in the ActivityGroup.

If you can't do so, just use Activity.getParent() method to pass ActivityGroup as the context. Of course in this case the call will fail if you try to use the child activity separately from ActivityGroup.