绑定服务时保留 mBound 标志是否相关?
Is it relevant to keep a mBound flag when binding a service?
如有关 bound services 的文档中所述,mBound
布尔值用于了解服务是否绑定在 activity 中。以下是文档中给出的代码示例的摘录:
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
}
如果未绑定,为什么要使用额外的成员而不是将 mService
设置为 null
?这对我来说似乎是多余的,并且可能 error-prone.
无需在您的 Activity 中保留额外的标志。
附加标志增加了数据一致性和原子性的风险,例如:
数据一致性: 其他人修改此代码可能会混淆应该使用 mBound
还是 mService != null
,就像你一样'回覆。他们可能会担心这个并添加assert(mBound == mService != null);
检查。
原子性: 在严格的线程安全条件下,onServiceConnected
可能只是在 mBound = true;
之前被阻塞,而在其他线程中,mService
和 mBound
可能在状态上发生冲突。
复杂度:如果其他人编辑的代码只是错误地将mBound
修改为其他状态怎么办?
希望这对您有所帮助。
如有关 bound services 的文档中所述,mBound
布尔值用于了解服务是否绑定在 activity 中。以下是文档中给出的代码示例的摘录:
public class BindingActivity extends Activity {
LocalService mService;
boolean mBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
LocalBinder binder = (LocalBinder) service;
mService = binder.getService();
mBound = true;
}
}
如果未绑定,为什么要使用额外的成员而不是将 mService
设置为 null
?这对我来说似乎是多余的,并且可能 error-prone.
无需在您的 Activity 中保留额外的标志。
附加标志增加了数据一致性和原子性的风险,例如:
数据一致性: 其他人修改此代码可能会混淆应该使用
mBound
还是mService != null
,就像你一样'回覆。他们可能会担心这个并添加assert(mBound == mService != null);
检查。原子性: 在严格的线程安全条件下,
onServiceConnected
可能只是在mBound = true;
之前被阻塞,而在其他线程中,mService
和mBound
可能在状态上发生冲突。复杂度:如果其他人编辑的代码只是错误地将
mBound
修改为其他状态怎么办?
希望这对您有所帮助。