如何在ProgressListener中使用AWS TransferManager更新Android UI?

时间:2013-04-20 19:16:17

标签: android multithreading amazon-web-services

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

   }

}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

有几种方法可以做到。

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

您可以找到有关线程here的更多信息。希望这会有所帮助。