When will it be called onServiceConnected for limited service?

I am trying to associate a service with another service, for example:

public class ServiceA extends Service { private ServiceB mDataService; private boolean mIsBound; @Override public void onCreate(){ super.onCreate(); doBindService(); /* ... */ } @Override public void onStart(final Intent intent, final int startId){ /*...*/ } private ServiceConnection mConnection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { mDataService = ((ServiceB.LocalBinder)service).getService(); } public void onServiceDisconnected(ComponentName className) { mDataService = null; } }; void doBindService() { bindService(new Intent(ServiceA.this, ServiceB.class), mConnection, Context.BIND_AUTO_CREATE); mIsBound = true; } void doUnbindService() { if (mIsBound) { unbindService(mConnection); mIsBound = false; } } } 

This is a simple snippet I took from goolge selections :) The code works very well and the mDataService contains a reference to the ServiceB instance, but there is one thing that I could not understand: the onServiceConnected is called after the onStart call. As I saw in the android docs, the callback works in the main thread - but can I expect it to ALWAYS happen in this order in my case? onCreate → onStart → onServiceConnected?

+7
source share
2 answers

If the official development guide is (still) unclear, Context.bindService () is indeed an asynchronous call . This also explains why ServiceConnection.onServiceConnected() implemented as a callback.

Check out the developer guide:

The client contacts the service by calling bindService() . When this happens, it should provide a ServiceConnection implementation that controls the connection to the service.

The return value of bindService() indicates whether the requested service exists and whether the client is allowed access to it.

When the Android system creates a connection between the client and the service, it calls onServiceConnected() in the ServiceConnection . The onServiceConnected() method includes an IBinder argument, which the client then uses to communicate with the associated service.

ServiceConnection.onServiceConnected() is called in the user interface thread at some point in the future (not immediately after calling Context.bindService ()) as soon as the connection to the service is established correctly.

+12
source

I would not rely on it. It depends on whether the services ServiceA and ServiceB are running in the same or in different processes. This probably also depends if ServiceB is already running. You must write your code so that you are not dependent on this sequence of events.

+2
source

All Articles