我有一个For循环,在其中调用一种将图像上传到服务器的方法,我面临的问题是服务器在一定限制下将强制停止打开的套接字,因此我必须一次上传每个图像。 / p>
for (int i = 0; i < paths.size(); i++) {
transferData(paths.get(i), i);
}
和transferData函数我正在使用transfer Utility aws s3函数
TransferUtility transferUtility =
TransferUtility.builder()
.context(this)
.awsConfiguration(AWSMobileClient.getInstance().getConfiguration())
.s3Client(amazonS3Client)
.defaultBucket("name")
.build();
TransferObserver uploadObserver = transferUtility.upload("name", name, new File(path), CannedAccessControlList.PublicRead);
uploadObserver.setTransferListener(new TransferListener() {
@Override
public void onStateChanged(int id, TransferState state) {
Log.d(TAG, "onStateChanged: " + id + ", " + state);
if (TransferState.COMPLETED == state) {
}
}
@Override
public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {
float percentDonef = ((float) bytesCurrent / (float) bytesTotal) * 100;
int percentage = (int) percentDonef;
Log.d(TAG, "onProgressChanged: " + percentage);
}
@Override
public void onError(int id, Exception ex) {
Log.e(TAG, "Error during upload: " + id, ex);
try {
showToast(ex.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
ex.printStackTrace();
}
});
如何等待方法完成执行然后继续循环
答案 0 :(得分:1)
等待循环使用此代码:
CountDownLatch latch=new CountDownLatch(1);
for (int i = 0; i < paths.size(); i++) {
transferData(paths.get(i), i);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
并将其放在您的方法结束处,以完成上传图片或失败
latch.countDown();
当您的方法丰富到latch.countDown();
时,您的循环将继续
请注意,您必须将循环放入除主线程之外的其他线程中