-1

我在我的应用程序中使用 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) {

    }
}
4

1 回答 1

2

答案是:只使用最新版本的外部库。

在 gradle 构建文件中,我使用 maven 存储库“jitpack.io”

repositories {
        maven {
            url "https://jitpack.io"
        }
    }

compile 'com.github.tavendo:AutobahnAndroid:v0.5.2'dependenciessection 中写下这一行是为了告诉 gradle 他应该从 jitpack 存储库下载dependendy。

Github 上的最新版本是 0.5.2,但如果你从 github(而不是 jitpack.io)下载它,你会看到不同之处。

于 2015-06-11T10:05:13.797 回答