Search code examples
javaandroidsocketsandroid-asynctask

Reading data from socket using AsyncTask in android studio


Hi i am currently working on a messaging app in android studio for a school project.

I am using sockets to let the client communicate with the server, i am aware that you should not call networking methods in a UI thread so to work around this i am using asynctask i have created asynctask classes to create a socket and then send data over it but i am having trouble with reviving data as i am struggling to find a way to get the data out of asynctask and back to the UI thread.

I have tried using onpostexecute to set a global variable in the class i am using for the socket related methods (and asynctask classes) and then using a getter method to read from it in the UI thread but the UI thread is to fast and reads it before it can be set and i don't want to have to set a timer to make the UI thread wait for this variable to be set as this defeats the point of using asynctask in the first place.

I was hoping that someone here could point me in the right direction of how to do this, is using asynctask just the wrong way tog about it? if so how should i implement sockets in android.

thanks for reading i appreciate your time :)

side note: i am using an datainputstream and .readUTF to receive data through the socket.


Solution

  • The AsyncTask class has two methods of importance for your problem, doInBackground(Params...) and onPostExecute(Result).

    You are using a DataInputStream to retrieve the data from your socket using its readUTF method. The readUTF method returns a String. I am not sure what data you are passing to your socket to initiate the request/response action but whatever that data type is you need to override doInBackground method with it. For example lets say you are passing a string of data to the server using the socket. Your doInBackground method would look something like

    @Override
    protected String doInBackground(String... data) {
        /* set up the socket/DataInputStream, etc. and whatever else you need
           in the background */ 
        DataInputStream in = ...;
        return in.readUTF();
    }
    

    The return type is a String just because that is the data returned by the readUTF method and thus I assume you want a String returned to the UI thread.

    Next you need to override the onPostExecute method as follows

    @Override
    protected void onPostExecute(String result) {
        // do whatever needs to be done on the UI thread with the result
    }
    

    Your subclassed AsyncTasks would be defined as

    class SocketTask extends AsyncTask<String, Void, String> {
    ...
    }