我有一些关于Android绑定服务的细节。指南:http://developer.android.com/guide/components/bound-services.html,关于bindService(),说:
The `bindService()` method returns immediately without a value但是这似乎不正确,因为这里方法的签名是
public abstract boolean bindService (Intent service, ServiceConnection conn, int flags)其中返回的布尔值描述如下:
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.所以问题是:为什么文档说方法是returns immediately without a value?此外,在这里中,绑定是以这种方式完成的:
void doBindService() {
bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}我不明白mIsBound = true的含义,因为javadoc说,如果服务边界失败,bindService()也可以返回false。所以应该是:
void doBindService() {
mIsBound = bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
}我说错了吗?
发布于 2014-09-30 18:30:39
文件不正确。当返回的布尔值为false时,这意味着不再进行建立连接的尝试。当返回true时,这意味着系统试图建立连接,这可以成功,也可以失败。
看看这个问题的答案:“在何种情况下,bindservice返回false”。基本上,当绑定服务找不到要绑定到的服务时,它会返回false。
发布于 2016-01-04 23:06:45
好的,我终于学会了android中绑定服务的所有细微之处,这就是ServiceBindHelper类,它可以被看作是“终极真理”(请原谅我的不谦虚)。
https://gist.github.com/attacco/987c55556a2275f62a16
用法示例:
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
复制相似问题