我有一个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
时)。答案 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;
}
}
}