We have talked about Android UI design.Official tutorial on "Android UI" Design. This article will discuss the thread model of Android applications and how to use threads to process time-consuming operations, rather than executing them in the main thread to ensure smooth running of the UI. This article also describes some APIs that interact with threads in the User Interface UI.
UI User Interface thread
When an application starts, the system creates a main thread for the Application) or a UI thread, which distributes events to different components, including painting events. Complete the interaction between your application and the Android UI component.
For example, when you touch a button on the screen, the UI thread will distribute the touch event to the component, change the status and add it to the event queue. The UI thread will distribute requests and notifications to each component, complete the action.
The performance of the single-thread model is very poor unless your application is quite simple, especially when all operations are executed in the main thread, for example, time-consuming operations such as accessing the network or database will cause the user interface to be locked, and all events will not be distributed, and the application will be like dead, more seriously, the system will pop up the "Application No response" dialog box when it exceeds 5 seconds.
If you want to see the effect, you can write a simple application and write Thread in the OnClickListener of a Button. sleep (2000), run the program and you will see that the button will remain in the pressed state for 2 seconds before the application returns to normal state. When this happens, you will feel that the application is quite slow.
In short, we need to ensure that the main thread UI thread is not locked. If there is a time-consuming operation, we need to put it in a separate background thread for execution.
The following is an example of downloading an image by clicking the button and displaying it on the Image view page:
-
-
- public void onClick(View v) {
- new Thread(new Runnable() {
- public void run() {
- Bitmap b = loadImageFromNetwork();
- mImageView.setImageBitmap(b);
- }
- }).start();
- }
At first, the above Code seems to be a good solution because it does not lock the user interface thread. Unfortunately, it violates the single-thread model of the user interface: the Android User Interface toolkit is NOT thread-safe and can only be operated in the UI thread. In the code above, you call mImageView in a work thread. when setImageBitmap (B) is used, unexpected errors will occur, which are very difficult to track and debug.
Android provides several methods to access the UI thread from other threads. You may already be familiar with them. Below is a comprehensive list:
-
-
- Activity.runOnUiThread(Runnable)
- View.post(Runnable)
- View.postDelayed(Runnable, long)
- Handler
You can use any of these classes and methods to correct the previous code example:
- public void onClick(View v) {
- new Thread(new Runnable() {
- public void run() {
- final Bitmap b = loadImageFromNetwork();
- mImageView.post(new Runnable() {
- public void run() {
- mImageView.setImageBitmap(b);
- }
- });
- }
- }).start();
- }
Unfortunately, these classes and methods often make your code more complex and hard to read. What's worse, it needs to perform complex operation interface updates frequently.
To solve this problem, Android 1.5 and later versions provide an audit class called AsyncTask, which simplifies long-running tasks and requires interaction with the user interface.
A UserTask class similar to AsyncTask can also be used in Android 1.0 and 1.1. It provides identical APIs. All you need to do is copy its source code to your application.
The goal of AsyncTask is to provide management services for your threads. The previous example can be easily rewritten using AsyncTask:
- public void onClick(View v) {
- new DownloadImageTask().execute("http://www.ideasandroid.com/image.png");
- }
-
- private class DownloadImageTask extends AsyncTask<String, Void,Bitmap> {
- protected Bitmap doInBackground(String... urls) {
- return loadImageFromNetwork(urls[0]);
- }
-
- protected void onPostExecute(Bitmap result) {
- mImageView.setImageBitmap(result);
- }
- }
As you can see, We must inherit the AsyncTask class to use it. It is very important that AsyncTask must be instantiated in the UI thread and can only be executed once.
The following describes how to use AsyncTask:
◆ You can specify three parameter types, generic parameters, values returned during the Progress value execution) and returned values after the final value execution ).
◆ This method doInBackground) automatically executes the working thread (background thread)
◆ OnPreExecute), onPostExecute) and onProgressUpdate are both called in the UI thread.
◆ Value returned by doInBackground) sent to onPostExecute)
◆ You can call publishProgress when executing doInBackground) and then execute onProgressUpdate In the UI group ).
◆ You can cancel a task from any thread at any time
Whether or not you use AsyncTask, always remember the two rules of the single thread model:
1. Do not lock the user interface.
2. Ensure that only the components in the Android User Interface toolkit are accessed in the UI thread.
AsyncTask only makes it easier for you to do these tasks.
This article is not an original file. It is a foreign language translation. If there is anything wrong, please correct it !!
Original article:Http://www.ideasandroid.com/Android/sdk/docs/resources/articles/painless-threading.html