Check and update the APK version (server and client)

Source: Internet
Author: User

I. First, let's take a look at the steps.

1. Obtain the current APK version.

2. Go to the server to obtain the latest version.

3. After comparison, decide whether to update.

4. Update and download the APK on the server.

5. Save the downloaded file to the SD card and install the APK

2. The client code is as follows:


Package COM. zhenshi. updataapk; import Java. io. file; import COM. zhenshi. util. httpconnect; import COM. zhenshi. util. toastutil; import android. app. activity; import android. app. alertdialog; import android. app. dialog; import android. app. progressdialog; import android. content. context; import android. content. dialoginterface; import android. content. intent; import android. content. PM. packagemanager. namenotfoundexception; Import android.net. uri; import android. OS. bundle; import android. OS. handler;/*** Class Name: testupdataactivity <br> * class description: <br> * PS: <br> ** @ Version 1.00 2012-4-5 4-5 * @ author zhenshi) peijiangping */public class testupdataactivity extends activity {private string packagename; private progressdialog pbar; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstan Cestate); setcontentview (R. layout. main); yesornoupdataapk ();}/*** role: whether to update the version <br> * Date: 2012-4-5 4-5 <br> ** @ author zhenshi) peijiangping */private int yesornoupdataapk () {packagename = This. getpackagename (); string nowversion = getvercode (testupdataactivity. this); string newversion = gotochecknewversion (); If (newversion. equals ("error") {return 0;} If (double. valueof (newversion)> double. valueof (nowvers Ion) {donewversionupdate (nowversion, newversion);} return 1;}/*** role: whether to update the prompt box <br> * Date: 2012-4-5 4-5 <br> ** @ author zhenshi) peijiangping */private void donewversionupdate (string nowversion, string newversion) {stringbuffer sb = new stringbuffer (); sb. append ("current version:"); sb. append (nowversion); sb. append (", new version found:"); sb. append (newversion); sb. append (", update? "); Dialog = new alertdialog. builder (testupdataactivity. this ). settitle ("Software Update "). setmessage (sb. tostring () // sets the content. setpositivebutton ("Update", // set the OK button new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {pbar = new progressdialog (testupdataactivity. this); pbar. settitle ("downloading"); pbar. setmessage ("Please wait... "); // pbar. setprogressstyle (progressdialog. style_spi Nner); pbar. show (); gotodownloadapk ();}}). setnegativebutton ("not updated now", new dialoginterface. onclicklistener () {public void onclick (dialoginterface Diener, int whichbutton) {// click the "cancel" button and exit the program finish ();}}). create (); // create // display the dialog box dialog. show ();}/*** role: Enable the download APK thread <br> * Date: 2012-4-6 <br> ** @ author zhenshi) peijiangping */private void gotodownloadapk () {New thread (New downloadapkthread (handler )). start ();} pub LIC handler = new handler () {public void handlemessage (Android. OS. message MSG) {super. handlemessage (MSG); If (MSG. what = 1) {toastutil = new toastutil (testupdataactivity. this); toastutil. showdefulttoast ("Download successful !! "). Show (); intent = new intent (intent. action_view); intent. setdataandtype (URI. fromfile (new file ("/sdcard/update/", "updata.apk"), "application/vnd. android. package-Archive "); startactivity (intent);} else {toastutil = new toastutil (testupdataactivity. this); toastutil. showdefulttoast ("Download failed !! "). Show ();} pbar. cancel () ;};/*** role: Get the latest application version <br> * Date: 2012-4-5 <br> ** @ author zhenshi) peijiangping */private string gotochecknewversion () {system. out. println ("gotochecknewversion"); string newversion = NULL; final string url = "http: // 192.168.1.41: 8080/testhttpservlet/getversionservlet"; httpconnect Hc = new httpconnect (URL, this); newversion = HC. getdataasstring (null); If (newversion. equals ("error") {return "error";} return newversion;}/*** role: Get the current program version <br> * Date: 2012-4-5 4-5 <br> ** @ author zhenshi) peijiangping */private string getvercode (context) {int vercode = 0; string vername = NULL; try {vercode = context. getpackagemanager (). getpackageinfo (packagename, 0 ). versioncode; vername = context. getpackagemanager (). getpackageinfo (packagename, 0 ). versionname;} catch (namenotfoundexception e) {system. out. println ("no");} system. out. println ("vercode" + vercode + "=" + "vername" + vername); Return vername ;}}

Package COM. zhenshi. updataapk; import COM. zhenshi. util. httpdownload; import android. OS. handler; import android. OS. message;/*** Class Name: downloadapkthread <br> * class description: Download APK thread <br> * PS: <br> ** @ Version 1.00 2012-4-5 4-5 * @ author zhenshi) peijiangping */public class downloadapkthread implements runnable {private handler; Private Static final string url = "http: // 192.168.1.41: 8080/testhttpservlet/APK/testupdata.apk "; Private Static final string filename =" updata.apk "; Private Static final string Path ="/sdcard/update "; Public downloadapkthread (handler) {This. handler = handler;} @ overridepublic void run () {system. out. println ("Download thread enabled"); message = new message (); message. what = httpdownload. downloadfile (URL, filename, PATH); handler. sendmessage (Message );}}

Package COM. zhenshi. util; import Java. io. ioexception; import Java. io. inputstream; import Java. util. list; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. param S. basichttpparams; import Org. apache. HTTP. params. httpconnectionparams; import Org. apache. HTTP. params. httpparams; import Org. apache. HTTP. protocol. HTTP; import Org. apache. HTTP. uticd. entityutils; import android. content. context; import android. util. log;/*** Class Name: httpconnect <br> * class description: http request tool class <br> * PS: <br> ** @ Version 1.00 2011/09/21 * @ author codyy) peijiangping */public class httpcon Nect {/*** address of the accessed Web Server */private string URL; private httppost httprequest; private httpresponse; private httpparams; private httpclient; Public httpconnect (string URL, context context) {This. url = URL; httpparams = new basichttpparams (); httpconnectionparams. setconnectiontimeout (httpparams, 15000); httpconnectionparams. setsotimeout (httpparams, 15000); httpclient = new de Faulthttpclient (httpparams);}/*** role: gets the returned value through an HTTP request (inputstream) <br> * Date: 2012-2-10 <br> ** @ author codyy) peijiangping */Public inputstream getdataasinputstream (list <namevaluepair> Params) {inputstream result = NULL; try {httprequest = new httppost (URL); If (Params! = NULL) {httprequest. setentity (New urlencodedformentity (Params, HTTP. utf_8);} httpresponse = httpclient.exe cute (httprequest); If (200 = httpresponse. getstatusline (). getstatuscode () {result = httpresponse. getentity (). getcontent () ;}} catch (ioexception e) {log. E ("nimeimei", E. getmessage (), e); return result;}/*** role: Get the return value (string) through an HTTP request. An error is returned. <br> * Date: 2012-2-10 <br> ** @ auth Or codyy) peijiangping */Public String getdataasstring (list <namevaluepair> Params) {string result = NULL; try {httprequest = new httppost (URL); If (Params! = NULL) {httprequest. setentity (New urlencodedformentity (Params, HTTP. utf_8);} httpresponse = httpclient.exe cute (httprequest); If (200 = httpresponse. getstatusline (). getstatuscode () {result = entityutils. tostring (httpresponse. getentity (); system. out. println ("Return Value" + result);} catch (ioexception e) {e. printstacktrace (); Return "error";} return result;}/*** role: Get the return value (INT) through the HTTP request. If the request fails,-1 is returned, data returned successfully <br> * Date: 2012-2-10 <br> ** @ author codyy) peijiangping */Public int getdataasint (list <namevaluepair> Params) {int result =-1; try {httprequest = new httppost (URL); If (Params! = NULL) {httprequest. setentity (New urlencodedformentity (Params, HTTP. utf_8);} httpresponse = httpclient.exe cute (httprequest); If (200 = httpresponse. getstatusline (). getstatuscode () {result = integer. parseint (entityutils. tostring (httpresponse. getentity ();} catch (ioexception e) {return result;}/*** role: http request server. No returned data is obtained, 1 <br> * Date: 2012-2-10 <br> ** @ author codyy) peijiangpi is returned. NG */Public int sendtoservice (list <namevaluepair> Params) {try {httprequest = new httppost (URL); If (Params! = NULL) {httprequest. setentity (New urlencodedformentity (Params, HTTP. utf_8);} httpresponse = httpclient.exe cute (httprequest);} catch (exception e) {e. printstacktrace (); Return 0;} return 1 ;}}

Package COM. zhenshi. util; 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;/*** Class Name: httpdownload <br> * Role: class of the downloaded file <br> * Date: 2012-4-5 4-5 <br> ** @ version V1.0 * @ author peijiangping */public class httpdownload {/*** function: download an object to a specified directory, 1 <br> * Date: <br> * Author: Jiang jiangping */public static int downloadfile (string httpurl, string filename, string path) {fileoutputstream Fos = NULL; inputstream is = NULL; httpurlconnection conn = NULL; // create the file directory file tmpfile = new file (PATH); If (! Tmpfile. exists () {tmpfile. mkdir () ;}// obtain the file object file = new file (path + "/" + filename); try {URL url = new URL (httpurl ); try {conn = (httpurlconnection) URL. openconnection (); is = Conn. getinputstream (); // gets the inputstream object returned by the HTTP request. Fos = new fileoutputstream (File); // get the output stream object of the file to write the byte [] Buf = new byte [256]; Conn. connect (); // HTTP request server double COUNT = 0; // If (Conn. getresponsecode ()> = 400) {system. out. println ("Nono"); Return 0;} else {While (count <= 100) {If (is! = NULL) {int numread = is. read (BUF); If (numread <= 0) {break;} else {FOS. write (BUF, 0, numread) ;}} else {break ;}} Conn. disconnect (); FOS. close (); is. close ();} catch (ioexception e) {e. printstacktrace (); Return 0;} finally {If (Conn! = NULL) {conn. Disconnect (); Conn = NULL;} If (FOS! = NULL) {try {FOS. Close () ;}catch (ioexception e) {e. printstacktrace () ;}fos = NULL ;}if (is! = NULL) {try {is. close ();} catch (ioexception e) {e. printstacktrace () ;}is = NULL ;}} catch (malformedurlexception e) {e. printstacktrace (); Return 0;} return 1 ;}}

Package COM. zhenshi. util; import android. content. context; import android. graphics. drawable. drawable; import android. view. gravity; import android. view. layoutinflater; import android. view. view; import android. widget. imageview; import android. widget. linearlayout; import android. widget. toast;/*** Class Name: toastutil <br> * class description: displays a toast tool class <br> * PS: <br> ** @ Version 1.00 2011/09/30 * @ author codyy) peijiangping */public class toastutil {private context; Public toastutil (context) {This. context = context;}/*** @ Param title * @ Param icon * @ return returns a toast with an image */Public toast showpictoast (String title, drawable icon) {Toast = toast. maketext (context, title, toast. length_long); toast. setgravity (gravity. center, 0, 0); linearlayout toastview = (linearlayout) toast. getview (); imageview imagecodeproject = new imageview (context); imagecodeproject. setbackgrounddrawable (icon); toastview. addview (imagecodeproject, 0); Return toast;}/*** @ Param title * @ return returns a default toast */Public toast showdefulttoast (String title) {Toast = toast. maketext (context, title, toast. length_short); Return toast;}/*** @ Param layoutid * @ return returns a custom toast */Public toast showdiytoast (INT layoutid) {layoutinflater Inflater = layoutinflater. from (context); view myview = Inflater. inflate (layoutid, null); Toast = new toast (context); toast. setgravity (gravity. right | gravity. top, 12, 40); toast. setduration (toast. length_long); toast. setview (myview); Return toast ;}}


3. The server code is as follows:

Package COM. zhenshi. servlet; import Java. io. ioexception; import Java. util. map; import javax. servlet. servletexception; import javax. servlet. HTTP. httpservlet; import javax. servlet. HTTP. httpservletrequest; import javax. servlet. HTTP. httpservletresponse; import COM. zhenshi. util. serialportlistener;/*** Class Name: getversionservlet <br> * class description: Get the latest software version <br> * PS: <br> ** @ Version 1.00 2012-4-6 * @ author zhenshi) peijiangping */public class getversionservlet extends httpservlet {Private Static final long serialversionuid = 1l; Public Map <string, string> configmap; /*** @ see httpservlet # httpservlet () */Public getversionservlet () {super (); // todo auto-generated constructor stub}/*** @ see httpservlet # doget (httpservletrequest request, httpservletresponse * response) */protected void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {request. setcharacterencoding ("UTF-8"); configmap = serialportlistener. configmap; string version = configmap. get ("version"); system. out. println (version); response. getwriter (). write (version);}/*** @ see httpservlet # dopost (httpservletrequest request, httpservletresponse * response) */protected void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {/* receive POST Request */doget (request, response );}}

Package COM. zhenshi. util; import Java. io. bufferedreader; import Java. io. filereader; import Java. io. ioexception; import Java. util. hashmap; import Java. util. map; import javax. servlet. servletcontext; import javax. servlet. servletcontextevent; import javax. servlet. servletcontextlistener;/*** Class Name: serialportlistener <br> * class description: Listener class for Web server startup <br> * PS: <br> * Date: 2012-2-16 <br> ** @ Version 1.00 * @ Author codyy) peijiangping */public class serialportlistener implements servletcontextlistener {public static Map <string, string> configmap; Public void contextinitialized (incluevent) {servletcontext context = event. getservletcontext (); string Path = context. getrealpath ("/"); Path = path. replace ("\", "/"); Path = path. replace ("/webcontent", ""); configmap = findconfig (PATH); // context. Setattribute ("configmap", configmap);} public void contextdestroyed (servletcontextevent arg0) {} public Map <string, string> findconfig (string path) {Map <string, string> configmap = new hashmap <string, string> (); filereader Fr = NULL; bufferedreader BR = NULL; try {Fr = new filereader (path + "CONF/config. properties "); // create a filereader object to read the latest stream BR = new bufferedreader (FR); // buffer the input string myreadline of the specified file ;// Defines a string type variable to read a row at a time while (BR. ready () {myreadline = BR. readline (); string [] keyandvalue = myreadline. split ("="); If (keyandvalue. length = 2) {configmap. put (keyandvalue [0]. trim (), keyandvalue [1]. trim ();} else if (keyandvalue. length> 2) {string keyname = myreadline. substring (0, myreadline. indexof ("="); string keyValue = myreadline. substring (myreadline. indexof ("=") + 1); configmap. put (keyname. tr Im (), keyValue. Trim () ;}} catch (ioexception e) {e. printstacktrace () ;}finally {If (BR! = NULL) {try {Br. Close () ;}catch (ioexception e) {e. printstacktrace () ;}} if (fr! = NULL) {try {Fr. Close () ;}catch (ioexception e) {e. printstacktrace () ;}} return configmap ;}}

The content of config. properties is:

#configversion=1.0

The content of web. XML is:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">  <display-name>TestHttpServlet</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>  <listener>    <listener-class>com.zhenshi.util.SerialPortListener</listener-class>  </listener>  <servlet>    <description></description>    <display-name>GetVersionServlet</display-name>    <servlet-name>GetVersionServlet</servlet-name>    <servlet-class>com.zhenshi.servlet.GetVersionServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>GetVersionServlet</servlet-name>    <url-pattern>/GetVersionServlet</url-pattern>  </servlet-mapping></web-app>

The server is tomcat.

Androidmainfest. xml remember to add some application-related permissions.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.