Android-async-http Project Address Https://github.com/loopj/android-async-http,android-async-http, as the name implies, is an asynchronous HTTP request, but it also supports synchronous request , this article mainly uses the android-async-http to do the asynchronous request to download the file. Whenever the app needs to update the new version, it needs to use the download function, the research android-async-http this third-party open source project is very useful, here is introduced to you.
1. Download class Downloadmanager.java
Package Com.figo.study.latin.mgr;import Java.io.file;import Java.io.ioexception;import java.util.HashMap;import Org.apache.http.header;import Android.content.context;import Android.net.connectivitymanager;import Android.os.environment;import Com.figo.study.r;import Com.android.inputmethod.latin.model.asyncdownload;import Com.figo.study.util.fileutil;import Com.figo.study.util.networkutil;import Com.loopj.android.http.asynchttpclient;import com.loopj.android.http.fileasynchttpresponsehandler;/** * Asynchronous Download class * @ Author Figo * */public class Downloadmanager {private Boolean musewifionly = false; Public Downloadmanager () {} private hashmap<string, asyncdownload> asyncdownlaods = null; public void init () {asyncdownlaods = new hashmap<string, asyncdownload> (); public void Download (final context context, string URL, final string md5, String Dirpath, String fileName, final down Loadlistener callback) {try {callback.onstart (); if (! Networkutil.isnetworkuseful (context)) {Callback.onerror (context.getstring (r.string.lbl_network_useless)); if (musewifionly) {if (Networkutil.getnetworktype (context)! = Connectivitymanager. Type_wifi) {callback.onerror (context.getstring (R.string.lbl_not_support)); } return; } String Sdpath = environment.getexternalstoragedirectory () + "/"; Asynchttpclient client =new asynchttpclient (); if (!asyncdownlaods.containskey (URL)) {asyncdownload asyncdownload = new Asyncdownload (); Asyncdownload.setasynchttpclient (client); Asyncdownload.setfilename (Sdpath + Dirpath + fileName); Asyncdownlaods.put (URL, asyncdownload); }else {client=asyncdownlaods.get (URL). getasynchttpclient (); } File File = new file (Sdpath + Dirpath, FilenaME); try {fileutil.createsddir (Dirpath); File = Fileutil.createsdfile (Dirpath + fileName); } catch (IOException E1) {if (e1! = null) {e1.printstacktrace (); }} Fileasynchttpresponsehandler Fileasynchttpresponsehandler = new Fileasynchttpresponsehandler (fil e) {@Override public void OnCancel () {super.oncancel (); System.out.print ("Cancel success!"); } @Override public void onprogress (int byteswritten, int totalsize) {sup Er.onprogress (Byteswritten, totalsize); int currentprogress = (int) ((Byteswritten * 1.0f/totalsize) * 100); Callback.onprogress (currentprogress); } @Override public void OnStart () {Super.onstart (); } @Override public void onfailure (int arg0, header[] arg1, Throwable arg2, File arg3) { if (arg2! = null) {arg2.printstacktrace (); } if (arg2! = null) {Callback.onerror (Arg2.getmessage ()); } else {Callback.onerror (context.getstring (r.string.lbl_network_error)); }} @Override public void onsuccess (int arg0, header[] arg1, File arg2) { String md5string = ""; try {md5string = fileutil.getfilemd5string (arg2); } catch (Exception e) {if (E! = null) {e.printstacktrace (); }}//if (md5.equals (md5string) = = False) {//C Allback.onerror (context.GetString (R.string.lbl_md5_error));/} else {//callback.onsuccess ();// }//Test release callback.onsuccess (); } }; Client.setenableredirects (TRUE);//Allow duplicate download of client.get (context, URL, fileasynchttpresponsehandler); } catch (Exception e) {callback.onerror (context.getstring (R.string.lbl_system_err)); }} public void Setdownloadwifionly (Boolean value) {musewifionly = value; } public void Canceldownload (context context, String URL) {try {if (asyncdownlaods! = null &&am P Asyncdownlaods.containskey (URL)) {//Downloaded files deleted fileutil.deletefile (asyncdownlaods.get (URL)). g Etfilename ()); Cancels the current download asynchttpclient client = asyncdownlaods.get (URL). getasynchttpclient (); if (client! = null) {client.cancelrequESTs (context, true); }//Current key delete asyncdownlaods.remove (URL); }} catch (Exception e) {if (E! = null) {e.printstacktrace (); } } }}
2, download the monitoring class Downloadlistener.java
Public interface Downloadlistener {public void OnStart (); public void OnError (String errmessage); public void onsuccess (); public void OnProgress (int progress);}
3, File management class Fileutil.java
/** * */package com.figo.study.util;import java.io.file;import java.io.fileinputstream;import java.io.IOException; Import Java.io.inputstream;import Java.security.messagedigest;import java.security.NoSuchAlgorithmException; Import android.os.environment;/** * @author Figo * */public class Fileutil {//Get the current external storage device directory (/sdcard) static St Ring Sdpath = environment.getexternalstoragedirectory () + "/"; /** * Default password string combination, used to convert bytes to 16 binary notation characters, Apache check the correctness of the downloaded file is the default of this combination */protected static char hexdigits[] = { ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ' , ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F '}; protected static MessageDigest messagedigest = null; static {try {messagedigest = messagedigest.getinstance ("MD5"); } catch (NoSuchAlgorithmException e) {e.printstacktrAce (); }} public static String getfilemd5string (file file) throws IOException {InputStream fis; FIS = new FileInputStream (file); byte[] buffer = new byte[1024]; int numread = 0; while ((Numread = fis.read (buffer)) > 0) {messagedigest.update (buffer, 0, numread); } fis.close (); Return Buffertohex (Messagedigest.digest ()); } private static String Buffertohex (byte bytes[]) {return Buffertohex (bytes, 0, bytes.length); } private static String Buffertohex (byte bytes[], int m, int n) {stringbuffer stringbuffer = new StringBuffer (2 * N); int k = m + N; for (int l = m; l < K; l++) {Appendhexpair (bytes[l], stringbuffer); } return stringbuffer.tostring (); } private static void Appendhexpair (Byte bt, StringBuffer stringbuffer) {char C0 = hexdigits[(BT & 0xf0) &G T;> the number of high 4 bits in the 4];//byte conversion//to the right shift of the logic, move the sign bit to the right, there is no difference between the two symbols found here Char C1 = HEXDIGITS[BT & 0xf];//takes a low 4-bit digital conversion stringbuffer.append (C0) in bytes; Stringbuffer.append (C1); public static void Main (string[] args) throws IOException {File File = new file ("E:/test/crm_account_yyyy_mm_ DD.txt "); String MD5 = getfilemd5string (file); SYSTEM.OUT.PRINTLN ("MD5:" + MD5); /** * Create file on SD card * @param fileName * @return * @throws IOException */public static F Ile Createsdfile (String fileName) throws IOException {File File = new file (Sdpath + fileName); if (file.exists ()) {final file to = new file (File.getabsolutepath () + System.currenttimemillis ()); File.renameto (to); To.delete ();//File.delete (); } file.createnewfile (); return file; /** * Create directory on SD card * @param dirName * @return * */public static File Createsddir (String Dirnam e) {File Dir = new File (Sdpath + DirName); if (!dir.exists ()) {dir.mkdirs (); } return dir; /** * Determine if the folder on the SD card exists * @param fileName * @return */public boolean isfileexist (String file Name) {File File = new file (Sdpath + fileName); return file.exists (); }/** * Delete file * @param fileName * @return * * * public static void DeleteFile (String Filenam E) {try {File file = new file (fileName); if (file.exists ()) {file.delete (); }} catch (Exception e) {if (e!=null) {e.printstacktrace (); } } }}
4, Network management class Networkutil.java
public class Networkutil {public static int getnetworktype (Context mcontext) {TR Y {final Connectivitymanager Connectivitymanager = (connectivitymanager) mcontext.getsystemservice (Context.CON Nectivity_service); Final Networkinfo networkinfo = Connectivitymanager.getactivenetworkinfo (); return Networkinfo.gettype (); } catch (Exception e) {return connectivitymanager.type_wifi; }} public static Boolean isnetworkuseful (Context mcontext) {final Connectivitymanager Connectivityma Nager = (Connectivitymanager) mcontext. Getsystemservice (Context.connectivity_service); Final Networkinfo mobnetinfoactivity = Connectivitymanager. Getactivenetworkinfo (); if (mobnetinfoactivity = = NULL | |!mobnetinfoactivity.isavailable ()) {return false; }else {return true; } }}
5. Test Testdownloadactivity.java
/** * */package com.figo.study.activity;import android.app.activity;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Com.figo.study.R; Import Com.android.inputmethod.latin.mgr.downloadlistener;import Com.android.inputmethod.latin.view.horizontalprogressbarwithnumber;import Com.loopj.android.http.asynchttpclient;import com.loopj.android.http.fileasynchttpresponsehandler;/** * @author Avazu * */public class Testdownloadactivity extends Activity {private Horizontalprogressbarwithnumber Mprogressbar, MP ROGRESSBAR1; Private Button Btndownload, Btncancel, Btn_pause_continue, BtnDownload1, BtnCancel1; Asynchttpclient client = new Asynchttpclient (); Fileasynchttpresponsehandler fileasynchttpresponsehandler = null; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub super.o Ncreate (savedinstancestate); Setcontentview (r.layout.activity_download_test); Initview (); } private void Initview () {Mprogressbar = (horizontalprogressbarwithnumber) Findviewbyid (R.id.id_progressbar); MProgressBar1 = (horizontalprogressbarwithnumber) Findviewbyid (R.ID.ID_PROGRESSBAR1); Btn_pause_continue = (Button) Findviewbyid (r.id.btn_pause_continue); Btn_pause_continue.setonclicklistener (New Onclicklistener () {////@Override// public void OnClick (View v) {/////TODO auto-generated method Stub// Fileasynchttpresponsehandler.sendretrymessage (0); // } // }); Final String url = "http://dl.wandoujia.com/files/phoenix/latest/wandoujia-wandoujia_web.apk?timestamp= 1409388568830 "; Final String MD5 = ""; Final String Dirpath = "study/download/"; Final String fileName = "Pea pod apk"; Btndownload = (Button) Findviewbyid (r.id.btn_download); try {Btndownload.setonclicklistener () {new Onclicklistener () {@Override Pub LIC void OnClick (View v) {baseskinapplication.shared (). GETDM (). Setdownloadwifionly (FA LSE); Baseskinapplication.shared (). GETDM (). Download (testdownloadactivity.this, URL, MD5, Dirpath, FileName, new Downloadlistener () {@Override public void OnStart () { Btndownload.setvisibility (View.gone); Btncancel.setvisibility (view.visible); } @Override public void OnError (String errmessage) { } @Override public void Onsuccess () {} @Override public void OnProgress (int progress) {Mprogressbar. SetpRogress (progress); } }); } }); } catch (Exception e) {e.printstacktrace (); } final String url1 = "http://msoftdl.360.cn/mobilesafe/shouji360/360safesis/360MobileSafe.apk"; Final String md51 = ""; Final String dirPath1 = "study/download/"; Final String fileName1 = "360.apk"; BtnDownload1 = (Button) Findviewbyid (R.ID.BTN_DOWNLOAD1); try {Btndownload1.setonclicklistener () {new Onclicklistener () {@Override public vo ID OnClick (View v) {baseskinapplication.shared (). GETDM (). Setdownloadwifionly (false); Baseskinapplication.shared (). GETDM (). Download (Testdownloadactivity.this, URL1, Md51, DirPath1, FileName1, New Downloadlistener () {@Override public void OnStart () { Btndownload1.setvisibility (VIEW.Gone); Btncancel1.setvisibility (view.visible); } @Override public void OnError (String errmessage) { } @Override public void Onsuccess () {} @Override public void OnProgress (int progress) {MPROGRESSBAR1 . setprogress (progress); } }); } }); } catch (Exception e) {e.printstacktrace (); } btncancel = (Button) Findviewbyid (r.id.btn_cancel); Btncancel.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { Baseskinapplication.shared (). GETDM (). Canceldownload (testdownloadactivity.this, URL); Btndownload.setvisibility (view.visible); Btncancel.Setvisibility (View.gone); } }); BtnCancel1 = (Button) Findviewbyid (R.ID.BTN_CANCEL1); Btncancel1.setonclicklistener (New Onclicklistener () {@Override public void OnClick (View v) { Baseskinapplication.shared (). GETDM (). Canceldownload (Testdownloadactivity.this, URL1); Btndownload1.setvisibility (view.visible); Btncancel1.setvisibility (View.gone); } }); }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Development Step by Step 67: Use Android Open source project android-async-http asynchronous download file