The example described in this article is the Android code for a weather report, which includes downloading and installing APK, checking apk updates, displaying ' already up-to-date ' or ' unable to get version Information ' dialog box, getting current client version information, displaying the Version Update Notification dialog box, displaying the Download dialog box, Determine whether to mount the SD card, display file size format: 2 decimal point display, and so on. The specific implementation code is as follows:
Import Java.io.ByteArrayInputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;
Import java.net.MalformedURLException;
Import Java.net.URL;
Import Java.text.DecimalFormat;
Import org.apache.http.HttpEntity;
Import Org.apache.http.HttpResponse;
Import Org.apache.http.client.methods.HttpGet;
Import org.apache.http.conn.ConnectTimeoutException;
Import org.apache.http.impl.client.DefaultHttpClient;
Import Org.apache.http.params.CoreConnectionPNames;
Import Org.apache.http.util.EntityUtils;
Import ORG.LMW.WEATHER.R;
Import Org.lmw.weather.entity.AppDetail;
Import Android.app.AlertDialog;
Import Android.app.Dialog;
Import Android.app.ProgressDialog;
Import Android.app.AlertDialog.Builder;
Import Android.content.Context;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.content.DialogInterface.OnCancelListener; Import Android.content.DialogInterface.OnClicKlistener;
Import Android.content.pm.PackageInfo;
Import android.content.pm.PackageManager.NameNotFoundException;
Import Android.net.Uri;
Import android.os.Environment;
Import Android.os.Handler;
Import Android.os.Message;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.widget.ProgressBar;
Import Android.widget.TextView;
Import Android.widget.Toast;
public class Downloadmanager {private static final int down_nosdcard = 0;
private static final int down_update = 1;
private static final int down_over = 2;
private static final int down_error=3;
private static final int dialog_type_latest = 0;
private static final int dialog_type_fail = 1;
private static final int dialog_type_interneterror = 2;
private static Downloadmanager Downloadmanager;
Private context Mcontext;
Notification dialog box private Dialog noticedialog;
Download dialog box private Dialog downloaddialog;
Progress bar Private ProgressBar mprogress;
Show download values private TextView mprogresstext; //Query animation private ProgressDialog Mprodialog;
' is already up to date ' or ' Can't get the latest Version ' dialog box private Dialog latestorfaildialog;
The installation package URL is returned private String Apkurl = "";
Progress value private int progress;
Download thread private thread downloadthread;
Terminate token private Boolean interceptflag;
Hint language private String updatemsg = "";
Download package save path Private String Savepath = "";
APK save full path private String Apkfilepath = "";
Temporary download file path private String Tmpfilepath = "";
Download file size private String apkfilesize;
Downloaded file size private String tmpfilesize;
Private String Curversionname = "";
private int curversioncode;
Private Appdetail mdownload; Private String checkurl= "Http://192.168.0.133:8080/lmw/androidMarket/SimpleWeather-20130701093349937/update.xml"
; Private Handler Mhandler = new Handler () {public void Handlemessage (msg) {switch (msg.what) {case Down_u
PDATE:mProgress.setProgress (progress);
Mprogresstext.settext (tmpfilesize + "/" + apkfilesize);
Break Case DOWN_OVER:downloadDialog.dismiss ();
INSTALLAPK ();
Break
Case DOWN_NOSDCARD:downloadDialog.dismiss ();
Toast.maketext (Mcontext, "Cannot download the installation file, please check the SD card is mounted", toast.length_short). Show ();
Break
Case DOWN_ERROR:downloadDialog.dismiss ();
if (msg.arg1==0) {Toast.maketext (Mcontext, "Network does not give force ah", Toast.length_short). Show (); }else if (msg.arg1==1| |
msg.arg1==2) {Toast.maketext (Mcontext, "Resource not Found", Toast.length_short). Show ();
} break;
}
};
}; public static Downloadmanager Getdownloadmanager () {if (Downloadmanager = null) {Downloadmanager = new Downloadmana
GER ();
} Downloadmanager.interceptflag = false;
return downloadmanager;
public void downloader (context context, Appdetail download) {this.mcontext = context;
this.mdownload = download;
Showdownloaddialog (); /** * Check App update * @param context * @param isshowmsg * Whether to display prompt message/public void Checkappupdate (context Co
ntext, Final Boolean isshowmsg,final Boolean notmain) {this.mcontext = context; GeTcurrentversion (Mcontext);
if (isshowmsg) {if (Mprodialog = = null) Mprodialog = progressdialog.show (Mcontext, NULL, "Being instrumented, please later ...", true, true); else if (mprodialog.isshowing () | |
(Latestorfaildialog!= null && latestorfaildialog.isshowing ()))
Return Final Handler Handler = new Handler () {public void Handlemessage (msg) {//Progress Bar dialog box does not display-detection results do not display if (Mprod
Ialog!= null &&!mprodialog.isshowing ()) {return;
//Close and release the Release progress bar dialog box if (isshowmsg && mprodialog!= null) {Mprodialog.dismiss ();
Mprodialog = null;
//Display detection results if (Msg.what = 1) {mdownload = (appdetail) msg.obj; if (mdownload!= null) {if (Curversioncode < Mdownload.getversioncode ()) {Apkurl = Mdownload.geturi () +mdownload
. GetFileName ();
Updatemsg = Mdownload.getapphistory ();
Shownoticedialog ();
else if (isshowmsg) {if (Notmain) {showlatestorfaildialog (dialog_type_latest);
}}}else if (msg.what==-1&&isshowmsg) { Showlatestorfaildialog (Dialog_type_interneterror);
}else if (isshowmsg) {showlatestorfaildialog (dialog_type_fail);
}
}
};
New Thread () {public void run () {msg = new message ();
try {defaulthttpclient client = new Defaulthttpclient ();
Client.getparams (). Setparameter (Coreconnectionpnames.connection_timeout, 3000);
HttpGet get = new HttpGet (Checkurl);
HttpResponse response = Client.execute (get);
if (Response.getstatusline (). Getstatuscode () = = httpentity entity = response.getentity ();
InputStream stream = new Bytearrayinputstream (entityutils.tostring (Entity, "gb2312"). GetBytes ());
Appdetail update = Appdetail.parsexml (stream);
Msg.what = 1;
msg.obj = update;
}else{msg.what =-1;
} catch (Exception e) {e.printstacktrace ();
Msg.what =-1;
Handler.sendmessage (msg);
}}.start ();
/* display ' is already up to date ' or ' cannot get version Information ' dialog box/private void Showlatestorfaildialog (int dialogtype) {String toastmsg= ""; if (LatestorfaildiaLog!= null) {//close and Release the previous dialog box Latestorfaildialog.dismiss ();
Latestorfaildialog = null;
}//Alertdialog.builder Builder = new Builder (mcontext);
Builder.settitle ("system hint");
if (DialogType = = dialog_type_latest) {//Builder.setmessage ("You are currently the latest version");
Toastmsg= "You are currently the latest version";
else if (DialogType = = Dialog_type_fail) {//Builder.setmessage ("Cannot get version update information");
Toastmsg= "Cannot get version update information";
}else if (dialogtype==dialog_type_interneterror) {//Builder.setmessage ("Network failure, unable to connect to server");
toastmsg= "Network failure, unable to connect to the server";
} toast.maketext (Mcontext, Toastmsg, Toast.length_short). Show (); /* Get current Client version information//public String getcurrentversion (context context) {try {packageinfo info = Context.getpackagema
Nager (). Getpackageinfo (Context.getpackagename (), 0);
Curversionname = Info.versionname;
Curversioncode = Info.versioncode;
catch (Namenotfoundexception e) {e.printstacktrace (system.err);
return curversionname; /* Show version Update Notification dialog box/private void Shownoticedialog () {alertdialog.
Builder Builder = new Builder (mcontext);
Builder.settitle ("software version update");
Builder.setmessage (UPDATEMSG); Builder.setpositivebutton ("Update Now", new Onclicklistener () {@Override public void OnClick (dialoginterface dialog, int
which) {Dialog.dismiss ();
Showdownloaddialog ();
}
}); Builder.setnegativebutton ("Talk Later", New Onclicklistener () {@Override public void OnClick (dialoginterface dialog, int
which) {Dialog.dismiss ();
}
});
Noticedialog = Builder.create ();
Noticedialog.show ();
/* Show Download dialog box */private void Showdownloaddialog () {Alertdialog.builder Builder = new Builder (mcontext);
Builder.settitle ("Downloading installation package");
Final Layoutinflater inflater = Layoutinflater.from (Mcontext);
View v = inflater.inflate (r.layout.download_progress, NULL);
Mprogress = (ProgressBar) V.findviewbyid (r.id.update_progress);
Mprogresstext = (TextView) V.findviewbyid (R.id.update_progress_text);
Builder.setview (v);
Builder.setnegativebutton ("Cancel", new Onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {Dialog.dismiss ();
Interceptflag = true;
}
}); Builder.setoncancellistener (New Oncancellistener () {@Override public void OnCancel (Dialoginterface dialog) {Dialo
G.dismiss ();
Interceptflag = true;
}
});
Downloaddialog = Builder.create ();
Downloaddialog.setcanceledontouchoutside (FALSE);
Downloaddialog.show ();
DOWNLOADAPK ();
Private Runnable mdownapkrunnable = new Runnable () {message error_msg=new message ();
@Override public void Run () {try {String apkname = Mdownload.getfilename (). Replace (". apk", "") + ". apk";
String tmpapk = Mdownload.getfilename (). Replace (". apk", "") + ". tmp";
Determine if the SD card String storagestate = Environment.getexternalstoragestate () is mounted; if (Storagestate.equals (environment.media_mounted)) {Savepath = Environment.getexternalstoragedirectory ().
GetAbsolutePath () + "/qn/qnstore/";
File File = new file (Savepath);
if (!file.exists ()) {file.mkdirs (); } Apkfilepath = SAvepath + apkname;
Tmpfilepath = Savepath + tmpapk;
//No SD card mounted, unable to download file if (Apkfilepath = null | | apkfilepath = = "") {mhandler.sendemptymessage (Down_nosdcard);
Return
} File Apkfile = new file (Apkfilepath);
Whether the updated files//if (Apkfile.exists ()) {//Downloaddialog.dismiss ();//installapk ();//return////////Output temporary download file
File Tmpfile = new file (Tmpfilepath);
FileOutputStream fos = new FileOutputStream (tmpfile);
URL url = new URL (Mdownload.geturi () +mdownload.getfilename ());
HttpURLConnection conn = (httpurlconnection) url.openconnection ();
try {conn.connect ();
catch (Connecttimeoutexception e) {error_msg.what=down_error;
error_msg.arg1=0;
Mhandler.sendmessage (ERROR_MSG);
int length = Conn.getcontentlength ();
InputStream is = Conn.getinputstream ();
Display file size format: 2 decimal points display DecimalFormat df = new DecimalFormat ("0.00");
The total file size shown below the progress bar apkfilesize = Df.format ((float) length/1024/1024) + "MB";
int count = 0; byte buf[] = new byte[1024];
do {int numread = Is.read (BUF);
Count + = Numread;
The current download file size shown below the progress bar tmpfilesize = Df.format ((float) count/1024/1024) + "MB";
Current Progress value progress = (int) (((float) count/length) * 100);
Update Progress Mhandler.sendemptymessage (down_update); if (numread <= 0) {//Download complete-Convert temporary download file to apk file if (Tmpfile.renameto (apkfile)) {//Notify installation Mhandler.sendemptymes
Sage (down_over);
} break;
} fos.write (buf, 0, Numread);
while (!interceptflag),//Click Cancel to stop downloading Fos.close ();
Is.close ();
catch (Malformedurlexception e) {error_msg.what=down_error;
Error_msg.arg1=1;
Mhandler.sendmessage (ERROR_MSG);
E.printstacktrace ();
catch (IOException e) {error_msg.what=down_error;
error_msg.arg1=2;
Mhandler.sendmessage (ERROR_MSG);
E.printstacktrace ();
}
}
};
/** * Download apk * @param url/private void downloadapk () {downloadthread = new Thread (mdownapkrunnable);
Downloadthread.start (); /** * Install apk * @param URL/Private void installapk () {File Apkfile = new file (Apkfilepath);
if (!apkfile.exists ()) {return;
} Intent i = new Intent (Intent.action_view);
I.setdataandtype (Uri.parse ("file://" + apkfile.tostring ()), "application/vnd.android.package-archive");
Mcontext.startactivity (i);
}
}