Android has progress bar asynchronous task download picture

Source: Internet
Author: User

First add Internet access in Androidmainifest

<uses-permission android:name= "Android.permission.INTERNET"/>

Layout file Activity_main.xml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <imageview        android:id= "@+id/img"        android:layout_width= "Match_parent"        android:layout_height= "280DP"/>    <button        android:id= "@+id/btn"        android:layout_width= " 150DP "        android:layout_height=" 50DP "        android:text=" Download Picture "/></linearlayout>

Activity code:

public class Mainactivity extends Activity{private Button button;private ImageView imageview;private progressdialog Progressdialog;private final String Imath_path = "http://image16-c.poco.cn/best_pocoers/20141010/ 11092014101016572228935421.jpg ";p rivate asynctask<string, Integer, byte[]> 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);p rogressdialog = new ProgressDialog (this);p rogressdialog.settitle ("hint message");p Rogressdialog.setmessage (" In the download, please later ");p Rogressdialog.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 (). Execute (Imath_path);}}); Class Myasynctask extends Asynctask<string, Integer, byte[]>{@Overrideprotected void OnPreExecute () {//TODO Auto    -generated method Stubsuper.onpreexecute ();p rogressdialog.setprogress (0);p rogressdialog.show (); @Overrideprotected void Onprogressupdate (Integer ... values) {//TODO auto-generated method Stubsuper.onprogressupdate (   Values);p rogressdialog.setprogress (Values[0]);}  @Overrideprotected byte[] Doinbackground (String ... params) {//TODO auto-generated method Stubhttpclient httpClient = new Defaulthttpclient (); HttpGet httpget = new HttpGet (Params[0]), byte[] image = new Byte[]{};try{httpresponse HttpResponse = Httpclient.execute (h Ttpget); 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 = HT Tpentity.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 ();} }}

Explain:

Synctask: The asynchronous task, literally, is to do something asynchronously when the main thread of our UI is running. Asynctask allows us to perform an asynchronous task in the background. We can place time-consuming operations in asynchronous tasks and update our UI controls at any time by returning the results of the task execution to our UI thread. Through Asynctask we can easily solve the problem of communication between multiple threads.

How to understand Asynctask? In layman's terms, Asynctask is the equivalent of Android to provide us with a framework for multithreaded programming, between thread and handler, if we want to define a asynctask, we need to define a class to inherit Asynctask abstract class. , and implement its only one Doinbackgroud abstract method. To master Asynctask, we must have a concept, summed up is: 3 generics, 4 steps.

What are the 3 generic types referring to? Let's take a look at Asynctask's definition of this abstract class, and when we define a class to inherit asynctask, we need to specify 3 generic parameters for it:

 
    • params : This generic specifies the type of arguments we pass to the execution of the asynchronous task
    • progress : This generic specifies the type of parameters that our asynchronous task will execute when executing the progress returned to the UI thread
    • Result : The type of the result returned to the UI thread after the execution of this generic specified asynchronous task has completed

When we define a class that inherits the Asynctask class, we must specify the three generic types, and if none are specified, write them void, for example:

Asynctask <void, Void, void>

4 steps: When we execute an asynchronous task, it needs to follow the following 4 steps to perform the respective

  • OnPreExecute (): This method is executed before the asynchronous task executes, and is executed in the UI thread, usually in this method we do some initialization of the UI controls, such as popup to give ProgressDialog
  • Doinbackground (params ... params): This method is executed immediately after the OnPreExecute () method is executed, which is the method to handle the asynchronous task. The Android operating system will open a worker thread in the thread pool in the background to execute our method, so this method is executed in the worker thread, and after this method executes, we can send our execution results to our last OnPostExecute method, in this method, we can get data from the network and some time-consuming operation
  • onprogressupdate (Progess ... values): This method is also executed in the UI thread, and we sometimes need to return the progress of execution to our UI interface when the asynchronous task executes, such as downloading a picture of the web , we need to show the progress of their downloads at all times, and we can use this method to update our progress. Before this method is called, we need to invoke a publishprogress (Progress) method in the Doinbackground method to pass our progress to the Onprogressupdate method all the way to update
  • onpostexecute ( result ... result): When our asynchronous task executes, the result is returned to this method, which is also called in the UI thread, and we can display the returned results on the UI control

Android has progress bar asynchronous task download picture

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.