views:

442

answers:

3

Hi,

I have a particular situation: a service started by a broadcast receiver starts an activity. I want to make it possible for this activity to communicate back to the service. I have chosen to use AIDL to make it possible. Everything seems works good except for bindService() method called in onCreate() of the activity. bindService(), in fact, throws a null pointer exception because onServiceConnected() is never called while onBind() method of the service is. Anyway bindService() returns true. The service is obviously active because it starts the activity. I know that calling an activity from a service could sound strange, but unfortunately this is the only way to have speech recognition in a service.

Thanks in advance

+1  A: 

I can't make up the exact problem out of your description, so I'm going to guess here!

How can bindService() throw a NullPointerException? The only way this could (/should) happen is when you don't supply a Service or a ServiceConnection listener.

bindService() can't throw a NullPointerException because onServiceConnected() isn't called. The call to onServiceConnected() is a product of bindService().

So I guess you are calling a AIDL method, before the Service is actually bond?!

MrSnowflake
yes sorry, I understand the problem could be explained better. NullPointerException is thrown because the remote interface is never filled as remote = IRemoteService.Stub.asInterface(service); in onServiceConnected() is never called. Should bindService trigger the onServiceConnected immediately?
Matroska
`onServiceConnected()` should not be called __immediately__, there will probably be a small delay.
MrSnowflake
You are right! The method is not called immediately. That was my problem.
Matroska
+2  A: 

After hours and hours of trying to figure this out, the issue is that the examples that show the creation of the service, don't include the onBind method or they have the following sample code or it generates this for you:

public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

This causes the onServiceConnected method to fail or never actually get executed. The fix is VERY simple, which is the following:

public IBinder onBind(Intent intent) {
    return mBinder;
}
Brad Brown
A: 

Thank you soooo much for this!

Alistair