我在android上实现了Socket.io客户端,我已经设法在Unbounded服务中初始化套接字但问题是它在应用程序处于后台并且手机被锁定的5分钟后断开连接。如果应用程序位于前台,则连接仍然无穷无尽。
断线情况:
MySingelton.java
public class MessageService extends Service {
Socket mSocket;
public MessageService() {
mSocket = Singelton.get(this).getSocket();
Log.d("chat", "Constructor"+String.valueOf(mSocket.hashCode()));
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("chat", "onStartCommand"+String.valueOf(mSocket.hashCode()));
initSocket();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
//Log.e(TAG, "onStartCommand");
return START_STICKY;
}
@Override
public void onDestroy() {
Log.d("chat", "onDestroyed");
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(getApplicationContext(), MessageService.class);
PendingIntent pintent = PendingIntent.getService(MessageService.this, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+(1*1000), pintent);
super.onDestroy();
}
@Override
public void onCreate() {
Log.d("chat", "onCreate");
super.onCreate();
}
private void initSocket(){
mSocket.on(Socket.EVENT_CONNECT,onConnect);
mSocket.on(Socket.EVENT_DISCONNECT,onDisconnect);
mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
mSocket.on(Socket.EVENT_RECONNECT, onReconnect);
mSocket.on("pingy", ping);
mSocket.connect();
mSocket.emit("pongy", "Hi");
}
int i=0;
Emitter.Listener ping = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("chat", String.valueOf(i) + " " + mSocket.hashCode());
i++;
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
new CountDownTimer(2000,1000) {
@Override
public void onTick(long millisUntilFinished) {
}
@Override
public void onFinish() {
mSocket.emit("pongy", "Hi");
}
}.start();
}
});
}
};
Emitter.Listener onConnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("chat", "connected");
}
};
Emitter.Listener onReconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("chat", "onReconnect");
}
};
Emitter.Listener onDisconnect = new Emitter.Listener() {
@Override
public void call(Object... args) {
//mSocket.disconnect();
Log.d("chat", "onDisconnect");
stopSelf();
}
};
Emitter.Listener onConnectError = new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.d("chat", args[0].toString());
}
};
}

为MyService
{{1}}
注意:我想让服务一直在后台运行,不应该被系统或应用程序杀死