AsyncTask download image asynchronously update UI

Source: Internet
Author: User

Because AndroidUI threads cannot perform time-consuming operations, such as file downloads and network connections. Therefore, operations must be performed in the new thread. Usually the acquired data needs to be displayed in the current Activity, and the UI cannot be updated in other threads. There are two methods: 1. Handler 2. AsyncTask

I tried the Handler method before, and it was easy to understand and complicated. Later I saw various articles about AsyncTask, so I tried it with reference to google's API guides.

Now we will use AsyncTask to download the image and update it to the current UI.

Only two steps are required to complete this task.

1. Write a class to inherit AsyncTask

2. Use this class in OnClick

First look at the activity_main.xml file. Simple layout: a button and an ImageView box

         

Next, let's take a look at the MainActivity. java file.

MainActivity // declare Button and ImageView Button = ImageView imageView = // get button and ImageView Button = // set listener button for the button. setOnClickListener (ButtonListener // when the button is pressed, start to execute this AsyncTask getimagetask(cmd.exe cute ("http://content.52pk.com/files/121122/1284656_175821_1_lit.jpg" // create a class by yourself, inherit the <String, Void, bitmap> refers to the parameter, progress, and return value.
// Parameter: The network address of an image, so it should be String
// Progress: Not clear. It generally refers to the progress of this time-consuming operation. You can update the progress to the progress bar for display.
// Return value: the returned image is Bitmap.
GetImageTask AsyncTask <String, Void, Bitmap >=. loadImageFromNetwork (urls [0 // override method. After a time-consuming operation is executed, update the obtained Bitmap to the ImageView Bitmap loadImageFromNetwork (String imageUrl) ====

References: http://developer.android.com/reference/android/ OS /AsyncTask.html

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.