Today learned Apache wrote a Web download effect, code as follows, code I have written a very detailed comments, I believe we can read
1 http://m.blog.csdn.net/article/details?id=52927536 2 3 4 PackageCom.wuxianedu.httpdemo; 5 6 ImportAndroid.app.ProgressDialog; 7 ImportAndroid.content.Intent; 8 ImportAndroid.net.Uri; 9 ImportAndroid.os.AsyncTask; Ten Importandroid.support.v7.app.AppCompatActivity; ImportAndroid.os.Bundle; ImportAndroid.view.View; ImportAndroid.widget.Button; ImportAndroid.widget.Toast; 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; ImportJava.io.InputStream; ImportJava.io.OutputStream; The public class Main2activity extends appcompatactivity implementsview.onclicklistener{PrivateButton button; PrivateProgressDialog Dialog; PrivateString path; + private final int ta_c = 0;//success of private final int ta_s = -1;//Failure 33 34@Override protected voidOnCreate (Bundle savedinstancestate) {$ super. OnCreate (Savedinstancestate); 37Setcontentview (r.layout.activity_main2); button =(Button) Findviewbyid (r.id.but_id); Button.setonclicklistener (This); 40} 41 42@Override public voidOnClick (view view) {$ switch(View.getid ()) {caser.id.but_id:46 new Myhui (). Execute ("http://g.pc6.com/0942666043/apk/4001_ZMJ2016_04_20161028_rnikgd.apk"); Break; 48} 49} The class Myhui extends asynctask<string,integer,integer>{52//operations before the asynchronous task executes 53@Override protected voidOnPreExecute () {dialog = new ProgressDialog (main2activity.this); Dialog.settitle ("Downloading"); 57Dialog.setprogressstyle (progressdialog.style_horizontal); 58Dialog.show (); Super. OnPreExecute (); 60} 61//Update progress method call using Publishprogress 62@Override protected voidOnprogressupdate (Integer ... values) {dialog.setprogress (values[0]); Super. onprogressupdate (values); 66} 67//Task execution in method 68@Override protectedInteger Doinbackground (String ... strings) {70//Build URL address link httpget httpget = new HttpGet (strings[0]); 72//Establish client link HttpClient HttpClient = newDefaulthttpclient (); Try{75//Get data for server response HttpResponse response =Httpclient.execute (HttpGet); 77//Get status code + INT code =Response.getstatusline (). Getstatuscode (); Switch(code) {Case 201: Bayi Case 200: 82//Get maximum file size Zuimax int = (int) response.getentity (). Getcontentlength (); 84//To the progress bar to assign the maximum value 85Dialog.setmax (Zuimax); 86//Get file input stream InputStream is =Response.getentity (). getcontent (); 88//Get storage address of the PATH = Getexternalcachedir (). GetParent () + "/tanchishe.apk"; 90//Get the output stream of the file, the address of the incoming write file outputstream OS = newFileOutputStream (path); The INTLength 93//progress bar Progress 94 int Jindu = 0; byte[] bytes = new byte[1024]; (length = is.read (bytes))! =-1) {Os.write (bytes,0, length); 98 jindu+=Length 99//Start Assignment Method 100Publishprogress (Jindu); 101}102//Close Stream 103Is.close (); 104Os.flush (); 105Os.close (); 106 returnTA_C;107 Case 401: 108 Break; 109}110} catch(IOException e) {111E.printstacktrace (); 112}113 return ta_s;114 }115 116//End of Task method 117 @Override118 protected void onpostexecute (integer integer) {119/ /Close progress bar Dialog.dismiss (); 121 Switch (integer) {122 case ta_c:123 Toast.maketext ( Main2activity.this, "Download succeeded" , Toast.length_short). Show (); 124 setupapk (); break ; 126 case TA _s:127 Toast.maketext (main2activity.this, "Download Failed" , Toast.length_short). Show (); break ; 129 }130 Super . OnPostExecute (integer); 131 }132 }133 134/**135 * Start the app installation. 136 */137 private void setupapk () {138 Intent Intent = new Intent (Intent.action_view); 139//"file://" + file path. The URI uri = Uri.parse ("file://" + Path), 141 Intent.setdataandtype (URI, "application/ Vnd.android.package-archive "); 142 startactivity (intent); 143 }144}
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>
Android Learning notes-using Apache httpclient for Web download, with progress bar display