for循环中的Android MainActivity线程

时间:2014-07-31 18:40:33

标签: java android multithreading handler

我刚刚在1天前开始使用android dev。在下面的代码中,我只想让For循环在每次迭代后休眠5秒。但是,它只运行并打印一次。 我不确定我做错了什么。 Log cat:07-31 17:49:58.656:I / System.out(511):

07-31 17:49:58.665:I / System.out(511):START

07-31 17:49:58.676:I / System.out(511):NAMECHECK:NOTAVALIBLE

07-31 17:49:58.676:I / System.out(511):建议:

07-31 17:49:58.676:I / System.out(511):END

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    TextView tv = new TextView(this);
    int count;

    try {
        String contents = "";
        u = new URL("http://rscript.org/lookup.php?type=namecheck&name=itachi");
        final HttpURLConnection con = (HttpURLConnection) u.openConnection();
        br = new BufferedReader(new InputStreamReader(con.getInputStream()));

        for (count = 0; count < 5; count++) {
            while ((contents = br.readLine()) != null) {
                System.out.println(contents);
                if (contents.contains(" AVALIBLE")) {
                    tv.setText("Available, sent mail " + count);
                    break;
                }
                tv.setText("Not Available " + count);
            }

            final Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
              @Override
              public void run() {
                  try {
                    u = new URL("http://rscript.org/lookup.php?type=namecheck&name=itachi");
                    br = new BufferedReader(new InputStreamReader(con.getInputStream()));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }   
              }
            }, 5000);


        }


        setContentView(tv);
        con.disconnect();
        br.close();
    }
    catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }


}

0 个答案:

没有答案