开发者社区> 问答> 正文

Android在主线程里用handler循环ping命令固定次数会出现ioexception

我做了一个ping百度的程序,使用的是handler循环。下面是循环体:

 private Handler handler = new Handler();
private Runnable task = new Runnable() {
    public void run() {
        // TODO Auto-generated method stub
        handler.postDelayed(this,5000);//设置延迟时间,此处是5秒
        //需要执行的代码,pingHost是ping百度的一个类
        text.append("\n"+pingHost("www.baidu.com")+count++);
        int offset=text.getLineCount()*text.getLineHeight();
        if(offset>text.getHeight()){
            text.scrollTo(0,offset-text.getHeight());
        }
    }
};
其中调用的pingHost是:
    public String pingHost(String str) {
    String resault = "";
    try {
        // TODO: Hardcoded for now, make it UI configurable
        Runtime runtime=Runtime.getRuntime();
        Process p = runtime.exec("ping -c 1 -w 1 " + str);
        int status = p.waitFor();
        if (status == 0) {
            //  mTextView.setText("success") ;
            resault = "success";
           } else {
            resault = "failed";
            //  mTextView.setText("fail");
        }
    } catch (IOException e) {
        resault="IOerror";//  mTextView.setText("Fail: IOException"+"\n");
    } catch (InterruptedException e) {
        resault="INTERRUPTerror";
        //exit(1);
        //  mTextView.setText("Fail: InterruptedException"+"\n");
    }
    finally {
    }

    return resault;
}
在循环调用312次后,会在ping的时候发生ioexception,无论我简化程序体或者是简化输出的字符串,次数都是这个固定的次数,这是由于主线程阻塞吗?还是由于Linux的ping的设定原因?

展开
收起
爵霸 2016-06-14 10:56:45 3545 0
1 条回答
写回答
取消 提交回答
  • 启用线程后台Ping,应该是一个阻塞的线程,而且ping好像是不会自己停止的,这个线程会一直ping下去,主线程不会阻塞,
    ping线程会阻塞,起一个阻塞一个。一直下去,直到系统资源耗尽。
    解决的方法应该是让ping线程延时自杀,或者使用select机制。或者有别的线程来把ping线程关闭。

    2019-07-17 19:36:59
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载