I would like to know, once for all. I've read in many places. When I want do some 'long time operations' I should use a Handler.
But I don't get why? All my 'long-time-operations' I surround with a regular threads, and it works fine.
Why would I use Handler for this?
The only time I had to use Handler was, when I had to schedule some task(postDelayed)
Is there any main idea I miss about handlers(When I should really use it)? Or maybe there isn't really difference?
A Handler lets you communicate back with the UI thread from your background thread. This is because UI operations are forbidden from within background threads. Note that starting at version 1.5, the AsyncTask class makes it much easier to do so.
It can't just be about getting you back to the UI thread since runOnUiThread(Runnable) does that very nicely. I suspect this is more about making it easier for Android to manage threads and other resources that shouldn't live outside of an Activity's context, and that the "Activity has leaked..." exceptions tell you when that's happened.
Related
Can a thread trying to access the same part of memory at the same time as another thread cause textViews on an android to freeze? if so what is the solution?
The solution is in the design of Android. The method calls to change something in the appearance of a TextView must be called within the Android-UI Thread. You get an exception, if you call methods like TextView.setText() from another thread.
The proposed solution for this is to call Activity.runOnUiThread() or similar and pass your changes to the runnable. See the Android guide about multithreading for more information and the different possiblities.
I never read about View' Thread safety concept in android Documentation. But i guess you will get exception because Changing by two Thread at a time is not good user experience. My conclusion is View are Thread safe and always be updated in UI thread.
Hopefully someone can explain this to me or point me to a resource I can read to learn more. I am building an app that uses a ListView and a custom list adapter that I modeled off one of the many tutorials available online such as this one:
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
It worked fine. However, every example of how to do this runs the process of building the list of objects to be displayed and collecting the required data on separate threads.
I want to know why/couldn't you just put everything into onCreate? I can't see a reason why you would need separate threads to make this happen. Is there some general form/standard for when/what must me run on certain threads?
The Android docs on this are very good, as with most things.
The upshot is: the UI should always be responsive. So if you have some operation that will take enough time that the user will notice, you might want to consider not running it in the UI thread. Some common examples are network IO and database accesses. It's something of a case-by-case basis though, so you have to make the call for yourself a bit.
Well, if building the list of objects is not a relatively short process, doing it in onCreate() would be blocking/slowing the main thread. If you use a separate thread, it will allow the android os to load all of the UI elements while you are waiting for the list to be populated. Then when the list of objects is ready, you can instantly populate the already initialized UI, as opposed to waiting to initialize the UI until after the list of objects is built. It ensures that your application will always be responsive for the user.
Because you only have 0.5 sec to execute onCreate — after which the dreaded ADN (application not responding) error message is displayed. So unless your list view is super simple you won't make it it in time. And even if your list view is super simple it is better to learn it the proper way.
BTW: I don't even use threads, I use one or more Services to do all the work. Even more difficult to implement but more robust and responsive as well.
The reason you don't do things in onCreate or on the UI thread is for responsiveness. If your app takes too long to process, the user gets shown an App Not Responding dialog.
my teacher once said: every software can be written in a single (big) for loop.
And if you think: it can be... maybe at NDK level.
Some SDK developers wanted to make the software developers tasks easier and that's, why exists the SDK's and frameworks.
Unless you don't need anything from multitasking you should use single threading.
Sometimes there are time limitations, sometimes UI/background/networking limitations and need to do stuff in diff threads.
If you see source code of Asyntask and Handler, you will see their code purely in Java. (of course, there some exceptions, but that is not an important point).
Why does it mean ? It means no magic in Asyntask or Handler. They just make your job easier as a developer.
For example: If ProgramA calls methodA(), methodA() would run in a different thread with ProgramA.You can easily test by:
Thread t = Thread.currentThread();
int id = t.getId();
And why you should use new thread ? You can google for it. Many many reasons.
So, what is the difference ?
AsyncTask and Handler are written in Java (internally use a Thread), so everything you can do with Handler or AsyncTask, you can achieve using a Thread too.
What Handler and AsyncTask really help you with?
The most obvious reason is communication between caller thread and worker thread. (Caller Thread: A thread which calls the Worker Thread to perform some task.A Caller Thread may not be the UI Thread always). And, of course, you can communicate between two thread by other ways, but there are many disadvantages, for eg: Main thread isn't thread-safe (in most of time), in other words, DANGEROUS.
That is why you should use Handler and AsyncTask. They do most of the work for you, you just need to know what methods to override.
Difference Handler and AsyncTask: Use AsyncTask when Caller thread is a UI Thread. This is what android document says:
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers
I want to emphasize on two points:
1) Easy use of the UI thread (so, use when caller thread is UI Thread).
2) No need to manipulate handlers. (means: You can use Handler instead of AsyncTask, but AsyncTask is an easier option).
There are many things in this post I haven't said yet, for example: what is UI Thread, of why it easier. You must know some method behind each kind and use it, you will completely understand why..
#: when you read Android document, you will see:
Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue
They may seem strange at first.Just understand that, each thread has each message queue. (like a To do List), and thread will take each message and do it until message queue emty. (Ah, maybe like you finish your work and go to bed). So, when Handler communicates, it just gives a message to caller thread and it will wait to process. (sophiscate ? but you just know that, Handler can communicate with caller thread in safe-way)
There are a couple ways of getting data Asynchronously in your app. One is a Handler and another one is an AsyncTask. Now I've used both, and would like to know which one performs better/more efficiently at some tasks.
Thusfar, I've mostly used AsyncTasks in getting Webdata, and Handler's in getting data from Services to Activities.
I would like to know if there is an advantage to using Handler's for Webdata, or using AsyncTasks for refreshing UI from Services. What is the big difference?
Since AsyncTask uses a Handler, your comparison is... odd.
AsyncTask is great for transactional work: stuff that will take more than a few milliseconds and less than a few minutes. For that sort of work, if you have no need for your own thread management, AsyncTask is generally simpler to use.
If you have some particular characteristics that you need for your threading that AsyncTask will not readily handle, or if you need the thread for an indeterminate period of time (e.g., until the user presses a Stop button), use your own thread and something else to get work to the main application thread: a Handler, or post(), or runOnUiThread(). The "indeterminate period of time" recommendation assumes you are using one of the built-in thread pools -- I am never a fan of tying up a thread out of a thread pool that you didn't set up.
Looks like AsyncTask uses its own internal Handler. My testing is the "post" using a Handler is enqueued immediately. When used in onCreate this can be problematic as other actions must be enqueued after onCreate (haven't read through Android Activity etc source on this yet). So, trying to post to later load the layout did not work. Had to use an AsyncTask. Since AsyncTask has its own internal Handler; perhaps, then creating the task might occur in the queue directly after onCreate but the doInBackground and onPostExecute might occur later as they are later in a queue.
So, AsyncTask worked better for this UI need to load an overly large layout file later with setContentView - later meaning after the onCreate so a ProgressDialog could be shown. ProgressDialog doesn't show up until onCreate is done.
Also, see this article for how to choose when to use AsyncTask. Basically says when wanting to update UI. But actually you can do this with runOnUIThread so don't really need handler nor AsyncTask if you already know Java threading. runOnUIThread is like the invoke/invokeLater stuff in Swing.
I am currently developing an android app, there is always unexpected exception popup when I use AsyncTask or Thread. any one tell me what's the difference between them and how to use them ?
"there is always unexpected exception popup when I use AsyncTask or Thread."
It depends on how to use them, and your code inside it. Mostly when you are using Main UI Thread in this (other) thread or asynctask in-properly.
For difference between AsyncTask and Thread you have to search on SO and net. You can find easily it.
Anyway I recommended you to just go through this blog Android Thread Constructs(Part 4): Comparisons
And this SO question Difference between Service, Async Task & Thread?
You really need to read this properly.
http://developer.android.com/guide/topics/fundamentals/processes-and-threads.html
Mostly use AsyncTask - it's a dressed-up Thread that allows you to among other things interact with the GUI at the beginning, at the end and to report progress in a controlled manner. If you're really feeling like using a Thread, use IntentService instead.
its a very good question and must considered before start using one of them please go through this
Difference between Service, Async Task & Thread?
There is a big difference between AsyncTask and Thread, i.e.
Thread can be triggered from any thread, main/UI or background; but AsyncTask must be triggered from main thread.
Also on lower api of android(not sure, may be api level < 11), one instance of AsyncTask can be executed only once.
I'm confused as to when one would choose AsyncTask over a Handler. Say I have some code I want to run every n seconds which will update the UI. Why would I choose one over the other?
IMO, AsyncTask was written to provide a convenient, easy-to-use way to achieve background processing in Android apps, without worrying too much about the low-level details(threads, message loops etc). It provides callback methods that help to schedule tasks and also to easily update the UI whenever required.
However, it is important to note that when using AsyncTask, a developer is submitting to its limitations, which resulted because of the design decisions that the author of the class took. For e.g. I recently found out that there is a limit to the number of jobs that can be scheduled using AsyncTasks.
Handler is more transparent of the two and probably gives you more freedom; so if you want more control on things you would choose Handler otherwise AsynTask will work just fine.
My rule of thumb would be:
If you are doing something isolated related to UI, for example downloading data to present in a list, go ahead and use AsyncTask.
If you are doing multiple repeated tasks, for example downloading multiple images which are to be displayed in ImageViews (like downloading thumbnails) upon download, use a task queue with Handler.
Always try to avoid using AsyncTask when possible mainly for the following reasons:
AsyncTask is not guaranteed to run since there is a ThreadPool base and max size set by the system and if you create too much asynctask they will eventually be destroyed
AsyncTask can be automatically terminated, even when running, depending on the activity lifecycle and you have no control over it
AsyncTask methods running on the UI Thread, like onPostExecute, could be executed when the Activity it is referring to, is not visible anymore, or is possibly in a different layout state, like after an orientation change.
In conclusion you shouldn't use the UIThread-linked methods of AsyncTask, which is its main advantage!!! Moreover you should only do non critical work on doInBackground.
Read this thread for more insights on this problems:
Is AsyncTask really conceptually flawed or am I just missing something?
To conclude try to prefer using IntentServices, HandlerThread or ThreadPoolExecutor instead of AsyncTask when any of the above cited problems ma be a concern for you. Sure it will require more work but your application will be safer.
If you want to do a calculation every x seconds, you should probably schedule a Runnable on a Handler (with postDelayed()) and that Runnable should start in the current UI thread. If you want to start it in another thread, use HandlerThread.
AsyncTask is easier to use for us but no better than handler.
The Handler is associated with the application’s main thread. it handles and schedules messages and runnables sent from background threads to the app main thread.
AsyncTask provides a simple method to handle background threads in order to update the UI without blocking it by time consuming operations.
The answer is that both can be used to update the UI from background threads, the difference would be in your execution scenario. You may consider using handler it you want to post delayed messages or send messages to the MessageQueue in a specific order.
You may consider using AsyncTask if you want to exchange parameters (thus updating UI) between the app main thread and background thread in an easy convinient way.
AsyncTask presumes you will do something on the UI thread, after some background work is finished. Also, you can execute it only once (after this, its status is FINISHED and you'll get an exception trying to execute it once more). Also, the flexibility of using it is not much. Yes, you can use THREAD_POOL_EXECUTOR for a parallel execution, but the effort might be not worthy.
Handler doesn't presume anything, except handling Runnables and Messages. Also, it can be run as many times as you wish. You are free to decide to which thread it must be attached to, how it communicates with other handlers, maybe produce them with HandlerThread. So, it's much more flexible and suitable for some repeated work.
Check different kind of Handler examples here.
They are best interview question which is asked.
AsyncTask - They are used to offload of UI thread and do tasks in background.
Handlers - Android dosent have direct way of communication between UI and background thread. Handlers must be used to send message or runnable through the message queue.
So AsyncTasks are used where tasks are needed to be executed in background and Handlers are used for communication between a UI and Background Thread.
doInBackground - basically does work in another thread.
onPostExecute - posts the results on the UI thread and it is internally sending message to handler of main thread. Main UI thread already has a looper and handler associated with it.
So basically,if you have to do some background task,use AsyncTask. But ultimately,if something needs to be updated on UI,it will be using main thread's handler.