The point of Handlers? - android

I am aware this is most likely a very stupid question, but I just cannot completely understand the point of Handlers. I know the idea is that Handlers execute on the main thread, and they seem to be most commonly used along with worker threads, but why cannot the worker thread just invoke methods on the calling Activity instead of said Activity creating the thread along with a Handler to receive messages?
Again, I apologise for the ignorance of my question, but all I've found online is tutorials on how to use Handlers and my Pro Android 3 book does not clear up my question (or I'm too stupid to understand it properly!)
Or, for that matter, why use them over AsyncTasks, which can modify the UI without problem?
Thank you.

When using handler (or message) each task becomes "serialized".
This has the advantage that there is NO concurrency and therefore no need to lock.
It is much easier to make a message driven system stable than an multi-threaded one.
By the way AsyncTask uses Handlers, too
Using handlers directly give you more flexibility.
For example you could schedule a message to be send in the future.
Or you could abort an scheduled message.
Handlers are a very powerful tool.

Related

Android AsyncTask vs Thread + Handler vs rxjava

I know this is the question which was asked many many times. However there is something I never found an answer for. So hopefully someone can shed me some light.
We all know that AsyncTask and Thread are options for executing background tasks to avoid ANR issue. It is recommended that asynctask should only be used for short-running tasks while thread can be used for long-running tasks. The reasons why asynctask shouldn't be used for long tasks are well-known which is about the possible leak caused by asynctask since it may continue running after an activity's destroyed. That is convincing. However, it also leads to some other questions:
Isn't thread also independent from activity lifecycle? Thus, the risk with asynctask can also be applied to thread. So why thread is suitable for long-running tasks?
Looks like the risk of asynctask is only applicable when using it with activity. If we use it in service (not IntentService since IntentService stops after its work's completed), and as long as we can guarantee to cancel the asyntask when the service's stopped, can we use it for long-running tasks? and doesn't it means it's risk free to use asynctask in services?
I've played with rxjava for a while and really like it. It eliminates the need of worrying about threading (except you have to decide in which thread to subscribe and observe the emitted data). From what I can see, rxjava (in conjunction with some other libs like retrofits) seems to be a perfect replacement of asynctask and thread. I'm wondering if we could completely forget about them or there is any specific case that rxjava can't achieve what asynctask and thread can do that I should be aware of?
Thanks
Since no one's replying. I'm answering my own questions then.
The reason why AsyncTask is recommended for only short tasks (around 5 seconds) is there is no method to cancel a running AsyncTask. There exists a method called AsyncTask.cancel(true) which invokes onCancelled(Result result). However, according to the docs, this method "runs on the UI thread after cancel(boolean) is invoked and doInBackground(Object[]) has finished." (https://developer.android.com/reference/android/os/AsyncTask.html). On the other hand, Thread can be stopped with Thread.interrupt().
There shouldn't be any problem running an AsyncTask within a Service provided that you are aware of the cancellation limitation of AsyncTask and the possibility of memory leak can be created by AsyncTask. Note that, there is obviously no need to use an AsyncTask in an IntentService which is already running in a worker thread.
This is a very experience-based question. I guess there would be no complete answer. What we can do is to understand Rx and being aware of the its limitations to determine where suitable to use it. In my development work, I use RxJava all the time without having any issue. Note that the same memory leaking issue is also applied to RxJava. You can perhaps find one of the specific questions here. There are also a whole bunch of discussions about handling leaking/screen rotation with RxJava that can be easily found by Googling.
AsyncTask and Thread+Handler are not carefully designed and implemented. RxJava, Akka and other frameworks for asynchronous execution seem more carefully developed.
Each technology has its limitations. AsyncTask is for a single parallel task with ability to show progress on UI. However, if activity is regenerated (e.g. because of screen rotating), connection to UI is lost (one possible solution for this problem is at https://github.com/rfqu/AsyncConnector).
Thread+Handler keeps memory for thread stack even when there is no messages to process. This limits the possible number of threads. You can have much more Akka actors or RxJava Subscribers than handler threads, with similar functionality.

Understanding when and why to use different Android threads

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)

How should I make multiple http requests in android

Hey I am trying to make multiple http requests and wondering the best way to perform this in android. Currently I am using an IntentService with threads, however this doesnt work too well because onhandleintent returns before the threading is complete. Should I Switch to A regular service and start my own threads in there or would asyncTask be more approiate?
Thanks
Any time you deal with threads you're going to have to deal with synchronization. For example, when onHandleIntent() is called you may need to synchronize with your HTTP request thread(s) and wait for it to complete.
If you know ahead of time you will be doing this a lot it may be worth looking at something like ThreadPoolExecutor to save a bit on the pains of creating and tearing down threads. Again you will still need to synchronize your threads if you want to wait for their termination before moving on. Android has many ways of doing this including abstractions that make it fairly trivial to implement.
If you're already starting new threads anyway (whether directly or indirectly), then yes you should use a Service instead of an IntentService. The whole point of an IntentService is for it to handle threading for you.

AsyncTask or Handler- Which one is better for time consuming network interaction and processing?

I am new to android development. Currently i am working on an application which will take a query from user, send the query to the server and will receive an XML response in return. Then it will process the xML response using XMLparser, will extract the answer from XML response and display answer to the user. Since all this processing takes some time, i want to show a progress dialog to the user for the processing time it takes.
I have gone through some ways of doing this like i can use AsyncTask, Handler or Runnable (java) threads. But as much I have read about all these, I have got confused which one to use.
Please tell me which one is better to use for above mentioned scenario. And a simple way to implement the preferred one.
Thank You in advance.
I'd recommend you to use AsyncTask because it is simplier than other approaches and it suits your needs.
I think you mess a bit these three different entities:
AsyncTask runs a set of actions in a separate thread, can show progress during its work and show notification when the task is completed.
Runnable is a command that can be performed. You should run in a separate thread. Also you should develop a logic in this case how to update progress and how to notify when the task is finished.
Handler is a special class that can handle messages that are sent to the handler's thread.
From http://developer.android.com/reference/android/os/AsyncTask.html :
This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
AsyncTask is designed for a use very similar to yours.
Runnable is only to run a block of code on another thread:
Represents a command that can be executed. Often used to run code in a different Thread.
(http://developer.android.com/reference/java/lang/Runnable.html)
Handler is used more for Message Queuing. Your case doesn't seem to require messages being sent repeatedly.
There are two main uses for a Handler: (1) to schedule messages and runnables to be executed as some point in the future; and (2) to enqueue an action to be performed on a different thread than your own.
http://developer.android.com/reference/android/os/Handler.html
Note that neither Runnable nor Handler talk about displaying the results back on the UI thread. That is where AsyncTask helps you more than either of these.
It may be my personal preference - but I would use AsyncTask in your case. It provides all necessary controls for starting up the task, updating progress as necessary, etc. I have a very similar requirement in my app (send request to server, get response in XML, parse response, do something with the data) - I'm using AsyncTasks for this purpose.
As far I know AsyncTask is the recommended way. I think is the easiest way to implement and the more "Android best practice" for asynchronous tasks.
Could you refer to this question
Here's how I see it.
Handler is more for queuing many actions, and gives a bit more control. It's better for repetitive tasks which are generally not restricted to the UI.
AsyncTask provides a simple way to do background processing, not caring much about the lower-level stuff. It's great for relatively small, individual UI updates.
IMO, you should use AsyncTask. That being said, it's kind of a toss-up.
I think it's a matter of self-preference, but in your case I would go for the AsyncTask because it facilitates the interaction between the UI thread and the background thread.
I'd use a combination of AsyncTask and Handler, because please remember that you cannot change the UI from outside the UI thread (in this case you cannot intervene and show the answer to the user).
To overcome this, I ran the AsyncTask and catched the result with a custom callback method, which simply encapsulate it inside a Message and sends it to my custom Handler, which is inside the UI thread and can safely render on-screen my result.
AsyncTask might be the choice,because it provides all necessary controls for starting up the async task, updating progress bar, etc.
But, the point is AsyncTask is the best solution to the scenario.
Handler or Runnable are more suitable to duplex cases, like chat apps.

Can startServce() be invoked from any thread?

Most Android framework components are not thread safe—at least this is the assumption that I usually work with.
However, is it safe to invoke startService() from a background thread?
I came across a post from Dianne Hackborn who says that it is safe to call sendBroadcast() from any thread, so I want to assume that this is also true for startService() (http://groups.google.com/group/android-developers/msg/38a09b52de93f70a).
Can anyone with framework experience comment?
Thanks!
I don't know the theory but I believe the answer is yes, and it is easy to try. Just be sure that as always, if you are going to update anything on the UI, to put a Handler in your main thread - and then in the Service, send that Handler a Message containing the data to be put on the UI.

Categories

Resources