Understanding and analysis of single thread model in Android programming

This paper describes the understanding and analysis of single thread model in Android programming. Share with you for your reference, as follows:

When an Android program starts, the Android system will start a corresponding main thread at the same time.

Because the main task of this main thread is to process UI related events (such as displaying text, processing click events, displaying pictures, etc.), the system calls to each component are distributed from the main thread, so it is often called UI thread.

Imp, the core principle of Android single thread model is that UI can only be processed in the UI thread (main thread). In order to improve performance, Android does not synchronize the UI processing methods, so when you try to operate the UI with other threads, the following exception will be thrown:

android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

Of course, this does not encourage us to put everything in the UI thread.

Some very time-consuming operations (such as network operations, database operations, etc.) that have little impact on UI update will lead to UI performance poor, yes, very poor, and even pop-up anr (application not responding) window, which is undoubtedly very unfriendly to users.

PS: as far as I know, the Android SDK does not support direct network related operations in the main thread after version 4.0, unless you brazenly add the following code to the main thread:

Therefore, the principles of Android single thread model can be summarized as follows:

1. The UI can only be processed in the UI thread. Do not access the Android UI toolkit outside the UI thread

2. Do not block the UI thread with time-consuming operations

For how to handle multithreading in Android programs, please refer to the official Android training

I hope this article will help you in Android programming.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>