0

我有一个 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它将再次循环。
  • 此重试应进行 5 次(何时len == -1),len != -1此时应停止重试。
4

2 回答 2

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;
    }
于 2013-11-07T10:04:01.850 回答
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;
        }
    }
}
于 2013-11-07T10:36:53.103 回答