简体   繁体   中英

Use ASyncTask onProgressUpdate to update UI

I have an ASyncTask that tries to

  1. find an image on disk
  2. checks if newer online

Then in onPostExecute update the image

I would like to update image (ie sync to ui thread) both after checking disk (which is fast, but still to slow to do in eg ListView getView ) and after checking online.

If I read the help correctly, I can call onProgressUpdate (executed in UI thread) by using publishProgress(Progress...) ... However, can I be sure of the order? I don't care about timing (if I have to wait a little) but I would like to make sure "disk-progress-state" happens before "online-progress-state"

It's entirely up to you to decide when you call publishProgress() and what parameters you pass to it.

If you want to call it twice from your background thread - once after the disk check, and once after network check - then that's fine. To distinguish between the two calls in your onProgressUpdate() just keep track of what state you're in or keep a count of how many times that function has already been called.

The calls on the UI thread will be in the same order as the calls you make to publishProgress() in the background thread.

If I understood you correctly you are asking if executing publishProgress invokes onProgressUpdate in the same sequence. The answer is yes, because it is posting messages via handler to the UI thread.

Here is the code from AsyncTask publishProgress

sHandler.obtainMessage(MESSAGE_POST_PROGRESS, new AsyncTaskResult<Progress>(this, values)).sendToTarget();

AsyncTask runs the methods on the UI Thread by sending Runnable s to the main thread Handler . This Handler takes every Runnable in the FIFO queue and run them after another sequentially with no parallelism. Thus if the disk-progress-state happens before online-progress-state, then the order of the publishProgress 's is preserved. The same applies to the order of publishProgress and onPostExecute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM