如何在Android(Java)中逐行显示ping结果?

时间:2016-11-28 22:39:12

标签: java android inputstream ping android-networking

简而言之,看看" str"变量如下。它的输出是PING操作的全部结果。

reader = new BufferedReader(new InputStreamReader (process.getInputStream()));
int j;
char[] buffer = new char[240];
StringBuffer output = new StringBuffer();
while ((j = reader.read(buffer)) > 0){
output.append(buffer, 0, j);}
str = output.toString();
Log.d("1:STR VALUE", str);
publishProgress(" "+str+" ");

" str"变量包含操作的整个结果,即3个ping到IP地址。但是,我希望从此Async任务逐行显示ping到Android活动的ping。

此外,如果有人能解释我正在使用的缓冲阵列长度的性能限制(即240 vs 120),那就太好了。

EDIT-1(对评论的回应):

11-28 18:11:17.404 10769-10815/com.example1 D/1:STR VALUE: PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
                                                           64 bytes from 192.168.0.1: icmp_seq=1 ttl=255 time=8.83 ms
11-28 18:11:17.600 10769-10815/com.example1 D/1:STR VALUE: PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
                                                           64 bytes from 192.168.0.1: icmp_seq=1 ttl=255 time=8.83 ms
                                                           64 bytes from 192.168.0.1: icmp_seq=2 ttl=255 time=2.05 ms
11-28 18:11:17.801 10769-10815/com.example1 D/1:STR VALUE: PING 192.168.0.1 (192.168.0.1) 56(84) bytes of data.
                                                           64 bytes from 192.168.0.1: icmp_seq=1 ttl=255 time=8.83 ms
                                                           64 bytes from 192.168.0.1: icmp_seq=2 ttl=255 time=2.05 ms
                                                           64 bytes from 192.168.0.1: icmp_seq=3 ttl=255 time=3.38 ms

                                                           --- 192.168.0.1 ping statistics ---
                                                           3 packets transmitted, 3 received, 0% packet loss, time 403ms
                                                           rtt min/avg/max/mdev = 2.059/4.758/8.835/2.933 ms

请注意,当STR值在while循环内发布时,会重复输出。

1 个答案:

答案 0 :(得分:0)

尝试这段代码后会得到什么输出?

        InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream());
        BufferedReader reader = new BufferedReader(inputStreamReader);
        try {
            String line;
            while ((line = reader.readLine()) != null)
            {
                Log.d("1:STR VALUE", line);
                publishProgress(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

更新:您使用publishProgress(line);代码发布的数据将作为参数发送到您的任务的onProgressUpdate方法。在此处将此文本附加到TextView。