Performing asynchronous tasks from the user interface thread and then changing the user interface is a common problem in Android development, so I decided to spend some time researching and playing with various methods and finding what works best for me.
I considered important factors:
- Should work reliably
- code readability
Activity or Fragment should be cleared of the maximum possible flow control.
Here is a summary of my impressions (which may be wrong, and some may be just opinions) about the various methods:
Asynctask
I used simple AsyncTask without LoaderManager when I first switched to Android:
- If there were recurring issues, I wrote my own
AsyncTaskManager to manage them with an activity life cycle. - Before that, there were some restrictions on the number of tasks and memory leaks.
- The biggest problem was that they made my code extremely confusing and simplified the code, breaking the purpose of using them in the first place.
AsyncTaskLoader with LoaderManager
This seems to be the recommended method, so I studied it a bit:
- After reading a little about it, it seems that the main reason this method is recommended is that it manages tasks with the
Fragment life cycle, and from my understanding it basically just reloads the tasks if necessary. It seems that he cannot get the results of the task launch before the action was restarted after the activity was restarted. - All task parameters seem to have to be
Parcelable or Serialiazable in order to go into the Bundle object.
Handler, Message Streams
This is the method I settled on:
- Easy to use, extremely customizable.
- You get access to the thread that performs the task: set the priority, set the name of the thread for debugging, set the daemon, etc.
- It seems much more responsive than using AsyncTasks based on eye testing, when I click the button many times and watch the results and threads blink;) I could compare this.
- To cope with life-cycle problems, you can write a singleton class that manages messages (saved while the process is alive). Saves them when this job handler is not configured, and then forwards them to the activity handler if it requests missed messages. The task value does not need to be restarted with the same parameters, which can be crucial for tasks that are not idempotent.
So, I came to the conclusion that using Handler , Threads and Messages is a much better solution, but I am convinced that I missed something, because almost everywhere I looked at the recommendation to use AsyncTaskLoader . What am I missing?
Thanks for the input.
android multithreading android-asynctask android-ui android-handler
Emil davtyan
source share