Android is a single-threaded model, which means that android UI operations are not thread-safe and must be executed in the UI thread. Therefore, you simply create a new thread and start () this is against the android single-threaded model. So how can we make good use of multithreading? Summary:
Event Processing Principle: all operations that may take time are processed by other threads.
The main thread event processing in Android cannot be too time-consuming. Otherwise, the subsequent events cannot receive a response within five seconds. the ANR dialog box is displayed. Which methods will be executed in the main thread?
1) activity lifecycle methods, such as oncreate (), onstart (), onresume (), etc.
2) event handling methods, such as onclick () and onitemclick ()
Generally, the method starting with on in the android base class is called back in the main thread.
To improve application responsiveness, you can start from these two aspects.
Generally, the execution time of the oncreate (), onstart (), and onresume () Methods of the activity determines the time when your application homepage is opened, try to put unnecessary operations in other threads for processing. If it is still time-consuming, you can use splashscreen. It is best to use dynamic to use splashscreen, so that the user knows that your application is not dead.
When a user interacts with your application, the execution speed of the event processing method determines whether the application's responsiveness is good, which is generally divided into synchronous and asynchronous scenarios:
1) synchronization. Wait for the returned results. For example, if a user clicks the register button and needs to wait for the server to return the result, a progress bar is required to prompt the user that your program is running and does not die. Generally, a progress bar is required for interaction with the server. For example, if the browser comes with the system, a progress bar is displayed during URL jump.
2) asynchronous. You do not need to wait for the returned results. For example, if you click the "add to Favorites" button in Weibo, you can just tell me if it is successfully executed. I don't want to wait for it. It is best to implement it asynchronously.
Regardless of synchronous and asynchronous processing, event processing may be time-consuming. Therefore, you need to put it in other threads for processing. After the processing is complete, the interface will be notified to refresh.
Note that not all interface refreshing behaviors need to be processed by the main thread. For example, the settext () method of textview must be in the main thread; otherwise, calledfromwrongthreadexception will be thrown, the setprogress () method of progressbar does not need to be processed in the main thread.
Of course, you can also put all the UI component-related behaviors in the main thread for processing, no problem. It can reduce the burden on your thinking, but you 'd better understand the differences between them and the experts who grasp the nuances between things. Put the event processing code in other threads for processing. If the processing result needs to be refreshed on the interface, the inter-thread communication method is required to send messages to the main thread for processing in other threads.
3. How to Implement inter-thread Communication
There are multiple methods in Android to achieve communication between other threads and the main thread. Here we will introduce two common methods.
1) Use asynctask
Asynctask is a helper class for asynchronous processing provided by the android framework. It can perform time-consuming operations in other threads, and the processing results are executed in the main thread. for developers, it shields the concept of multithreading and handler to be discussed later. You don't know how to deal with inter-thread communication. asynctask helps you well. You will find that your code is easy to understand, because they all have some methods with specific responsibilities, especially asynctask, which has a preprocessing method onpreexecute, there are methods for executing tasks in the background, such as doinbackground, publishprogress for updating progress, onpostexecute for returning results, and so on. This is not like the methods for post, and all operations are written in a runnable. But the better the encapsulation, the more advanced the API, the worse it is for junior programmers, that is, you do not understand its principles. When you need to deal with more complex situations, and advanced APIs cannot be done well, you will have a cup of cake. Therefore, we also need to master the more powerful functions and more free ways to communicate with the main thread: the use of handler.
2) use Handler
Here, we need to know several classes for inter-thread communication provided by the android SDK.
2.1 Handler
Handler is responsible for sending and processing messages in Android. It can implement message communication between other threads and main threads.
2.2 Logoff
Logoff is responsible for managing the message queues and message loops of threads.
2.3 message
Message is the message carrier for inter-thread communication. The message serves as a container to store any messages you want to transmit between two terminals.
2.4 messagequeue
Messagequeue is a message queue. It is used to save messages to be processed by threads.
The relationship between the four is that handler is called in other threads. sendmsg () method (the parameter is a message object). Add the events that need to be processed by the main thread to the messagequeue of the main thread, when the main thread extracts the handler message from the Message Queue through mainlogoff, it calls back the handlermessage () method of handler.
In addition to the above two common methods, there are also several simple methods
3) activity. runonuithread (runnable)
4) view. Post (runnable)
View. postdelayed (runnable, long)
5) handler. Post
Handler. postdelayed (runnable, long)
4. Use the thread pool to improve performance
We recommend that you use a thread pool to manage temporary thread objects to improve application performance.
A thread pool is an instance of a resource pool in a thread application. Before learning about the thread pool, we should first understand the concept of the resource pool. In Java, creating and destroying objects consume resources. If we need to frequently create and destroy an object instance of a certain type in the application, many temporary objects will be generated. When there are too many temporary objects to be referenced, the virtual opportunity will be garbage collection (GC ), when the CPU is GC, the application may not run properly, resulting in reduced application responsiveness.
The resource pool is used to solve this problem. When you need to use an object, you can obtain it from the resource pool. The resource pool is responsible for maintaining the object lifecycle.
After learning about the resource pool, we will have a good understanding of the thread pool. The thread pool is the resource pool where all object types are stored in the thread.
I have added an example of how to create handler in other threads as an optional course. If you have mastered it, let's take a look. If you need to implement a message processing mechanism similar to that of the main thread, other threads are required to communicate with your thread, which can be implemented in this way.