`while`循环在AsyncTask中重试

时间:2013-11-07 09:59:31

标签: android

我有一个AsyncTask,它包含以下doInBackground()方法:

    protected Boolean doInBackground(String... StringUrls) {

       // ...

            while (len != -1) {

                bufOutstream.write(buffer, 0, len);
                len = in.read(buffer);

                if (Recorder.this.isCancelled)  {

                Recorder.this.stopSelf();
                    break;
                }

            }


            bufOutstream.close();

        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());


        }


       return true;
    }

我想做以下事情:

  • while循环完成后(因为len == -1)我想等待1秒然后重试它,那么如果len将更改为len != -1它将再次循环。
  • 此重试应该在完成len == -1重试时停止5次(len != -1时)。

2 个答案:

答案 0 :(得分:0)

protected Boolean doInBackground(String... StringUrls) {

       for (int i = 0; i < 5; i++) {
        try {
            while (len != -1) {
                bufOutstream.write(buffer, 0, len);
                len = in.read(buffer);
                if (Recorder.this.isCancelled)  {
                    Recorder.this.stopSelf();
                    break;
                }
            }
            bufOutstream.close();
        } catch (IOException e) {
            System.err.println("Caught IOException: " + e.getMessage());
        }
        TimeUnit.SECONDS.sleep(1);
       }
       return true;
    }

答案 1 :(得分:0)

所以你想要阅读和写作,但是当你没有什么可读的时候你想要以1秒的间隔重试5次并在5秒钟后放弃(重试)?

boolean retry=true;
while(retry) {
    retry = false;
    while(len != -1) {
        bufOutstream.write(buffer, 0, len);
        len = in.read(buffer);
        if (Recorder.this.isCancelled){
            Recorder.this.stopSelf();
                break;
        }
    }

    for(int i=0; i<5; ++i) {
        synchronized(this) {
            try{ 
                wait(1000);
            } catch (InterruptedException){}
        }

        len = in.read(buffer);
        if(len!=-1) {
            retry = true;
            break;
        }
    }
}