Today I managed to speed-up my Android application a lot by using a Runnable handling a piece of code inserting/updating and deleting some database stuff. However I also used RunOnUiThread() and a normal Thread() but I don't have any idea what the differences are between all three. I do know the ASyncTask, but how do you choose what to work with and what are the main differences?
An explanation / link to another site would be very nice.
Kind Regard.
Most of the code you write runs on the UI thread, ie main thread, by default. Some operations about View
s must be executed on the UI thread. And operations which consume lots of resources should be executed off the UI thread.
You can start a new Thread
by calling new Thread(Runnable).start()
, then the task will be executed on a non-UI thread. But it's recommended to use a thread pool like ExecutorService
to do this, because it reuses the threads.
For an AsyncTask
, the code in doInBackground()
runs on a non-UI thread from a static thread pool of AsycTask
, while onPostExecuted()
are executed on the UI thread. So you should do UI operations in onPostExecuted()
.
When using Handler
, where the handleMessage()
code runs is based on the Looper
you pass to the constructor of Handler
. By default, it's Looper.getMainLooper()
, so it runs on the UI thread.