我正在使用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!!!");
}
}
});
}
}
答案 0 :(得分:0)
使用在UI线程上创建的Handler
对象,因此它将在该线程上接收对handleMessage
或Runnable.run()
的调用。
答案 1 :(得分:0)