Several ways for Android to update the UI asynchronously

Source: Internet
Author: User

Objective

? We know that in Android development you can't update the UI in a non-UI thread, but sometimes we need to do some time-consuming operations like accessing the network, querying the database, and so on, in order not to block the UI thread, we often open a new thread (worker thread) to perform these time-consuming operations. Then we may need to render the queried data to the UI component, so we need to consider the problem of updating the UI asynchronously.

There are several workarounds for the following asynchronous update UI in Android:

    1. Activity.runonuithread (Runnable)
    2. View.post (Runnable)
    3. Long) view.postdelayed (Runnable, long)
    4. Using handler (inter-thread communication) (recommended)
    5. Asynctask (recommended)

For the following code:

publicvoidonClick(View v) {     new Thread(new Runnable() {         publicvoidrun() {            Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");            mImageView.setImageBitmap(bitmap);             }     }).start(); }

This code is a button click event Response method, when clicked on this button to open a sub-thread to load the image on the network, and then in this thread to set a picture (updated UI), this code in the non-UI thread to update the UI, run will throw an error imageview.

1. Activity.runonuithread:

Typically, in activity, we can use the activity's Runonuithread method to update the UI.

Such as:

publicvoidonClick(View v) {     new Thread(new Runnable() {         publicvoidrun() {            Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");           runOnUiThread(new Runnable() {                @Override                publicvoidrun() {                    mImageView.setImageBitmap(bitmap);                  }           });                      }     }).start(); }

2. View.post (runable)

The view class and its subclasses provide a post (runable) method that allows us to put our actions into the Run method of this anonymous Runable object, where we can update the UI directly.

Such as:

publicvoidonClick(View v) {     new Thread(new Runnable() {         publicvoidrun() {            Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");           imageView.post(new Runnable() {              @Override              publicvoidrun() {                  mImageView.setImageBitmap(bitmap);                }           });                     }     }).start(); }

3. Long) view.postdelayed (Runnable, long)

The

and View.post (runable) methods, just defer execution after the time specified by the second parameter, and View.post (runable) is executed immediately.

public  void  onclick  (View v) {new  Thread (new  Runnable () {public  void  run  () {Bitmap Bitmap = loadimagefromnetwork ( "http://example.com/image.png" ); Imageview.postdelayed (new  Runnable () { @Overr IDE  public  void  run  () {mimageview.setimagebitmap (bitmap);                  }},2000 ); }}). Start (); }

4. Using handler (recommended)

There are several ways of saying that when this is too much, our code will look bloated, the code and the business are difficult to manage control, so we should take a handler approach when this kind of code is too much.

Such as:

new Thread(new Runnable() {     publicvoidrun() {         Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png");          Message message = mHandler.obtainMessage();        1;        message.obj = bitmap;        mHandler.sendMessage(message);            } }).start();     
new Handler(){    @Override    publicvoidhandleMessage(Message msg) {        switch (msg.what){            case1:                Bitmap bitmap = (Bitmap) msg.obj;                imageView.setImageBitmap(bitmap);                break;            case2:                // ...                break;            default:                break;        }    }};

5. Asynctask (recommended)

Android provides us with asynchronous task Asynctask, and we can use Asynctask to easily implement asynchronous loading of data and updating the UI.

Such as:

Asynctask<string,void,bitmap> Asynctask =NewAsynctask<string, Void, bitmap> () {/** * Callback is going to take time-consuming tasks, there are some initialization operations here.    @Override    protected void OnPreExecute() {Super. OnPreExecute (); }/** * Takes a time-consuming operation in the background, and its return value will be the parameter of the OnPostExecute method * @param params * @return  */    @Override    protectedBitmapDoinbackground(String ... params) {Bitmap Bitmap = loadimagefromnetwork (params[0]);returnBitmap }/** * When this asynchronous task is completed, that is, after the Doinbackground () method is completed, the return result of the method is the parameter * @param bitmap */    @Override    protected void OnPostExecute(Bitmap Bitmap)    {Imageview.setimagebitmap (bitmap); }};asynctask.execute ("Http://example.com/image.png");

What you need to know is that the Doinbackground method works in a worker thread, so we perform time-consuming operations in this method. At the same time, because the return result is passed to the OnPostExecute method, and the OnPostExecute method works on the UI thread, we update the UI in this method, which is the purpose of updating the UI asynchronously.

In fact, for Android to load data asynchronously and update the UI, we can choose not only the Asynctask asynchronous task, but also many open source network frameworks, such as xutils,volley,okhttp, ..., These excellent network frameworks make it easy to update the UI asynchronously, and the efficiency and performance are very high.

Summarize:

? For many of the solutions above, in fact they do the same thing, that is to do time-consuming tasks in the worker thread, and then update the UI in the UI thread, but the process is not the same, there is a direct package for us, there is a need for our own control management.

Several ways for Android to update the UI asynchronously

Related Article

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.