I have some boubts about Android bound service. The guide: http://developer.android.com/guide/components/bound-services.html
,about bindService()
, says:
The `bindService()` method returns immediately without a value
But this does not seems to be correct, since here the signature of the method is
public abstract boolean bindService (Intent service, ServiceConnection conn, int flags)
where the returned boolean value is described as below:
If you have successfully bound to the service, true is returned; false is returned if the connection is not made so you will not receive the service object.
So the question is: why the documentation says that the method returns immediately without a value
? Moreover, here, the bind is done in this way:
void doBindService() {
bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
and I don't understand the sense of mIsBound = true
, since the javadoc says that bindService() can also return false, if the bounding to service fail. So it should be:
void doBindService() {
mIsBound = bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
}
Am I wrong?
The documentation is incorrect. When returned boolean is false this means that no further attempts to establish connection are made. When true is returned this means that system tries to establish a connection and this can succeed or fail.
Look at answer for this question: "in what case does bindservice return false". Basically bindservice returns false when it does not find a service to even attempt to bind to.
Ok, i finally completed learning all the nuances of binding services in android, and that is the ServiceBindHelper class, that can be treated as "ultimate truth" (excuse my immodesty).
https://gist.github.com/attacco/987c55556a2275f62a16
Usage example:
class MyActivity extends Activity {
private ServiceBindHelper<MyService> myServiceHelper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myServiceHelper = new ServiceBindHelper<MyService>(this) {
@Override
protected Intent createBindIntent() {
return new Intent(MyActivity.this, MyService.class);
}
@Override
protected MyService onServiceConnected(ComponentName name, IBinder service) {
// assume, that MyService is just a simple local service
return (MyService) service;
}
};
myServiceHelper.bind();
}
protected void onDestroy() {
super.onDestroy();
myServiceHelper.unbind();
}
protected void onStart() {
super.onStart();
if (myServiceHelper.getService() != null) {
myServiceHelper.getService().doSmth();
}
}
}
来源:https://stackoverflow.com/questions/26127129/doubts-about-bindservice