-
- Objective
- The necessity of multi-threading in Android development
- Understanding Android Multithreading
- MessageQueue
- Looper
- Handler
- Handlerthread
- Why Android only allows UI updates on the main thread
- Android system specifically rules to allow UI updates in the main thread in order to avoid overly complex threading security issues
- And developers to avoid the above problems need to pay attention to IS
- Summarize
- Thanks
Objective
Android Performance Patterns Season 5 mainly describes the performance issues in the Android multithreaded environment. By introducing a variety of multithreaded tool classes (Asynctask, Handlerthread, Intentservice, ThreadPool) offered by Android, let's familiarize ourselves with the appropriate scenarios for each component to choose the one with the best performance in a given scenario.
This article is for watching videos 1 ~ 3, referring to Hu's Android performance optimization model for the 5th quarter of the summary of the results, thanks to them.
The necessity of multi-threading in Android development
In Android development, many operations need to be performed by the main thread (UI thread), such as:
- System events (such as device state changes)
- Input events
- Service
- Alarm clock
- UI Drawing
- ...
We often need to write code for these situations.
Since there is only one main thread, all tasks are executed serially, and if we include a large number of network requests and I/O in an operation, subsequent user actions will be affected.
The most obvious user perception is the interface drawing, response is timely :
We know that the Android system has a screen refresh rate of one FPS, which is the refresh of every Ms. If in a certain drawing process, our operation can not be completed in the four MS, then it can not catch the drawing bus, only wait for the next round, this phenomenon is called "drop Frame", the user sees is the interface drawing discontinuous, lag .
In order to avoid long-time operations resulting in "drop frames", we take these operations from the main thread to the child threads, so that other operations on the main thread are not affected and the user experience is much smoother.
Understanding Android Multithreading
A thread that has three main states: Start, perform task, end.
When a thread survives, we let it perform a number of tasks, and when the task is completed or the initiative is canceled, the thread retire.
In many cases, we will have many threads surviving at the same time, and we need to add a task queue that keeps threads from getting tasks from the queue while other threads add tasks to it, a typical producer-consumer model:
If we are to implement this model, we need to write three roles: producer Threads, consumer threads, task queues, and ensure that they work together methodically, which can overwhelm a lot of people.
In order to make developers more worry, the Android system for us to achieve the above class, respectively:
- MessageQueue
- Looper
- Handler
MessageQueue
MessageQueue is the task queue, which holds the carrier of different types of tasks (Intent, Runnable, Message).
Looper
Looper is what we call the "consumer," which constantly gets the task from the task queue and executes it.
Handler
Handler is "producer", which sends tasks from other threads to MessageQueue.
Handler can specify the position of the task in the task queue, and can delay delivery at a certain time.
Handlerthread
Handlerthread is a combination of the above three components.
When each app starts, the system creates a process for the app and the main thread, where the main thread is a handlerthread.
This main thread will handle the major events, as follows:
Why Android only allows UI updates on the main thread
On Android, the UI can only be updated by default on the main thread (UI thread), and may not work or even crash when you make UI changes to a child thread:
Why design it like this?
We know that multi-threaded concurrent access to resources to follow the important principle is atomicity, visibility, order . Without a synchronization mechanism, multiple threads reading and writing memory at the same time can cause unexpected problems:
Multithreading is also the same as the UI, if you want to allow multiple threads to update the UI, you need to design the corresponding synchronization mechanism, in order to avoid this problem, the Android system directly allows only UI thread update UI.
In addition to thread safety, there is another reason: the life cycle of the UI component is not deterministic .
There may be a situation where we hold a reference to a button in a thread that executes a network request, but before the request results are returned, the button is removed by the View Hierarchy, and any action on the button is unavailable and meaningless.
There is also a bit of a memory leak caused by a thread reference .
We know that each view holds a reference to the current Context, activity, and if the child thread holds a reference to a View and then holds the corresponding activity reference, then the thread returns, even if the activity is unavailable and cannot be recycled, causing a memory leak 。
In addition to holding View, the line Cheng-hold Activity can also cause a memory leak, as long as the child thread does not end, the referential relationship persists.
For example, create an internal asynctask in the Activity:
Or it is common to create a Handler in the Activity:
As the Android Studio prompts, the internal threading Tool class holds external class references that can cause memory leaks .
In order to avoid overly complex thread safety issues, the Android system specifically allows the UI to be updated only in the main thread. And developers, in order to avoid the above problems, need to pay attention to:
Do not have any child threads holding UI components or Activity references.
Summarize
This article is about the necessity of multi-threading in Android and some basic concepts.
The Android system provides us with the following types of tools:
- Asynctask
- Switch between the main thread and the Sub-threading task
- Handlerthread
- Open a separate thread for a task/callback
- ThreadPool
- Manage multiple threads and execute tasks concurrently
- Intentservice
- Get Intent in a child thread to perform a background Service that is started by the UI
We will then follow the official video to learn more about the features of these tools, so that you can choose the right person for the right scenario and optimize the performance of your application as much as possible.
Thanks for the attention.
Thanks
https://www.youtube.com/watch?v=qk5F6Bxqhr4&index=1&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE&t=39s
http://hukai.me/android-performance-patterns-season-5/
Android Performance Optimizations: Multi-threaded note