我正在使用 AWS TransferManager 将文件下载到 SD 卡。它允许 ProgressListener,但我无法更新视图,因为它位于不同的线程上。我怎样才能做到这一点?
下面的 btn.setText() 方法会产生此警告并且不会更新 UI:
android.view.ViewRootImpl$CalledFromWrongThreadException:只有创建视图层次结构的原始线程才能接触其视图。
public class Download
{
ProgressDialog dialog;
File new_video_file;
Button btn; //the progress meter needs to know what button called this. set via setter method below.
int position;
protected void start(int position, Button btn)
{
this.btn = (Button) btn;
this.position = position;
this.new_video_file = new File(storage_dir, arr_videos.get(position)); //local file to be writtent to
AWSCredentials credentials = new BasicAWSCredentials("xxx", "xxx" );
TransferManager tx = new TransferManager(credentials);
Log.v("s3_bucket", s3_bucket);
Log.v("s3_dir", s3_dir);
Log.v("name", arr_videos.get(position));
final com.amazonaws.services.s3.transfer.Download download = tx.download(s3_bucket, s3_dir + arr_videos.get(position), new_video_file);
download.addProgressListener(new ProgressListener() {
public void progressChanged(ProgressEvent pe) {
Double progress = download.getProgress().getPercentTransfered();
String percent = progress.intValue() + "%";
Log.v("progress", percent);
btn.setText(percent);
if (download.isDone()) {
Log.v("dev", "download complete!!!");
}
}
});
}
}