android remote service running in a separate process and call methods from onserviceconnected()

StackOverflow https://stackoverflow.com/questions/19716307

Frage

I'm writing a service using AIDL to invoke methods remotely. I'm able to connect to the service successfully and also, invoke methods on it. However, if I try to invoke a method in onServiceConnected(), I get null pointer exception. Snippet of the code is below.

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
 Log.v(TAG, "service connected");
 serviceObj = <AIDL Interface>.Stub.asInterface(service)
 if(serviceObj != null) {
   serviceObj.getMyMethod(); // Throws Null Pointer Exception, why???
} 
}

Also, in manifest, I have defined the following property in the service tag:

android:process=":remote"

However, if I invoke serviceObj.getMyMethods() somewhere else, like on clicking a GUI button, I don't get such error and the methods returns successfully. In addition, if I remove the above ":remote" property, I don't get this error with the same code.

I guess this is the problem associated with running the app and service in different processes, but not able to figure out the exact cause. Any ideas?

War es hilfreich?

Lösung

Finally I figured it out. Some internal crash/null pointer exception was happening due to the fact that Context.startService() is an asynchronous call. While onStartCommand() was performing some tasks, a method invoked on serviceObj in parallel was crashing since it needed some initialization to happen first which was taking place in onStartCommand().

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top