今天终于搞定了批量文件上传,特地分享出来供大家参考。
//创建一个新线程以免阻塞主线程
new Thread() {
@Override
public void run() {
for (int i = 0; i < files.size(); i++) { //这里的 files 是一个 ArrayList<AVFile> 集合
CountDownLatch latch = new CountDownLatch(1); //创建一个CountDownLatch对象用来阻塞这个for循环
UploadLatch upload = new UploadLatch(files.get(i), latch, i + 1, files.size()); //下面有一个UploadLatch类继承自Thread
upload.start();
try {
latch.await(); //阻塞for循环
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//for循环结束后需要做的事情
}
}.start();
//UploadLatch类
public class UploadLatch extends Thread {
private AVFile file;
private CountDownLatch latch;
private int currentnum;
private int totalnum;
//构造函数
//注意AVFile和CountDownLatch一定要传进来
public UploadLatch(AVFile file, CountDownLatch latch, int a, int b) {
this.file = file;
this.latch = latch;
this.currentnum = a;
this.totalnum = b;
}
//执行Thread.start()时回自动调用这个方法
public void run() {
file.saveInBackground(new SaveCallback() {
@Override
public void done(AVException e) {
if (e == null) Log.w("INFO", "SUCCESS");
if (e != null) Log.e("INFO", "FAILURE");
latch.countDown(); //关键部分,因为传进来的latch是从1开始的,这里会变成0,上面的for循环就会继续执行了
}
}, new ProgressCallback() {
@Override
public void done(Integer integer) {
Log.i("INFO", "PROGRES [" + currentnum + "/" + totalnum + "] - " + integer + " %");
}
});
}
}
关键代码都在这里了,大家如果有更好的方法也欢迎拿出来分享!