Understanding and Analysis of the single thread model in Android programming

  • 2020-09-16 07:46:46
  • OfStack

This article describes the understanding and analysis of the single thread model in Android programming. To share for your reference, the details are as follows:

When an Android program starts, the Android system starts a corresponding main thread (Main Thread) at the same time.

Since the main task of the main thread (Main Thread) is to handle 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.

The core principle of the IMP, Android single-threaded model is that UI can only be processed in UI threads (Main Thread).
To improve Performance, Android handles UI in relation to method, which is not synchronized, so when you try to manipulate UI with another thread, you throw the following exception:

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 all 1 cut operations in the UI thread.

Some operations (such as network operation, database operation, etc.) that take 10 minutes but have little impact on UI update will lead to UI Performance10fen poor if put in the UI thread for 1, right, very very poor, and even pop up ANR(Application Not Responding) window, which is undoubtedly unfriendly to users.

Ps: As far as I know, Android SDK does not support network related operations directly in Main Thread after version 4.0, unless you have the audacity to add the following code to the main thread:


StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 
  .detectDiskReads().detectDiskWrites().detectNetwork() 
  .penaltyLog().build()); 
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() 
  .detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath() 
  .build());

Thus, the principles of the Android single-threaded model can be summarized in two general terms:

1. Only process UI in UI thread (Main Thread). Do not access Android UI toolkit outside of UI thread

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

How to deal with multithreading in Android program, can you refer to Android official training

I hope this article is helpful for Android programming.


Related articles: