Android: Introduction to asynchronous task asyncTask and download image of asynchronous task (with progress bar)

Source: Internet
Author: User

Android: Introduction to asynchronous task asyncTask and download image of asynchronous task (with progress bar)

Why use an asynchronous task?

In android, the ui can be updated only in the main thread, while other threads cannot directly perform operations on the ui.

Android itself is a multi-threaded operating system. We cannot place all operations in the main thread, such as time-consuming operations. If a blocking event is placed in the main thread, the system throws an anr exception when the blocking event is too long. So we need to use Asynchronous tasks. Android provides an encapsulated component asynctask.

AsyncTask can update the ui in the Child thread, which encapsulates and simplifies asynchronous operations. It is suitable for simple asynchronous processing. If Handler is required for multiple background tasks, it is not described here.

AsyncTask is generally used to be inherited. AsyncTask defines three generic types

Params: parameter type entered when the task is started

Progress: Percentage of backend tasks executed

Result: Type of the returned Result after the task is executed.

The methods to be rewritten After inheriting AsyncTask include:

DoInBackgroud: It must be rewritten. The tasks to be completed by the background thread are asynchronously executed. time-consuming tasks must be written here, And the ui cannot be operated here. You can call publishProgress to update the real-time task progress.

OnPreExecute: called before execution of time-consuming operations. initialization can be completed.

OnPostExecute: After doInBackground is executed, the main thread calls this method. You can operate the ui in this method.

OnProgressUpdate: The publishProgress method is called in the doInBackgroud method. This method is called after the task execution progress is updated.

The following is an example of AsyncTask.

First, attach the running result

Layout file:

<Linearlayout xmlns: android = "http://schemas.android.com/apk/res/android" xmlns: tools = "http://schemas.android.com/tools" android: layout_width = "match_parent" android: layout_height = "match_parent" android: orientation = "vertical"> <button android: id = "@ + id/btn_download" android: layout_width = "wrap_content" android: layout_height = "wrap_content" android: layout_gravity = "center_horizontal" android: text = "click to download"> <framelayout android: layout_width = "fill_parent" android: layout_height = "fill_parent"> <imageview android: id = "@ + id/iv_image" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: scaletype = "fitCenter"> </imageview> </framelayout> </button> </linearlayout>
MainActivity
Package com. example. asynctask; import java. io. bufferedInputStream; import java. io. byteArrayOutputStream; import java. io. IOException; import java. io. inputStream; import java.net. malformedURLException; import java.net. URLConnection; import android. OS. asyncTask; import android. OS. bundle; import android. app. activity; import android. app. progressDialog; import android. graphics. bitmap; import android. graphics. bitmapFactory; import android. view. view; import android. view. view. onClickListener; import android. widget. button; import android. widget. imageView; public class MainActivity extends Activity implements OnClickListener {private ImageView image; private ProgressDialog SS; private Button btn_download; private static String URL = "http://img4.imgtn.bdimg.com/it/u=1256159061,743487979&fm=21&gp=0.jpg"; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); image = (ImageView) findViewById (R. id. iv_image); btn_download = (Button) findViewById (R. id. btn_download); progress = new ProgressDialog (this); progress. setIcon (R. drawable. ic_launcher); progress. setTitle ("prompt message"); progress. setMessage ("downloading... please wait... "); progress. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); btn_download.setOnClickListener (this);} @ Overridepublic void onClick (View v) {// TODO Auto-generated method stubnew myasynctask(.exe cute (URL );} /** String ********* corresponds to the Progress value of the progress bar of our URL type * Integer ****** * ** type returned after the asynchronous task is completed **/class MyAsyncTask extends AsyncTask
 
  
{// Run the command before the asynchronous task (doInBackground) and run @ Overrideprotected void onPreExecute () {// TODO Auto-generated method stubsuper In the ui thread. onPreExecute (); if (image! = Null) {image. setVisibility (View. GONE);} // The progress bar of the Start download dialog box displays progress. show (); progress. setProgress (0) ;}@ Overrideprotected Bitmap doInBackground (String... params) {// TODO Auto-generated method stub // params is a variable length array. Here we only pass in a url String url = params [0]; bitmap bitmap = null; URLConnection connection; InputStream is; // The input stream ByteArrayOutputStream bos used to obtain data; // it can capture data in the memory buffer and convert it into a byte array. Int len; float count = 0, total; // count indicates the total size of the downloaded image. try {// obtain the network connection object connection = (URLConnection) new java.net. URL (url ). openConnection (); // obtain the total length of the current page total = (int) connection. getContentLength (); // get the input stream is = connection. getInputStream (); bos = new ByteArrayOutputStream (); byte [] data = new byte [1024]; while (len = is. read (data ))! =-1) {count + = len; bos. write (data, 0, len); // call publishProgress to publish the progress, and the onProgressUpdate method will be executed publishProgress (int) (count/total * 100 )); // to display the progress, the Thread is sleeping for 0.5 seconds. sleep (500);} bitmap = BitmapFactory. decodeByteArray (bos. toByteArray (), 0, bos. toByteArray (). length); is. close (); bos. close ();} catch (MalformedURLException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return bitmap;} // you can run the ui @ Overrideprotected void onPostExecute (Bitmap bitmap) in the ui thread {// TODO Auto-generated method stubsuper. onPostExecute (bitmap); // The progress bar of the download completion dialog box hides progress. cancel (); image. setImageBitmap (bitmap); image. setVisibility (View. VISIBLE );} /** after the publishProgress method has been called in the doInBackground method to update the task execution progress * call this method to update the progress bar **/@ Overrideprotected void onProgressUpdate (Integer... values) {// TODO Auto-generated method stubsuper. onProgressUpdate (values); progress. setProgress (values [0]) ;}}
 

Do not forget to configure network access permissions in the AndroidManifest file.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

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.