我实际上是在尝试使用nv-websocket-client在Android上构建一个WebSocket客户端应用程序。 但是我在doInBackground函数中遇到了interfaces。
我正在尝试使用AsyncTask进行WebSocket连接,但是当我必须从onTextMessage传递onPostExecute消息时我就陷入困境:/
private class Reseau extends AsyncTask<Void, Void, String> {
// This is run in a background thread
@Override
protected String doInBackground(Void... params) {
socket.addListener(new WebSocketAdapter() {
@Override
public void onTextMessage(WebSocket websocket, String message) throws Exception {
// Here I want to return the String message to onPostExecute
// How to do it ? return message do not work because onTextMessage is void
}
});
try { socket = new WebSocketFactory()
.setConnectionTimeout(5000)
.createSocket(adresse[0] + adresse[1])
.connect();
}
catch (IOException e) { e.printStackTrace(); } catch (WebSocketException e) { e.printStackTrace(); }
return "I want to pass message from onTextMessage to onPostExecute";
}
// This runs in UI when background thread finishes
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
zone.append(result);
}
}
我可以使用RunOnUIThread或启用StrictMode,但这不是执行该工作的好方法。
感谢您的帮助!