求解:AsyncTask同步更新UI的原理

tiantangniao232 2012-10-05 04:32:57
从网络上下载一个文件,在AsyncTask的doInBackground里实现下载并且把进度通过publishProgress传给UI线程更新UI上的进度条,想问一下AsyncTask如何保证doInBackground里的publishProgress发布的进度和UI线程更新的进度同步的??
因为下载和更新是在两个线程进行的,AsyncTask如何保证更新同步的:
Thread is running 10 ----doInBackground发布进度
handleMessage ----UI更新进度
Thread is running 20 ----依次进行
handleMessage
Thread is running 30
handleMessage
Thread is running 40
handleMessage
Thread is running 50
handleMessage

而不是像下面这样:(异步线程连续发布了好几次进度后,UI线程才开始集中更新,导致进度条跳跃式前进了)
Thread is running 10 ----doInBackground发布进度
Thread is running 20 ----doInBackground发布进度
Thread is running 30 ----doInBackground发布进度
handleMessage
handleMessage
handleMessage
Thread is running 40
Thread is running 50

谢谢
...全文
230 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
fishmen26 2012-10-07
  • 打赏
  • 举报
回复
参见源代码, 如下:

/**
* This method can be invoked from {@link #doInBackground} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate} on the UI thread.
*
* @param values The progress values to update the UI with.
*
* @see #onProgressUpdate
* @see #doInBackground
*/
protected final void publishProgress(Progress... values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new AsyncTaskResult<Progress>(this, values)).sendToTarget();
}

sHandler 最后会调到onProgressUpdate 函数。通知UI 更新进度。

所以:

UI 和 doInBackGround 两个线程是没有同步的。 上面代码只能说明, UI 收到更新通知时,后台线程肯定已经执行过那个update到UI的进度了。
franzhong 2012-10-07
  • 打赏
  • 举报
回复
异步加载要同步吗
KPRF2009 2012-10-06
  • 打赏
  • 举报
回复
多看看异步加载相关的东西就知道了
Utopia 2012-10-06
  • 打赏
  • 举报
回复
publishProgress将会触发onProgressUpdate(Progress...),而onProgressUpdate(Progress...)在UI线程中执行啊
AMinfo 2012-10-05
  • 打赏
  • 举报
回复
描述不够通俗易懂
zhongyuanceshi 2012-10-05
  • 打赏
  • 举报
回复
楼主是要交替进行更新吧。这方面不懂,帮顶一个

80,359

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧