Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between thread/runnable, handler, runonuithread, asynctask

i started learning android programming and am working on a small game. i heard that doing background operations or updates or downloading or what ever background and time consuming thing should not be done with ui thread and instead use thread/runnable or asynctask. but i cant do some things in threads like background connectivity to database where as this connectivity works with the remaining handler,runonuithread,asynctask.am greatly confused where to use which one. I have some questions 1.handler,runonuithread are both runs on ui thread, thread/runnable is a different thread and in async task, doinbackground method run on different thread and others methods like onprogressupdate,onpreexecute and onpostexecute run on ui thread. right? if that so i wrote a program to do database connectivity with thread/runnable it didnt worked but when i wrote it in doinbackground it worked. my confusin is that as both those methods run on different thread why this is happening. 2.what is the main difference btw those 4 and where are they applicable and not applicable. And also want to know what are the tasks which only ui thread can do. thanks in adv:)

like image 354
jayachandra chillipuri Avatar asked Mar 17 '23 21:03

jayachandra chillipuri


1 Answers

A Handler allows you to post messages to be executed on the main UI thread. Activity#runOnUiThread(Runnable) is a convenience method that uses a Handler internally to post a Runnable on the UI thread (see the source code). Handlers are often used to synchronize events generated on background threads with the main UI thread. For example, since Views and other UI widgets can't be modified directly on a background thread, the background thread might instead post a message that makes those modifications on the main UI thread instead of in the background.

An AsyncTask is a utility class that uses a thread pool to execute tasks and provides helpful callback methods (i.e. onPreExecute, onPostExecute, etc.) that are guaranteed to be executed on the main UI thread (in other words, it abstracts the idea of Handlers from the developer).

like image 79
Alex Lockwood Avatar answered Mar 20 '23 20:03

Alex Lockwood