0

我正在使用 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!!!");
              }
          }
      });

   }

}
4

2 回答 2

0

有几种方法可以做到这一点。

  • 试试 Activity.runOnUiThread(Runnable), View.post(Runnable), View.postDelayed(Runnable, long)
  • 使用 Handler 或 AsyncTask。这是一个使用 AmazonS3Client.putObject 将文件上传到 S3 并将更新发送到对话框的示例。

您可以在此处找到有关线程的更多信息。希望这可以帮助。

于 2013-05-03T00:01:04.867 回答
0

使用Handler在 UI 线程上创建的对象,因此它将接收对该线程handleMessageRunnable.run()在该线程上的调用。

于 2013-04-20T19:24:54.897 回答