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; } } }
这是我从goolge的样本中获取的一个简单片段:)
代码工作正常,mDataService保存对ServiceB实例的引用,但有一件事我无法理解:在调用onStart之后调用onServiceConnected回调.正如我在android的文档中所看到的那样,the callback is running on the main thread – 但是我可以指望它在我的情况下总是按照这个顺序发生吗? onCreate – > onStart – > onServiceConnected?
解决方法
A client can bind to the service by calling bindService(). When it does,it must provide an implementation of ServiceConnection,which monitors the connection with the service. The bindService() method returns immediately without a value,but when the Android system creates the connection between the client and service,it calls onServiceConnected() on the ServiceConnection,to deliver the IBinder that the client can use to communicate with the service.
一旦正确建立了与服务的连接,就会在未来的某个时刻(在调用Context.bindService()之后不立即)在UI线程上调用ServiceConnection.onServiceConnected().