从网络上下载一个文件,在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谢谢
因为下载和更新是在两个线程进行的,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谢谢
* 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的进度了。