我有一个关于套接字对象的问题,我通过Service实例传递到我的Android活动中。
套接字对象总是返回null,我不明白为什么。 我在其他活动中使用相同的方法,它工作正常。有人可以看看吗?
这是我的代码:
**Service class code:**
public class SocketService extends Service {
// Create subclass of IBinder and bind it to local class instance
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
SocketService getService() {
return SocketService.this;
}
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
@Override
public void onCreate() {
try {
socket = new SocketIO(URL);
socket.connect(new IOCallback() {
// Tell if connection was established
@Override
public void onConnect(){
}
// Server Message
@Override
public void on(String event, final IOAcknowledge ack,
Object... arg) {
}
@Override
public void onDisconnect() {
socket.reconnect();
}
@Override
public void onError(SocketIOException arg0) {
Log.e("ERROR", "No Connection to host");
error = true;
}
@Override
public void onMessage(String arg0, IOAcknowledge arg1) {
}
@Override
public void onMessage(JSONObject arg0, IOAcknowledge arg1) {
}
});
} catch (MalformedURLException e) {
Log.e("error", "Wrong Server URL" + e); }
} else {
Log.e("ERROR", "No connection possible");
}
}
@Override
public void onDestroy() {
super.onDestroy();
socket.disconnect();
stopSelf();
}
public SocketIO getSocket(){
return socket;
}
这里是null套接字对象的活动:
Activity code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
socketConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
LocalBinder binder = (LocalBinder) service;
socketService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
socketService = null;
}
};
// Bind to socket service
Intent serviceIntent = new Intent(ContactMenuActivity.this, SocketService.class);
bindService(serviceIntent, socketConnection, Context.BIND_AUTO_CREATE);
socket = socketService.getSocket(); // This code always returns null
but only for this activity, it works with other activities with same approach
答案 0 :(得分:1)
好的,我找到了问题的答案。在任何一种情况下,显然绑定到服务可能需要一些时间,比我的活动启动时间长。
解决方案是在意图连接到服务后立即检查IBinder对象的返回值:
Service Class
@Override
public IBinder onBind(Intent arg0) {
Log.d("DEBUG", "Connected to service");
return mBinder;
}
Activity Class
if (mBinder != null)
socket = socketService.getSocket();