We should all have a similar experience, when an app needs to be updated, the entry screen will alert you if a new update is updated, there are a few steps
1 checking the current version first
2 determining the version in the server
3 If there is an update, click Update, download the installation package, and install it automatically after the download is complete.
How does the code implement it? Let's see it together.
/* * 获取当前程序的版本号 */ privategetVersionNamethrows Exception{ //获取packagemanager的实例 PackageManager packageManager = getPackageManager(); //getPackageName()是你当前类的包名,0代表是获取版本信息 0); return packInfo.versionName; }
Read Server version number
/* * Parse the XML file returned by the server with the Pull parser (XML encapsulates the version number) */ Public StaticUpdatainfoGetupdatainfo(InputStream is) throws exception{Xmlpullparser parser = Xml.newpullparser (); Parser.setinput ( is,"Utf-8");//Set the parsed data source intType = Parser.geteventtype (); Updatainfo info =NewUpdatainfo ();//entity while(Type! = xmlpullparser.end_document) {Switch(type) { CaseXmlpullparser.start_tag:if("Version". Equals (Parser.getname ())) {info.setversion (Parser.nexttext ());//Get version number}Else if("url". Equals (Parser.getname ())) {Info.seturl (Parser.nexttext ());//Get the APK file to be upgraded}Else if("description". Equals (Parser.getname ())) {info.setdescription (Parser.nexttext ());//Get information about this file} Break; } type = Parser.next (); }returnInfo }
Download
Public StaticFileGetfilefromserver(String path, ProgressDialog PD) throws exception{//If equal indicates that the current sdcard is mounted on the phone and is available if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {URL url =NewURL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout ( the);//Gets the size of the filePd.setmax (Conn.getcontentlength ()); InputStream is= Conn.getinputstream (); File File =NewFile (Environment.getexternalstoragedirectory (),"updata.apk"); FileOutputStream fos =NewFileOutputStream (file); Bufferedinputstream bis =NewBufferedinputstream ( is);byte[] buffer =New byte[1024x768];intLen;intTotal=0; while(Len =bis.read (buffer))!=-1) {fos.write (buffer,0, Len); total+= Len;//Get current Download volumePd.setprogress (total); } fos.close (); Bis.close (); is. Close ();returnFile }Else{return NULL; } }
Version matching, automatic installation
/ * * Get XML parsing from the server and compare version number */ Public class checkversiontask implements Runnable{ Public void Run() {Try{//Get the server address from the resource fileString path = Getresources (). getString (R.string.serverurl);//object wrapped as a URLURL url =NewURL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout ( the); InputStream is =conn.getinputstream (); info = Updatainfoparser.getupdatainfo (IS);if(Info.getversion (). Equals (Versionname)) {LOG.I (TAG,"version number same without upgrade"); Loginmain (); }Else{LOG.I (TAG,"The version number is different, prompting the user to upgrade"); Message msg =NewMessage (); Msg.what = updata_client; Handler.sendmessage (msg); } }Catch(Exception e) {//Pending processingMessage msg =NewMessage (); Msg.what = Get_undatainfo_error; Handler.sendmessage (msg); E.printstacktrace (); }}} Handler Handler =NewHandler () {@Override Public void Handlemessage(Message msg) {//TODO auto-generated method stub Super. Handlemessage (msg);Switch(msg.what) { CaseUpdata_client://dialog box notifies the user to upgrade the programShowupdatadialog (); Break; CaseGet_undatainfo_error://server timed outToast.maketext (Getapplicationcontext (),"failed to get server update information",1). Show (); Loginmain (); Break; CaseDown_error://Download apk failedToast.maketext (Getapplicationcontext (),"Download new version failed",1). Show (); Loginmain (); Break; } } };/* * * Pop-up dialog to notify users of updates * * Popup dialog box steps: * 1. Create Alertdialog Builder. * 2. To set properties for Builder, dialog box contents, Style, Button * 3. Create a dialog box with Builder * 4. dialog box Show () out */ protected void Showupdatadialog() {Alertdialog.builder Builer =NewBuilder ( This) ; Builer.settitle ("Version Upgrade"); Builer.setmessage (Info.getdescription ());//When the Click OK button downloads the new apk from the server and installsBuiler.setpositivebutton ("OK",NewOnclicklistener () { Public void OnClick(Dialoginterface Dialog,intwhich) {log.i (TAG,"Download apk, update"); DOWNLOADAPK (); } });//Sign in when the Cancel button is clickedBuiler.setnegativebutton ("Cancel",NewOnclicklistener () { Public void OnClick(Dialoginterface Dialog,intwhich) {//TODO auto-generated method stubLoginmain (); } }); Alertdialog dialog = Builer.create (); Dialog.show (); }/ * * Download APK from the server * / protected void downloadapk() {FinalProgressDialog PD;//Progress bar dialog boxPD =NewProgressDialog ( This); Pd.setprogressstyle (progressdialog.style_horizontal); Pd.setmessage ("Downloading Updates"); Pd.show ();NewThread () {@Override Public void Run() {Try{File File = Downloadmanager.getfilefromserver (Info.geturl (), PD); Sleep the); installapk (file); Pd.dismiss ();//Close the Progress Bar dialog box}Catch(Exception e) {Message msg =NewMessage (); Msg.what = Down_error; Handler.sendmessage (msg); E.printstacktrace (); }}}.start (); }//install APK protected void installapk(File file) {Intent Intent =NewIntent ();//Perform actionsIntent.setaction (Intent.action_view);//type of data executedIntent.setdataandtype (uri.fromfile (file),"Application/vnd.android.package-archive"); StartActivity (Intent); }/ * * Enter the main interface of the program */ Private void Loginmain() {Intent Intent =NewIntent ( This, Mainactivity.class); StartActivity (Intent);//End the current activity This. Finish (); }
Related classes
Public classUpdatainfo {PrivateString version;PrivateString URL;PrivateString description; PublicStringgetversion() {returnVersion } Public void setversion(String version) { This. Version = version; } PublicStringGETURL() {returnUrl } Public void SetUrl(String URL) { This. url = URL; } PublicStringgetdescription() {returnDescription } Public void setdescription(String description) { This. Description = description; }}
Related layouts
<?xml version="1.0" encoding="utf-8"?><info> <version>2.0</version> <url>http://192.168.0.64:8080/mobilesafe.apk</url> <description>检测到最新版本,请及时更新!</description></info>
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Android Version detection upgrade