在我的应用程序中,我想与服务建立TCP连接,并将此服务绑定到需要它的每个活动。它在我的登录活动中开始,一切正常。这是代码:
private TCPService mService;
private boolean mBound = false;
@Override
protected void onStart() {
super.onStart();
Intent intent = new Intent(this, TCPService.class);
startService(intent);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
super.onStop();
if (mBound) {
unbindService(mConnection);
mBound = false;
}
}
/** Defines callbacks for service binding, passed to bindService() */
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className, IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
TCPService.LocalBinder binder = (TCPService.LocalBinder)service;
mService = binder.getService();
mBound = true;
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
现在我想在没有startService(intent);
的情况下使用几乎相同的代码将服务绑定到另一个活动中但是mBound永远不会设置为true,我无法像预期的那样访问服务函数。
以下是该服务的实施:
public class TCPService extends Service {
private final IBinder myBinder = new LocalBinder();
public class LocalBinder extends Binder {
public TCPService getService() {
return TCPService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
return myBinder;
}
}
我错过了什么?有什么我应该检查可能会导致这种行为吗?
提前致谢