Android Read Terminal Line by Line
<p>I'm trying to make a ping component for a network tools app I'm working on. It's just an interface to the linux ping command line tool. I started from Jim Huang's answer <a href="http://stackoverflow.com/questions/3905358/how-to-ping-external-ip-from-java-android">here</a>. Next I attempted to modify it to use ping -c 10 so I could see some average latency and packet loss. I noticed that when I did that, rather than output each ping response as it came, it waited for them all before displaying anything. I looked at the code some more and noticed that it was indeed waiting for each line to be appended to a variable and then returning the results. So I replaced the code that appended to the variable with code that appended to a TextView. I'm not sure why this hasn't fixed things. Perhaps something to do with the UI thread being accessed improperly? Have a look at my code. Any help is greatly appreciated.</p>

<pre><code>public void ping(String thingToPing, TextView pingResultView, ScrollView pingScrollView) {
    Process p;
    try {
        p = Runtime.getRuntime().exec("ping -c 10 " +thingToPing);      
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String s;
        while ((s = stdInput.readLine()) != null) {
            pingResultView.append(s+"\n");
            pingScrollView.fullScroll(View.FOCUS_DOWN);
        }
        pingResultView.append("\n\n");  
        p.destroy();
    } catch (Exception e) {
        Log.e("ping", e.getMessage());
        pingResultView.append("Error doing ping. Please try again later.\n");
    }
}
</code></pre>
