0

I'm actually trying to build a WebSocket client application on Android with the nv-websocket-client. But I'm stuck with interfaces in my doInBackground function.

I'm trying to use a AsyncTask for the WebSocket connetion, but I'm stuck when I have to pass to onPostExecute the message from onTextMessage :/

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);
    }
}

I can use a RunOnUIThread or enable StrictMode but this is not the good method to do that job.

Thank you for your help !

joedu12
  • 33
  • 1
  • 6
  • Instead of trying to send it to the onPostExecute() method, why don't you define another custom method in the AsyncTask class to do whatever you intend on doing. – TeChNo_DeViL Jan 30 '16 at 13:21
  • In my mind public void onTextMessage(WebSocket websocket, String message) is supposed to be executed in the thread related to doInBackground and String message has to be passed to the UI thread in onPostExecute. So how move "socket.addListener" in another method could solve my problem ? – joedu12 Jan 30 '16 at 13:42
  • Do you intend just to get a single message or keep getting messages? – TeChNo_DeViL Jan 30 '16 at 13:46
  • Get every message until the application is launched – joedu12 Jan 30 '16 at 16:25
  • Well I am confused, if your activity is not running, then why at all use an AsyncTask to fetch data? Why don't you use a simple service instead? If your main intention is to receive data, make a service and launch the listener there. And since services run away from the main UI, you won't need an AsyncTask – TeChNo_DeViL Jan 30 '16 at 16:32
  • The goal is to make a Chat between clients across Websocket so the activity is running. Drops, I'll manage it with Handlers and runOnUiThread :) – joedu12 Jan 30 '16 at 20:04

0 Answers0