检查您是否已绑定(bind)到 Android 中的服务的常见方法是在绑定(bind)步骤中保留 bool 参数,例如 mBound
,如 Android 开发人员指南中所述。我注意到这个 Android 引用教程中的一个问题,我认为这种方法在某种程度上是一种不好的做法。这是来自 Bound Services 的代码:
这是一个带有语言代码作为提示的代码块:
public class ActivityMessenger extends Activity {
Messenger mService = null;
boolean mBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
mService = new Messenger(service);
mBound = true;
}
public void onServiceDisconnected(ComponentName className) {
mService = null;
mBound = false;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
protected void onStart() {
super.onStart();
// Bind to the service
bindService(new Intent(this, MessengerService.class), mConnection,
Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
}
好的,问题来了。我们假设由于任何原因 OnStop()
在 OnStart()
之后立即调用。您可以通过在 OnCreate()
中放置一个断点来创建这种情况,然后等待手机屏幕变黑,强制重新启动应用程序,然后继续运行应用程序。
如果发生这种情况,当您运行 OnStop()
时,mBount
变量仍将为 false
,因为服务连接的 onServiceConnected ()
尚未被调用。因此,您不会调用 unbindService()
,并且您将拥有一个已绑定(bind)且从未解除绑定(bind)的服务。
对于更好的绑定(bind)服务方法有什么建议吗?我想知道在任何情况下调用 unbideService()
是否足够(例如,即使现在未绑定(bind)服务也调用)。
最诚挚的问候
最佳答案
我还没有在实践中尝试过这一点,但在调用 bindService
时设置 mBound = true
似乎是合理的,而不是在打回来。实际上,documentation表示即使 bindService
返回 false
,您也应该调用 unbindService
(这意味着您永远不会收到任何 onServiceConnected
调用,并且mBound
永远不会是真的):
Note: If the method returns false, your client does not have a valid connection to the service. However, your client should still call unbindService(); otherwise, your client will keep the service from shutting down when it is idle.
考虑到这一点,很明显仅在 onServiceConnected
中设置 mBound = true
是不够的(或者至少是推荐的)。我怀疑在先前未绑定(bind)的情况下调用 unbindService 是无操作,但这可能需要一些确认。如果是这样,在调用 bindService
时设置 mBound = true
似乎是一个好方法。
关于android - 绑定(bind)Android服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49035779/