Android Learning notes-using HttpURLConnection for Web download effects with progress bar display

Source: Internet
Author: User

I'm going to go directly to the code, because I've written very detailed comments in the code.

1  PackageCom.wuxianedu.httpdemo;2 3 ImportAndroid.app.ProgressDialog;4 Importandroid.content.Intent;5 ImportAndroid.net.Uri;6 ImportAndroid.os.AsyncTask;7 ImportAndroid.os.Handler;8 ImportAndroid.os.Message;9 Importandroid.support.v7.app.AppCompatActivity;Ten ImportAndroid.os.Bundle; One ImportAndroid.view.View; A ImportAndroid.widget.Button; - ImportAndroid.widget.Toast; -  the ImportOrg.apache.http.HttpResponse; - Importorg.apache.http.client.HttpClient; - ImportOrg.apache.http.client.methods.HttpGet; - Importorg.apache.http.impl.client.DefaultHttpClient; +  - ImportJava.io.FileOutputStream; + Importjava.io.IOException; A ImportJava.io.InputStream; at ImportJava.io.OutputStream; - Importjava.net.HttpURLConnection; - Importjava.net.MalformedURLException; - ImportJava.net.URL; -  -  Public classMain2activityextendsAppcompatactivityImplementsview.onclicklistener{ in  -     Privatebutton button; to     PrivateProgressDialog Dialog; +     PrivateString Path; -     PrivateHandler Handler =NewHandler () { the @Override *          Public voidhandlemessage (Message msg) { $ dialog.setprogress (msg.what);Panax Notoginseng             Super. Handlemessage (msg); -         } the     }; +  A @Override the     protected voidonCreate (Bundle savedinstancestate) { +         Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.activity_main2); $button =(Button) Findviewbyid (r.id.but_id); $Button.setonclicklistener ( This); -Dialog =NewProgressDialog ( This); -     } the  - @OverrideWuyi      Public voidOnClick (view view) { the         Switch(View.getid ()) { -              Caser.id.but_id: WuDialog.settitle ("Download It"); - Dialog.setprogressstyle (progressdialog.style_horizontal); About dialog.show (); $                 NewThread (NewRunnable () { - @Override -                      Public voidrun () { - GetURL (); A                     } + }). Start (); the                  Break; -         } $     } the  the     /** the * Start the app installation.  the      */ -     Private voidsetupapk () { inIntent Intent =NewIntent (intent.action_view); the         //"File://"+ file path.  theUri uri = uri.parse ("file://" +path); AboutIntent.setdataandtype (URI, "application/vnd.android.package-archive"); the startactivity (intent); the     } the  +     Private voidGetURL () { -         Try { the             //Build URL addressBayiURL url =NewURL ("http://g.pc6.com/0942666043/apk/4001_ZMJ2016_04_20161028_rnikgd.apk"); the             Try { the                 // Open Open Open -HttpURLConnection Hcont =(HttpURLConnection) url.openconnection (); -                 //establish the actual link the Hcont.connect (); the                 //get input stream content theInputStream is =Hcont.getinputstream (); the                 //Get file length -                 intDDDDD =hcont.getcontentlength (); the                 //assign a value to a progress bar the Dialog.setmax (DDDDD); the                 //Phone storage Address94Path = Getexternalcachedir (). GetPath () + "/wuxl.apk"; the                 //Write File theOutputStream OS =NewFileOutputStream (path); the                 intlength;98                 intLengtsh = 0; About                 byte[] bytes =New byte[1024]; -                  while(length = is.read (bytes))! =-1){101Os.write (bytes,0, length);102                     //get Current progress value103lengtsh+=length;104                     //Pass the value to handler . the handler.sendemptymessage (lengtsh);106                 }107                 //Close the stream108 is.close ();109 os.close (); the Os.flush ();111 Dialog.dismiss (); theRunonuithread (NewRunnable () {113 @Override the                      Public voidrun () { theToast.maketext (main2activity. This, "downloaded successfully", Toast.length_short). Show (); the                     }117                 });118}Catch(IOException e) {119 e.printstacktrace (); -             }121 122}Catch(malformedurlexception e) {123 e.printstacktrace ();124         } the     }126}

Here is the layout file

1 <?XML version= "1.0" encoding= "Utf-8"?>2 <Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"3 Xmlns:tools= "Http://schemas.android.com/tools"4 Android:layout_width= "Match_parent"5 Android:layout_height= "Match_parent"6 7 Tools:context= "Com.wuxianedu.httpdemo.Main2Activity">8 9     <ButtonAndroid:id= "@+id/but_id"Android:text= "Download App"Ten Android:layout_width= "Wrap_content" One Android:layout_height= "Wrap_content" /> A </Relativelayout>

Very simple, everyone in the use of the time do not forget to add network permissions ha

Android Learning notes-using HttpURLConnection for Web download effects with progress bar display

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.