How to implement automatic software updates, the following are specific examples:
Effect Chart:
Specific steps:
1. xml files used to deploy updates on the server: Version.xml
<update>
<version>2</version>
<name>baiduxinwen.apk</name>
<url >http://gdown.baidu.com/data/wisegame/e5f5c3b8e59401c8/baiduxinwen.apk</url>
</update>
2. Implement the update operation on the client
Involves three technologies:
Resolution of 1.xml files
2.HttpURLConnection Connection
3. File stream I/O
This creates a service class that parses the XML file: Parxmlservice.java
Package com.xiaowu.news.update;
Import Java.io.InputStream;
Import Java.util.HashMap;
Import Javax.xml.parsers.DocumentBuilder;
Import Javax.xml.parsers.DocumentBuilderFactory;
Import org.w3c.dom.Document;
Import org.w3c.dom.Element;
Import Org.w3c.dom.Node;
Import org.w3c.dom.NodeList; public class Parsexmlservice {public hashmap<string, string> parsexml (InputStream instream) throws exception{Ha
shmap<string, string> hashMap = new hashmap<string, string> ();
Creates a documentbuilderfactory that will create the Documentbuilder.
Documentbuilderfactory factory = Documentbuilderfactory.newinstance ();
Creating Documentbuilder,documentbuilder will actually parse to create the Document object Documentbuilder Builder = Factory.newdocumentbuilder ();
Resolves the file to create a Document Object document = Builder.parse (instream);
Gets the XML file root node Element root = Document.getdocumentelement ();
Get all child nodes nodelist childnodes = Root.getchildnodes (); for (int i = 0; i < childnodes.getlength (); i++) {Node Childnode = (node) childnoDes.item (i);
if (childnode.getnodetype () = = Node.element_node) {element childelement = (element) Childnode; The version number if ("Version". Equals (Childelement.getnodename ())) {Hashmap.put ("version", Childelement.getfirstchild ().
Getnodevalue ()); Software name} else if ("name". Equals (Childelement.getnodename ()) {hashmap.put ("name"), Childelement.getfirstchild (). Getno
Devalue ()); Download Address} else if ("url". Equals (Childelement.getnodename ())) {hashmap.put ("url", Childelement.getfirstchild (). GetNode
Value ());
}} return hashMap;
}
}
Administrative class that implements the update operation: Updatemanager.java
Package com.xiaowu.news.update;
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.util.HashMap;
Import javax.net.ssl.HttpsURLConnection;
Import Android.app.AlertDialog;
Import Android.app.AlertDialog.Builder;
Import Android.app.Dialog;
Import Android.content.Context;
Import Android.content.DialogInterface;
Import android.content.Intent;
Import Android.content.DialogInterface.OnClickListener;
Import android.content.pm.PackageManager.NameNotFoundException;
Import Android.net.Uri;
Import android.os.Environment;
Import Android.os.Handler;
Import Android.view.LayoutInflater;
Import Android.view.View;
Import Android.widget.ProgressBar;
Import Android.widget.Toast;
Import COM.XIAOWU.NEWS.R; /** * * @author WWJ * @date 2012/11/17 * Implementation of the Software update management class/public class Updatemanager {//download ... private static FINA l INT DownloAD = 1;
Download complete private static final int download_finish = 2;
Save parsed XML Information hashmap<string, string> Mhashmap;
Download save path private String Msavepath;
Record progress bar Quantity private int progress;
Whether to cancel updating private Boolean cancelupdate = false;
Contextual object private context Mcontext;
Progress bar Private ProgressBar Mprogressbar;
Update dialog box for progress bar private Dialog mdownloaddialog; Private Handler Mhandler = new Handler () {public void Handlemessage (android.os.Message msg) {switch (msg.what) {//download
In ...
Case DOWNLOAD://Update progress bar System.out.println (progress);
Mprogressbar.setprogress (progress);
Break
Download Complete Case download_finish://Installation file installapk ();
Break
}
};
};
Public Updatemanager {super ();
This.mcontext = context;
/** * Detection software update/public void Checkupdate () {if (Isupdate ()) {//Display prompt dialog Shownoticedialog ();
else {toast.maketext (Mcontext, R.string.soft_update_no, Toast.length_short). Show (); }} private void Shownoticedialog () {//TODO auto-generated Method Stub//Construct dialog box Alertdialog.builder Builder = new Builder (mcontext);
Builder.settitle (R.string.soft_update_title);
Builder.setmessage (R.string.soft_update_info); Update Builder.setpositivebutton (R.STRING.SOFT_UPDATE_UPDATEBTN, New Onclicklistener () {@Override public void oncli
CK (dialoginterface dialog, int which) {//TODO auto-generated Method Stub Dialog.dismiss ();
Display Download dialog box Showdownloaddialog ();
}
}); Later update Builder.setnegativebutton (R.string.soft_update_later, New Onclicklistener () {@Override public void onclic
K (dialoginterface Dialog, int which) {//TODO auto-generated Method Stub Dialog.dismiss ();
}
});
Dialog Noticedialog = Builder.create ();
Noticedialog.show ();
private void Showdownloaddialog () {//Construct software Download dialog box Alertdialog.builder Builder = new Builder (mcontext);
Builder.settitle (r.string.soft_updating);
Add progress bar to download dialog box final Layoutinflater inflater = Layoutinflater.from (Mcontext); View view =Inflater.inflate (r.layout.softupdate_progress, NULL);
Mprogressbar = (ProgressBar) View.findviewbyid (r.id.update_progress);
Builder.setview (view); Builder.setnegativebutton (R.string.soft_update_cancel, New Onclicklistener () {@Override public void OnClick (Dialog
Interface dialog, int which) {//TODO auto-generated Method Stub Dialog.dismiss ();
Set Cancel state CancelUpdate = true;
}
});
Mdownloaddialog = Builder.create ();
Mdownloaddialog.show ();
Download file downloadapk (); /** * Download apk file */private void downloadapk () {//TODO auto-generated Method Stub//start new thread download software
Read (). Start (); /** * Check whether the software has an updated version * @return/public boolean isupdate () {//Get the current software version int versioncode = Getversioncode (Mcontex
T); Put the version.xml on the network and get the file information InputStream instream = ParseXmlService.class.getClassLoader (). getResourceAsStream ("
Version.xml "); Parse the XML file.
Because the XML file is relatively small, the DOM method is used to parse parsexmlservice service = new Parsexmlservice (); try {mhashmap = Service. Parsexml (instream);
catch (Exception e) {//Todo:handle Exception e.printstacktrace ();
} if (null!= mhashmap) {int servicecode = integer.valueof (Mhashmap.get ("version"));
Version judgment if (Servicecode > Versioncode) {return true;
return false; /** * Get software version number * @param context * @return/private int Getversioncode (context) {//TODO auto-generated
Method Stub int versioncode = 0;
Gets the software version number, corresponding to the Androidmanifest.xml under Android:versioncode try {versioncode = Context.getpackagemanager (). Getpackageinfo (
"Com.xiaowu.news", 0). Versioncode;
catch (Namenotfoundexception e) {//TODO auto-generated catch block E.printstacktrace ();
return versioncode; /** * Download File thread * @author Administrator */private class Downloadapkthread extends thread {@Override public vo ID run () {try {///determine if the SD card exists and has read and write permission if (environment.getexternalstoragestate). Equals (environment.media_mounted ) {//Get sdcard path String Sdpath = EnvIronment.getexternalstoragedirectory () + "/";
Msavepath = Sdpath + "Download";
URL url = new URL (mhashmap.get ("url"));
Create connection HttpURLConnection conn = (httpurlconnection) url.openconnection ();
Conn.connect ();
Gets the file size int length = Conn.getcontentlength ();
Create an input stream inputstream is = Conn.getinputstream ();
File File = new file (Msavepath);
If the file does not exist, create a new directory if (!file.exists ()) {File.mkdir ();
File Apkfile = new file (Msavepath, Mhashmap.get ("name"));
FileOutputStream fos = new FileOutputStream (apkfile);
int count = 0;
Cache byte buf[] = new byte[1024];
Write to the file do {int numread = Is.read (BUF);
Count + = Numread;
Calculates the position of the progress bar progress = (int) ((float) count/length) * 100);
Update Progress Mhandler.sendemptymessage (DOWNLOAD);
if (numread <= 0) {//Download complete mhandler.sendemptymessage (download_finish);
Break
}//Write file Fos.write (buf, 0, Numread);
while (!cancelupdate)//Click Cancel to stop downloading Fos.close ();
Is.close ();
} catch (Malformedurlexception e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
//Cancel Download dialog box display Mdownloaddialog.dismiss ();
}/** * Install apk file */private void installapk () {File Apkfile = new file (Msavepath, Mhashmap.get ("name"));
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);
}
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.