Android has a progress bar asynchronous task to download images

Source: Internet
Author: User

Android has a progress bar asynchronous task to download images

First, add the Internet access permission to AndroidMainifest.

 

 

Layout file activity_main.xml

 


Activity Code:

 

 

Public class MainActivity extends Activity {private Button button; private ImageView imageView; private ProgressDialog progre; private final String IMATH_PATH = http://image16-c.poco.cn/best_pocoers/20141010/11092014101016572228935421.jpg;private AsyncTask
 
  
Task; @ Overrideprotected void onCreate (Bundle savedInstanceState) {// TODO Auto-generated method stubsuper. onCreate (savedInstanceState); setContentView (R. layout. activity_main); button = (Button) findViewById (R. id. btn); imageView = (ImageView) findViewById (R. id. img); progressDialog = new ProgressDialog (this); progressDialog. setTitle (prompt information); progressDialog. setMessage (download in progress, please wait); progressDialog. setOnCancelListener (new OnCancelListener () {@ Overridepublic void onCancel (DialogInterface arg0) {// TODO Auto-generated method stubtask. cancel (true) ;}}); progressDialog. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); button. setOnClickListener (new OnClickListener () {@ Overridepublic void onClick (View arg0) {// TODO Auto-generated method stubtask = new myasynctask(cmd.exe cute (IMATH_PATH );}});} class MyAsyncTask extends AsyncTask
  
   
{@ Overrideprotected void onPreExecute () {// TODO Auto-generated method stubsuper. onPreExecute (); progressDialog. setProgress (0); progressDialog. show () ;}@ Overrideprotected void onProgressUpdate (Integer... values) {// TODO Auto-generated method stubsuper. onProgressUpdate (values); progressDialog. setProgress (values [0]);} @ Overrideprotected byte [] doInBackground (String... params) {// TODO Auto-generated m Ethod stubHttpClient httpClient = new DefaultHttpClient (); HttpGet httpGet = new HttpGet (params [0]); byte [] image = new byte [] {}; try {HttpResponse httpResponse = httpClient.exe cute (httpGet); HttpEntity httpEntity = httpResponse. getEntity (); InputStream inputStream = null; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream (); if (httpEntity! = Null & httpResponse. getStatusLine (). getStatusCode () = HttpStatus. SC _ OK) {long file_length = httpEntity. getContentLength (); long total_length = 0; int length = 0; byte [] data = new byte [1024]; inputStream = httpEntity. getContent (); while (-1! = (Length = inputStream. read (data) {total_length + = length; byteArrayOutputStream. write (data, 0, length); int progress = (int) (total_length/(float) file_length) * 100); publishProgress (progress);} image = byteArrayOutputStream. toByteArray (); inputStream. close (); byteArrayOutputStream. close ();} catch (Exception e) {e. printStackTrace ();} finally {httpClient. getConnectionManager (). shutdown () ;}return image ;}@ Overrideprotected void onPostExecute (byte [] result) {// TODO Auto-generated method stubsuper. onPostExecute (result); Bitmap bitmap = BitmapFactory. decodeByteArray (result, 0, result. length); imageView. setImageBitmap (bitmap); progressDialog. dismiss ();}}}
  
 

Explanation:

 

 

SyncTask: asynchronous tasks, literally, perform some operations asynchronously when the main UI thread is running. AsyncTask allows us to execute an asynchronous task in the background. We can place time-consuming operations in asynchronous tasks for execution, and return the task execution results to our UI thread at any time to update our UI control. With AsyncTask, we can easily solve the communication problem between multiple threads.

How to Understand AsyncTask? Generally speaking, AsyncTask is equivalent to a framework provided by Android for multi-threaded programming, which is between Thread and Handler. If we want to define an AsyncTask, define a class to inherit the abstract class AsyncTask and implement its unique doInBackgroud abstract method. To master AsyncTask, we must have a concept. In summary, there are three generic types and four steps.

What do the three generic types mean? Let's take a look at the definition of the abstract class AsyncTask. When we define a class to inherit the class AsyncTask, We need to specify three generic parameters for it:

AsyncTask 
 
  • Params: This generic type specifies the parameter type that we pass to the asynchronous task for execution.
  • Progress: This generic type specifies the type of parameters that our asynchronous task returns the execution Progress to the UI thread during execution.
  • Result: The type of the Result returned to the UI thread after the asynchronous task is executed.

    When defining a class to inherit the AsyncTask class, we must specify these three generic types. If none of them are specified, they are all written as Void. For example:

    AsyncTask 
       

    4 steps: When we execute an asynchronous task, perform the following 4 steps:

    • OnPreExecute (): This method is executed before the asynchronous task is executed, and is executed in the UI Thread. Generally, we initialize some UI controls in this method, for example
    • DoInBackground (Params... params): After the onPreExecute () method is executed, this method will be executed immediately. This method is used to process asynchronous tasks, the Android operating system starts a worker thread in the background thread pool to execute this method. Therefore, this method is executed in the worker thread, after this method is executed, we can send our execution results to our last onPostExecute method. In this method, we can obtain data from the network and perform some time-consuming operations.
    • OnProgressUpdate (Progess... values): This method is also executed in the UI Thread. During asynchronous task execution, we sometimes need to return the execution progress to our UI interface, for example, downloading a network image, we need to display the download progress at any time, so we can use this method to update our progress. Before calling this method, we need to call a publishProgress (Progress) method in the doInBackground method to transfer our Progress to the onProgressUpdate Method for update at all times.
    • OnPostExecute (Result... result): After an asynchronous task is executed, the result is returned to this method, which is also called in the UI Thread, we can display the returned results on the UI control.

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.