我在我的应用程序中使用 websocket 来检查新消息。Websocket 在我的 Service 类中实现,当我想停止服务(在 Activity 中使用 stopService)它应该调用断开 websocket,但方法onClose
不调用
这是一些代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
start();
super.onStartCommand(intent, flags, startId);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
Log.i("tag", "onDestroy service start");
Intent intent = new Intent(this, RepeatingAlarmService.class);
if (alarmManager != null) {
alarmManager.cancel(PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0));
}
mConnection.disconnect(); // this line doesn't work ???
super.onDestroy();
Log.i("tag", "service stopped");
}
private void start() {
final String uri = "ws://ws.blabla.com"
try {
mConnection.connect(uri, new WebSocketConnectionHandler(){
@Override
public void onOpen() {
Log.i("tag", "Socket open"); // this line work well
super.onOpen();
}
@Override
public void onClose(int code, String reason) {
Log.i("tag", "Socket closed " + String.format("code: %d, reason: %s", code, reason)); // this line doesn't been printed
}
super.onClose(code, reason);
}
@Override
public void onTextMessage(String payload) {
Log.i("tag", payload); // this line work well
super.onTextMessage(payload);
}
});
} catch(Exception ex) {
}
}