Android: Thread Runnable and Handler.post issues - (Handler.postXX does not run on time when expected) within the Run method
<p>I have a TCP Socket used as a TCP client which is used to read incoming data from a server <strong>constantly</strong> -- until the client or the server drops the connection. I don't know of any other way but use a <strong>while (true)</strong> loop in a different Runnable thread and in it (in the while loop) check for incoming data. The received data needs to be printed in an <strong>EditText</strong>.</p>

<p>The problem I am having is updating the text from <strong>Handler.post(...)</strong>.</p>

<p>I know that:</p>

<ul>
<li><p>In order to create TCP connections with Android 3.0 and above, I am required to place the TCP code either in a <strong>new Thread(...)</strong> or an <strong>AsyncTask</strong> because Strict mode has been enabled by default and I do not want to disable it.</p></li>
<li><p>I know that in order to update the UI from a new Thread in Android, I need to use Handler.post() if I use a <strong>Thread</strong> or the <strong>onProgressUpdate</strong> via <strong>publichProgress</strong> if I use <strong>AsyncTask</strong> and I know how to use all these but I am experiencing <em>weird</em> frustrating issues with both of them. </p></li>
</ul>

<p>So, all I want to do is:</p>

<ul>
<li>Listen to the server permanently</li>
<li>As soon as the server sends me a message, example: 'w' or 'a' or n', I immidiately display it on the EditText. You can think of it as a telnet session but I need "more" 
precision than telnet as I want to process every single byte, even non-printable ones so I do <strong>not</strong> want to use <strong>readLine</strong> in anyway. I <strong>must</strong> read a byte at a time OR get a buffer of bytes and then process them separately by iterating through the buffer. I went with a byte at a time.</li>
</ul>

<p>Here is the code I have and please <strong>pay attention to my comment above handle.response</strong> to see the problem I am having. I hope you can clear this out. </p>

<p>The code is very briefly coded and I have removed a lot of the error checking sections for this sample.</p>

<p>I have a new class called: ThreadClientInput:</p>

<pre><code>public class ThreadClientInput  implements Runnable {

InputStream inputStream;
MainActivity mainActivity;
Handler handler = new Handler();
int NextByte = 0;

public ThreadClientInput(MainActivity ma)
{
    mainActivity = ma;
}

@Override
public void run() 
{ 
    ////////////////////////////////////////////////////////////////
    // Run the sensitive code that requires us to create this thread
    try {
        mainActivity.tcp_Client = new Socket("192.168.1.90", 23);
    }
    catch (Exception e){Log.e("EXEPTION:", e.getMessage().toString());return;}
    ////////////////////////////////////////////////////////////////


    // Only try to get the inputStream if we have a successful connection
    if (mainActivity.tcp_Client != null) 
    {
        try 
        {
            inputStream = mainActivity.tcp_Client.getInputStream();
        }
        catch (Exception e){Log.e("EXEPTION:", e.getMessage().toString()); return;}
    }


    /////////////////////////////////////////////
    /////////////////////////////////////////////
    // Update the text on the "Connect" button
    handler.post(new Runnable() 
    {
        @Override
        public void run() 
        { mainActivity.btn_Connect.setText("Connected");}
    });
    /////////////////////////////////////////////
    /////////////////////////////////////////////

    try 
    {   

        // I need to constantly read the data until we manually disconnect or
        // the server drops the connection
        while (true) 
        {
            // Get the next byte
            // I do not want to use "readline()" from a BufferedReader etc because I need to know exactly what's coming in
            // I need to process every single byte
            NextByte = inputStream.read();

            if (NextByte &gt; -1)
            {
                Log.e("in (While loop):", Character.toString((char)NextByte));

                *** Here is the problem ****
                // Update the EditText and this is where the problem starts
                // if the server sends "1234", the Log.e() above will display everything correctly: "1234"
                // however the handler.post below will run at the end of the last byte so the
                // the EditText as well as the second Log.e below within the handle.post will display: "1444" or "4444" or "2444"
                // So the handler.post does *not* run immediately even if I try handle.postAtFrontOfQueue()
                // If the server sends "12345678", again, Log.e() above will display everything correctly: "12345678" 
                // however the handler.post below will run at the end of the last byte again
                // and I will get "88888888" (most of the time) or "18888888" 

                //   

                handler.post(new Runnable() 
                {
                    @Override
                    public void run() 
                    {
                        mainActivity.et_Response.setText(mainActivity.et_Response.getText() + Character.toString((char)NextByte));
                        Log.e("In handler.post:", Character.toString((char)NextByte));
                    }
                });
            }
        }           
    }
    catch (Exception e){Log.e("EXEPTION:", e.getMessage().toString());}
}}
</code></pre>

<p>I tried various variations including one with <strong>runOnUiThread</strong> and AsyncTask, with all I am getting same results. I am out, I have nothing. At this point of time I am just reading some documentation about Handle.post method to see if I can make sense.</p>

<p>I hope you have a solution and I know that "<strong>while (true)</strong>" isn't a good practice but I can break the loop from outside the thread with setting a flag and I don't know of any other way how to do this.</p>
