Android UI design and background thread Interaction

Source: Internet
Author: User

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:

 
 
  1.  
  2.  
  3. public void onClick(View v) {  
  4.   new Thread(new Runnable() {  
  5.     public void run() {  
  6.       Bitmap b = loadImageFromNetwork();  
  7.       mImageView.setImageBitmap(b);  
  8.     }  
  9.   }).start();  
  10. }  

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:

 
 
  1.  
  2.  
  3. Activity.runOnUiThread(Runnable)  
  4. View.post(Runnable)  
  5. View.postDelayed(Runnable, long)  
  6. Handler  

You can use any of these classes and methods to correct the previous code example:

 
 
  1. public void onClick(View v) {  
  2.   new Thread(new Runnable() {  
  3.     public void run() {  
  4.       final Bitmap b = loadImageFromNetwork();  
  5.       mImageView.post(new Runnable() {  
  6.         public void run() {  
  7.           mImageView.setImageBitmap(b);  
  8.         }  
  9.       });  
  10.     }  
  11.   }).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:

 
 
  1. public void onClick(View v) {  
  2.   new DownloadImageTask().execute("http://www.ideasandroid.com/image.png");  
  3. }  
  4.    
  5. private class DownloadImageTask extends AsyncTask<String, Void,Bitmap> {  
  6.      protected Bitmap doInBackground(String... urls) {  
  7.          return loadImageFromNetwork(urls[0]);  
  8.      }  
  9.    
  10.      protected void onPostExecute(Bitmap result) {  
  11.          mImageView.setImageBitmap(result);  
  12.      }  
  13.  } 

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.