This post appears on my blog
This article as a “translation”, the original link: www.mergeconflict.net/2012/05/jav…
The translation is authorized by the original author. The level is limited, if there is any omission, please correct, thank you ~
preface
There is a very important but less discussed issue in Android development: UI responsiveness. Part of the problem is the Android system itself, but more often it’s the developer’s responsibility. The key, among other things, is to get as much of the time consuming work done in the background as possible. As we all know, there are basically only two ways to put time-consuming or CPU-intensive tasks in the background:
-
Java Thread
-
Android native AsyncTask helper class
It is not always clear which one is better than the other, so understanding their usage scenarios can help you optimize performance.
Usage scenarios of AsyncTask
-
Simple network operations that do not require downloading large amounts of data
-
I/O intensive tasks that may take more than a few milliseconds
Java Thread usage scenarios
-
Involving moderate or large amounts of network data manipulation (including upload and download)
-
Cpu-intensive tasks that need to be performed in the background
-
When you want to control CPU usage in the UI thread
There is also the perennial issue of never performing network operations on the UI thread (main thread). You need to use one of these two methods to access the network.
The key point
The key difference between Java Threads and AsyncTasks is that AsyncTasks run on top of GUI threads, so heavy CPU tasks can make the UI less responsive. Java Threads can have different Thread priorities, and using low-priority threads to complete non-real-time computing tasks is a good way to free up CPU time for GUI operations. This is one of the key points to make your GUI more responsive.
However, as many Android developers know, you can’t update UI components in background threads without throwing exceptions. This is not a big deal for AsyncTask, but when you use A Java Thread, you must update the UI³ with post() at the end of your operation.
Note:
-
AsyncTask must be loaded on the main thread, where all three methods except doInBackground(Object []) are run on the UI thread
-
Based on the first point, AsyncTask can update UI components in the remaining three methods
-
UI components can be updated using the view.post() method, which is not very different from using the activity.runonuithRead () method
See:
-
Java threads vs. Android AsyncTask: Which to use?
-
AsyncTask Android Developers
-
Update UI from Thread
-
Android: What’s the difference between Activity.runOnUiThread and View.post?