Directly paste the Code:
Config class:
Package COM. tutor. config; import Org. JSON. jsonarray; import Org. JSON. jsonobject; import COM. tutor. update. r; import android. content. context; import android. content. PM. packageinfo; import android. content. PM. packagemanager; import android. content. PM. packagemanager. namenotfoundexception; import android. util. log; public class config {Public String update_server = "http: // 10.81.48.181: 8080/update/"; Public String u Pdate_apkname = ""; Public String update_savename = "update.apk"; Public String update_verjson = "ver. JSON "; public static int newvercode; public static string newvername;/*** get the current version ** @ Param context * @ return */Public int getvercode (context) {int vercode =-1; try {// obtain packagemanager's instance packagemanager = context. getpackagemanager (); // getpackagename () is the package name of your current class. 0 indicates obtaining the version information packagei Nfo packinfo = packagemanager. getpackageinfo (context. getpackagename (), 0); vercode = packinfo. versioncode; // vercode = // context. getpackagemanager (). getpackageinfo (// "com. example. update ", 0 ). versioncode; system. out. println ("nowcode ---? >>> "+ Vercode);} catch (namenotfoundexception e) {log. E ("RG", E. getmessage ();} return vercode;}/*** get version name ** @ Param context * @ return */Public String getvername (context) {string vername = ""; try {// obtain the packagemanager instance packagemanager = context. getpackagemanager (); // getpackagename () is the package name of your current class. 0 indicates obtaining the packageinfo packinfo = packagemanager. getpackageinfo (context. getpackagename (), 0); vername = packinfo. versionname; // vername = // context. getpackagemanager (). getpackageinfo (// "com. example. update ", 0 ). versionname;} catch (namenotfoundexception e) {log. E ("RG", E. getmessage ();} return vername;} // public static string getvername (context) // {// string vername = // context. getresources (). gettext (R. string. app_versionname )//. tostring (); // return vername; //} public static string getappname (context) {string vername = context. getresources (). gettext (R. string. app_name ). tostring (); Return vername;}/*** check the server version ** @ return */Public Boolean getserververcode () {try {string verjson = networktool. getcontent (update_server + update_verjson); system. out. println ("verjson --- >>>" + verjson); jsonarray array = new jsonarray (verjson); If (array. length ()> 0) {jsonobject OBJ = array. getjsonobject (0); try {newvercode = integer. parseint (obj. getstring ("vercode"); newvername = obj. getstring ("vername"); system. out. println ("newvercode --- >>>" + newvercode); system. out. println ("newvername --- >>>" + newvername);} catch (exception e) {newvercode =-1; newvername = ""; return false ;}}} catch (exception e) {log. E ("RG", E. getmessage (); Return false;} return true ;}}
Networktool class:
package com.tutor.config;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class NetworkTool{public static String getContent(String filename){URL url;String str;try{url = new URL(filename);HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.connect();int len = conn.getContentLength();InputStream is = conn.getInputStream();byte[] by = new byte[len];is.read(by);str = new String(by, "UTF-8");return str;}catch (MalformedURLException e){// TODO Auto-generated catch blocke.printStackTrace();return "";}catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();return "";}}}
Updateapplication class:
Package COM. tutor. config; import android. content. context; public class updateapplication {/*** check the Update Status ** @ Param context * @ return */public static Boolean getupdateinfo (context) {config COF = new config (); COF. getserververcode (); If (COF. getvercode (context) <config. newvercode) {return true;} else {return false;}/*** update immediately ** @ Param context */public static void newupdate (context) {updatemanager mupdatemanager = new updatemanager (context); mupdatemanager. checkupdateinfo ();}}
Updatemanager class:
Package COM. tutor. config; 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 COM. tutor. update. r; import android. app. alertdialog; import android. app. dialog; import android. app. alertdialog. builder; import android. content. context; import android. content. di Aloginterface; import android. content. intent; import android. content. dialoginterface. onclicklistener; import android.net. uri; import android. OS. handler; import android. OS. message; import android. view. layoutinflater; import android. view. view; import android. widget. progressbar; public class updatemanager {private context mcontext; // prompt private string updatemsg = "you have the latest software package. Download it now ~ "; // Returned installation package urlprivate string apkurl =" http: // 10.81.48.181: 8080/update/updatedemo.apk "; private dialog noticedialog; private dialog downloaddialog; /* download package installation path */Private Static final string savepath = "/sdcard/updatedemo/"; Private Static final string savefilename = savepath + "updatedemorelease.apk "; /* progress bar and handler and MSG constant for notifying UI refreshing */private progressbar mprogress; Private Static final int down_update = 1; priv Ate static final int down_over = 2; private int progress; private thread downloadthread; private Boolean interceptflag = false; private handler mhandler = new handler () {public void handlemessage (Message MSG) {Switch (MSG. what) {Case down_update: mprogress. setprogress (Progress); break; Case down_over: installapk (); break; default: Break ;};}; public updatemanager (context) {This. mcontext = context;} // external interface Let the main activity call Public void checkupdateinfo () {shownoticedialog ();} private void shownoticedialog () {alertdialog. builder = new Builder (mcontext); builder. settitle ("Software Version Update"); builder. setmessage (updatemsg); builder. setpositivebutton ("Download", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss (); showdownloaddialog () ;}}); builder. setnegativebutton ("later", new Onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss () ;}}); noticedialog = builder. create (); noticedialog. show ();} private void showdownloaddialog () {alertdialog. builder = new Builder (mcontext); builder. settitle ("Software Version Update"); Final layoutinflater Inflater = layoutinflater. from (mcontext); view v = Inflater. inflate (R. layout. progress, null); mprogress = (Prog Ressbar) v. findviewbyid (R. id. progress); builder. setview (V); builder. setnegativebutton ("cancel", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss (); interceptflag = true ;}}); downloaddialog = builder. create (); downloaddialog. show (); downloadapk ();} private runnable mdownapkrunnable = new runnable () {@ overridepublic void run () {try {URL url = new URL (apkurl); htT Purlconnection conn = (httpurlconnection) URL. openconnection (); Conn. connect (); int length = Conn. getcontentlength (); inputstream is = Conn. getinputstream (); file = new file (savepath); If (! File. exists () {file. mkdir ();} string apkfile = savefilename; file apkfile = new file (apkfile); fileoutputstream Fos = new fileoutputstream (apkfile); int COUNT = 0; byte Buf [] = new byte [24]; do {int numread = is. read (BUF); count + = numread; Progress = (INT) (float) count/length) * 100); // Update Progress mhandler. sendemptymessage (down_update); If (numread <= 0) {// install mhandler after the download is complete. sendemptymessage (down_over); break ;} FOS. Write (BUF, 0, numread);} while (! Interceptflag); // click Cancel to stop the download. FOS. close (); is. close ();} catch (malformedurlexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}};/*** download APK *** @ Param URL */private void downloadapk () {downloadthread = new thread (mdownapkrunnable); downloadthread. start ();}/*** install APK ** @ Param URL */private void installapk () {If (downloaddialog. isshowing () {downloaddialog. dismiss ();} file apkfil E = new file (savefilename); 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 );}}
Mainacitivity:
Package COM. tutor. update; import COM. tutor. config. updateapplication; import android. app. activity; import android. OS. bundle; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. toast; public class mainacitivity extends activity {@ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layou T. main); button bt = (button) findviewbyid (R. id. button1); BT. setonclicklistener (New onclicklistener () {@ overridepublic void onclick (view v) {If (updateapplication. getupdateinfo (mainaciti.pdf. this) {updateapplication. newupdate (mainacitivity. this);} else {toast. maketext (mainaciti.pdf. this, "the program is in the latest state! Thank you for using ", Toast. length_short). Show ();}}});}}