Reputation: 796
On an application I'm working on the onCreate starts a service with startService() and subsequently after, that same activity calls bindService(to that same service) in its onStart. The problem is the Sevice isn't initialized until well after the onStart has completed which causes a fatal error from a nullpointer exception caused by a null service. I don't know how to get around this without using a half-assed solution and I have no idea how the onStart is finishing before the onCreate.
Suggestions? Any help is much appreciated.
public class PNetworkService extends Service {
private final IBinder binder = new NtwkSvcBinder(this);
@Override
public void onCreate() {
// Creates a HandlerThread to process the network events.
HandlerThread handlerThread = new HandlerThread("SystemStartService",
Process.THREAD_PRIORITY_BACKGROUND);
// Starts the network thread.
handlerThread.start();
// Obtains looper so that that the NetworkServiceHandler is bound to that looper.
serviceLooper = handlerThread.getLooper();
// Create the Network Service Handler.
nsh = new NetworkServiceHandler(serviceLooper, this);
messenger = new Messenger(nsh);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "onStartCommand");
return START_STICKY;
}
@Override
public IBinder onBind(Intent i) {
Log.i(TAG, "onBind called");
return binder;
}
public void setExtHandler(Handler extHandler) {
Log.i(TAG, "setting exthandler");
nsh.setExtHandler(extHandler);
}
}
Upvotes: 0
Views: 235
Reputation: 2554
I think that the main problem is that you assume that the service is already running when Activity's onStart is executing and expect bindService to bind immediately. However, usually it doesn't work.
The reason of such behavior, I think, is that Android instantiates Components one by one, think you cannot synchronously create service inside onCreate of Activity. For sure it will be created, but after the system queue will go to this new service creation.
So will it work if you'll just provide a correct handling of Connection for binding the service? For instance move following code
mConnection.getService().setExtHandler(mapActivityHandler);
to inside of onServiceConnected()
?
Upvotes: 4