简体   繁体   中英

simple android tcp app doesn't update the main thread

I want to build a simple tcp client for Android. The client need to start by sending name and password and then maintain connection with the server till the app get closed (if we lost connection from some reason we need to re- establish connection by sending user and password).

Now i implemented some simple client like this:

public class SendRecvAsynch extends AsyncTask<String, String, TcpClient> {

    final String SERVER_IP = "10.0.0.7"; //server IP address
    final int SERVER_PORT = 1234;

    String modifiedSentence;
    EditText tv = (EditText) findViewById(R.id.editText_main);


    @Override
    protected TcpClient doInBackground(String... message) {
        //we create a TCPClient object
        try {
            // create address
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            try {
                //create a socket to make the connection with the server
                Socket socket = new Socket(serverAddr, SERVER_PORT);


                // create in out stream
                DataOutputStream outToServer = new DataOutputStream(socket.getOutputStream());
                BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                // write to server and get response
                outToServer.writeBytes("hello from client");

                // read from server
                modifiedSentence = inFromServer.readLine();
                if (modifiedSentence == null)
                {
                    modifiedSentence = "didn't get a dame thing from the server";
                }

                // close the socket
                socket.close();

            }catch (IOException e) {
                tv.setText(e.toString());
                e.printStackTrace();
            }


        } catch (UnknownHostException e) {
            tv.setText("got exceptin");
            e.printStackTrace();
        }



        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

        tv.setText(modifiedSentence);

        //response received from server
        Log.d("test", "response " + values[0]);
        //process server response here....

    }

}

I start the client from OnCreate method like this:

new SendRecvAsynch().execute("");

I expected that the app will connect the server, send him "hello from client" , wait and get the server responds and will close the socket connection.

After i get the responds i want the AsyncTask to update an EditText box I have on the main App screen.

The problem is that this AsyncTask don't update the EditText ... I see in the server side that the App got connected and send the server "hello from client" but i don't see from the client side the server responds...

I guess that from some reason the background process can't get access to the main screen that belongs to the main thread, how can i change it? How can i create that simple tcp client that send and receive line from server?

Thank you.

Yes you are right, in android it's forbidden to access to update the UI ( EditText in your case) outside of the main thread.

But for this reason AsyncTask has the onPostExecute() method where you can run code directly from the main thread.

So the only thing that you have to do is override and implement onPostExecute() in your SendRecvAsynch to suit your needs.

You should take a look to the runOnUiThread method .

From Android's Developers website:

public final void runOnUiThread (Runnable action)

Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Even though you can solve your problem using runOnUiThread , I highly recommend switching the new Architecture Components that were introduced not that long ago. Take a look specially to ViewModel and LiveData components. Here is a Guide to app architecture .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM