Reputation: 6972
According to the documentation one of three options should be used for accessing the UI thread from a different thread. These are the options:
When should I use which? They all seem to add a Runnable to the message queue of the UI thread.
I assume postDelayed is only really useful if you want to schedule a Runnable for later and they only mentioned it because it also runs the Runnable on the UI thread.
And for extra confusion there is also AsyncTask. When should I use that now?
Upvotes: 1
Views: 116
Reputation: 786
If you need a mechanism for returning to the UI thread that is available from everywhere without needing a context, you can use this:
Handler handler = new Handler(Looper.getMainLooper());
handler.post(Runnable);
Upvotes: 1
Reputation: 4447
I will recommend you to use AsyncTasks, they were designed to do hard work in other thead (doInBackground()) and then syncronize with UI thead to push work results (onPostExecute()), and of course you can periodically update UI with work progress (onProgressUpdate()).
If you want to run more than one AsyncTask concurrently on Android Version greater than HONEYCOMB, you can use my small lubrary: Android-AsyncTask-Executor
Upvotes: 0
Reputation: 11568
Forget about AsyncTask
, it's not for running code in the UI thread, but running code in a background thread starting the AsyncTask
from the UI thread.
Regarding the other options, feel free choosing any of them. If you are dealing with a View
object, it is likely you are already on the UI thread. Therefore, you better keep a reference to the Activity
context from the other thread and call runOnUiThread.
Upvotes: 0
Reputation: 9276
runOnUiThread and View.post are exactelly the same they both send a runnable object to the activity's Handler . so use whichever you like.
Regarding the AsynchTask it is not used to run on the UI thread. but after an Asynch task finishes working it calls a method called OnPostExcute
on the UI thread.
There is a very great tutorial on this subject Here
Upvotes: 1
Reputation: 618
I always choose runOnUiThread, I think so is the best way to run something on the same UI Thread. AsyncTasks are tricky, it's a good idea but if you want to use something new, use loaders or IntentService.
Upvotes: 0