Android Learning-interface-event-asynctask

Source: Internet
Author: User

Asynchronous task Asynctask complete a download

Activity_main.xml

<Relativelayoutxmlns: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"Tools:context= "${relativepackage}.${activityclass}" >    <ButtonAndroid:id= "@+id/button1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignparentleft= "true"Android:layout_alignparenttop= "true"Android:layout_marginleft= "23DP"Android:layout_margintop= "14DP"Android:text= "Start Download" />    <EditTextAndroid:id= "@+id/edittext1"Android:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:layout_alignleft= "@+id/button1"Android:layout_alignparentbottom= "true"Android:layout_alignparentright= "true"Android:layout_below= "@+id/button1"Android:layout_margintop= "45DP"Android:ems= "Ten"Android:inputtype= "Textmultiline" >        <Requestfocus/>    </EditText></Relativelayout>
View Code

Mainactivity.java

 Public classMainactivityextendsActivity {EditText editText1;        Button btn1; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); EditText1=(EditText) Findviewbyid (R.ID.EDITTEXT1); BTN1=(Button) Findviewbyid (R.id.button1); Btn1.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Mydown down=NewMydown (mainactivity. This); Try{Down.execute (NewURL ("http://w.x.baidu.com/alading/anquan_soft_down_normal/12350")); } Catch(malformedurlexception e) {//TODO Auto-generated catch blockE.printstacktrace ();    }                            }        }); }            classMydownextendsAsynctask<url, Integer, string>{        //Download ProgressProgressDialog p; //Total Download Volume        intTotalsize=0; //Current Download        intDownloadszie=0;        Context context; //Download Start timeCalendar date_s=calendar.getinstance (); //Download End TimeCalendar date_e;  PublicMydown (Context context) { This. context=context; } @Overrideprotected voidOnPreExecute () {p=NewProgressDialog (context); P.setmax (0); P.settitle ("In Task Execution"); P.setmessage ("Task execution completed than, please wait ...");             P.setprogressstyle (progressdialog.style_horizontal); P.setcancelable (false); P.setindeterminate (false);        P.show (); } @OverrideprotectedString doinbackground (URL ... params) {stringbuffer str=NewStringBuffer (); Try{httpurlconnection http= (httpurlconnection) params[0].openconnection (); //get total Download VolumeTotalsize=http.getcontentlength (); InputStream in=Http.getinputstream (); byte[] buffer =New byte[1024]; intReadsize=0;  while(Readsize=in.read (buffer))!=-1) {date_e=calendar.getinstance (); //calculates the total time of the download, mainly for the calculation of k/s                    intA= (int) (Date_e.gettimeinmillis ()-date_s.gettimeinmillis ())/1000; //Total DownloadsDownloadszie =downloadszie +readsize; //Refresh UIpublishprogress (downloadszie,totalsize,a); }                returnstr.tostring (); } Catch(Exception e) {//TODO Auto-generated catch blockE.printstacktrace (); }            return NULL; }                protected voidOnPostExecute (String result) {Edittext1.settext ("Download Complete");        P.dismiss (); } @Overrideprotected voidonprogressupdate (Integer ... values) {p.setprogress (values[0]/1024); P.setmax (values[1]/1024); intSed=0; if(values[2]==0) sed=1;ElseSed=values[0]/1024/values[2]; P.setmessage ("Task execution completed than, please wait ... \ n speed" +sed+ "k/s"); }            }}
View Code

Android Learning-interface-event-asynctask

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.