【发布时间】:2016-01-05 07:06:45
【问题描述】:
我对 Android 绑定服务有一些疑问。导游:http://developer.android.com/guide/components/bound-services.html
,关于bindService(),说:
The `bindService()` method returns immediately without a value
但这似乎不正确,因为here方法的签名是
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?而且here,绑定是这样完成的:
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);
}
我错了吗?
【问题讨论】:
-
返回值没有什么意义恕我直言,例如,如果您的服务尚未运行并且您使用 flags == 0 绑定到它,则返回值为 true,为什么?我不知道...
-
是的,这是矛盾的,因为我们只能在调用 onServiceConnect() 时知道连接是否创建,而不是立即。
-
更糟糕的是:您的 bindService() 返回 true 但从未调用 onServiceConnected() (未启动/创建服务且标志 == 0 的情况),我认为您可以简单地忘记返回重视并仅依赖 ServiceConnection
-
对。事实上,我的想法是在 onServiceConnected() 中设置一个 mIsBound,让它默认为 false,所以如果从不调用 onServiceConnected(),则变量保持为 false。
-
关于忽略返回的布尔值,我同意@pskink。我几乎觉得他们意外地将布尔返回留在了那里,并且打算遵循文档中提到的 void 约定。正如 pskink 提到的,布尔值充其量可能会产生误导
标签: android android-activity android-service android-service-binding