【问题标题】:How can a background thread modify the UI in between Activity loads in Android?后台线程如何在 Android 的 Activity 加载之间修改 UI?
【发布时间】:2013-08-08 02:55:04
【问题描述】:

我有一个在后台运行的下载过程,并使用进度更新 UI(ListView 适配器)。在我离开活动并回来之前它工作正常。再次加载活动后,会出现一个“新”ListView 对象,该对象与绑定到 BG 下载过程的对象不同。如何构造我的代码,以便后台进程始终可以与我的活动中的 ListView 对话?

执行此操作的具体行是:

adapter.notifyDataSetChanged();

这是下载类的外壳:

public class Download
{
   }
   protected void start() 
   {

      TransferManager tx           = new TransferManager(credentials);
      this.download                = tx.download(s3_bucket, s3_dir + arr_videos.get(position), new_video_file);


      download.addProgressListener(new ProgressListener() 
      {
        public void progressChanged(final ProgressEvent pe) 
        {
          handler.post( new Runnable() 
          {
            @Override
            public void run() 
            {
              if ( pe.getEventCode() == ProgressEvent.COMPLETED_EVENT_CODE )
              {
                Download.this.onComplete();
              }
              else
              {
                Download.this.onProgressUpdate();
              }
            }
          });
        }
      });
   }

   protected void onProgressUpdate()
   {
      this.download_status         = "downloading";
      Double progress = this.download.getProgress().getPercentTransfered();
      Integer percent  = progress.intValue();
      //Log.v("runnable", percent + "");

      downloaded_data.edit().putInt(position+"", percent).commit();


      adapter.notifyDataSetChanged();
   }
}

【问题讨论】:

标签: android multithreading listview background


【解决方案1】:

简短的回答是“不”。没有简单的方法可以在已销毁/重新创建的 Activity 中查找/保留对 ListView 的引用。

解决此问题的一种方法是使用BroadcastReceiver。您可以广播进度意图,并让 Activity 在 onCreate() 和 onPause() 中从这些意图中注册/注销。

您可以做的另一个(可以说是更简单的)技巧是保持状态(按照您使用下载的数据.edit()所做的事情),并在您的活动中设置一个线程,定期轮询此状态并更新相应的 ListView。

【讨论】:

    【解决方案2】:

    您可以将listview的数据保存在文件中,然后在函数onCreate回调中获取。使用 File 可能是一个解决方案。一旦你的 Activity 被销毁,所有数据都会丢失

    【讨论】:

      【解决方案3】:

      使任务可分离,就像放置在组件中的 Executor 服务一样,在 Activity 更改之间始终存在:

      1. 使用服务:客户端可以连接到它并请求正在运行的任务等。
      2. 实现 Application 类并让它保存对正在运行的任务的引用,通过静态字段公开。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多