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