Android version detection and update

Source: Internet
Author: User

As an android client of the website, the user installs it on his mobile phone. What if I release a new version? You must have the version update function.

It is best to perform automatic version check. However, if you start a program each time, you need to check for a round first, which is a waste. After all, version update is a small probability. Maybe you can judge the time when the program is enabled. It can be detected in a single day. It will not be detected in two days, or it will be random, reducing the detection frequency?

I have implemented the detection function on the menu. If you need it, manually open it and check it. We are a website client. If we have a version update, we can send a notice on the website.

The following key steps are involved in Version Detection and update:

1. Check for new versions

2. download the new version

3. Install and replace the New Version

My solution is

1. Add a file in the assets Folder: ver. cfg, record version information, in plain text format, with only one sentence:

Version=1.0


This will be packaged to the user's mobile phone with installation

Then, on the website, set an XML file ver_apk.xml with the following content:

<?xml version="1.0" encoding="utf-8" ?><string>1.0</string>

During the detection, access the XML file of the website to obtain the latest version number, and then access the server on the mobile phone. compare the records in the cfg file. If they are different, you can think that a new version exists and prompt for updates.

2. Download directly. I don't know how to resume resumable upload.

3. The key to installation and replacement is signature. That is, the signatures of each version must be consistent. Otherwise, the new one cannot be replaced with the old one, and the installation is not completed.

----------------- The weather is too cold, giggling ------------------------------------

This function is implemented on the menu. The trigger code is as follows:

// ================================================ ==================================================================/// Menu/ /======================================================== ======================================== Private Static final string urlapk = "http: // 3G. ***. COM/tool /***. APK "; Private Static final string urlver =" http: // 3G. ***. COM/tool/ver_apk.xml "; @ overridepublic Boolean oncreateoptionsmenu (menu) {menu. add (menu. none, menu. first + 1, 5, "detection Update "). seticon (Android. r. drawable. ic_menu_upload); menu. add (menu. none, menu. first + 2, 4, "quit "). seticon (Android. r. drawable. ic_lock_power_off); Return true ;}@ overridepublic Boolean onoptionsitemselected (menuitem item) {Switch (item. getitemid () {Case menu. first + 1: Toast. maketext (this, "version being checked", toast. length_long ). show (); updatever UV = new updatever (urlapk, urlver, mainactivity. this); UV. checkver (); break; Case menu. first + 2: confirmit (); break;} return false ;}

Detection and update: because there are many codes, write them as a class for encapsulation.

Updatever. Java

Package android. * **; 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.net. uri; import android. OS. asynctask; import android. util. log; import android. webKit. urlutil; import android. widget. toast; import Java. io. file; import ja Va. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import java.net. malformedurlexception; import java.net. URL; import java.net. urlconnection; import Java. util. properties; import Org. XML. sax. inputsource; import Java. text. simpledateformat; import Java. util. date; public class updatever extends activity {Private Static final string tag = "downloa DAPK "; private string pastversion; private string nowversion; Public progressdialog pbar; private string currentfilepath =" "; private string fileex =" "; private string filena = ""; private string strurl = ""; private string versionuri = ""; private context mcontext; private final string filever = "ver. cfg "; Public updatever (string urlapk, string urlver, final context) {simpledateformat df = new simpledat Eformat ("yyyymmddhhmmss"); string ver = "? Ver = "+ DF. format (new date (); // It is used to avoid the caching of the mobile phone. strurl = urlapk + ver; versionuri = urlver + ver; mcontext = context;} public void checkver () {// parse the version page and obtain the version number getversionxml (versionuri);} private void comparever () {load (); // If (pastversion! = NULL &&! Pastversion. equals (nowversion) {dialog = new alertdialog. builder (mcontext ). settitle ("system update "). setmessage (string. format ("the latest version % s is found. The current version is % S. Please update it! ", Nowversion, pastversion) // sets the content // sets the OK button. setpositivebutton ("OK", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {pbar = new progressdialog (mcontext); pbar. settitle ("downloading"); pbar. setmessage ("Please wait... "); pbar. setprogressstyle (progressdialog. style_spinner); fileex = strurl. substring (strurl. lastindexof (". ") + 1, strurl. length ()). tolowercase (); Fileex = fileex. substring (0, fileex. lastindexof ("? "); Filena = strurl. substring (strurl. lastindexof ("/") + 1, strurl. lastindexof (". "); GetFile (strurl );}}). setnegativebutton ("cancel", new dialoginterface. onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int whichbutton) {// click "cancel" to exit the program }}). create (); // create // display the dialog box dialog. show ();} else {toast. maketext (mcontext, String. format ("Currently the latest version % s", pastversion), toast. length_long ). show ();} Private void GetFile (final string strpath) {pbar. show (); try {If (strpath. equals (currentfilepath) {getdatasource (strpath);} currentfilepath = strpath; runnable r = new runnable () {@ overridepublic void run () {try {getdatasource (strpath );} catch (exception e) {log. E (TAG, E. getmessage (), e) ;}}; new thread (R ). start ();} catch (exception e) {e. printstacktrace () ;}/ * Get Remote File */private void get Datasource (string strpath) throws exception {If (! Urlutil. isnetworkurl (strpath) {log. D ("tag", "error");} else {/* Get URL */URL myurl = new URL (strpath);/* create online */urlconnection conn = myurl. openconnection (); Conn. connect ();/* inputstream download file */inputstream is = Conn. getinputstream (); If (is = NULL) {log. D ("tag", "error"); throw new runtimeexception ("file content not read");}/* create a temporary file */file mytempfile = file. createtempfile (filena ,". "+ fileex); mytempfile. getabso Lutepath ();/* write the file to a temporary disk */fileoutputstream Fos = new fileoutputstream (mytempfile); byte Buf [] = new byte [128]; do {int numread = is. read (BUF); If (numread <= 0) {break;} FOS. write (BUF, 0, numread);} while (true);/* open the file to install */openfile (mytempfile); try {is. close ();} catch (exception ex) {log. D ("tag", "error"); log. E (TAG, "error:" + ex. getmessage (), Ex) ;}}/ * open the file on your phone */private void openfile (file F) {Pbar. cancel (); intent = new intent (); intent. addflags (intent. flag_activity_new_task); intent. setaction (Android. content. intent. action_view);/* Call getmimetype () to obtain mimetype */string type = getmimetype (f);/* set the intent file and mimetype */intent. setdataandtype (URI. fromfile (F), type); mcontext. startactivity (intent);}/* determine the mimetype Method */private string getmimetype (file F) {string type = ""; string F Name = f. getname ();/* Get the extension */string end = fname. substring (fname. lastindexof (". ") + 1, fname. length ()). tolowercase ();/* determine mimetype by extension type */If (end. equals ("m4a") | end. equals ("MP3") | end. equals ("mid") | end. equals ("xmf") | end. equals ("Ogg") | end. equals ("WAV") {type = "audio";} else if (end. equals ("3GP") | end. equals ("MP4") {type = "video";} else if (end. equals ("jpg") | end. equals ("GIF ") | End. equals ("PNG") | end. equals ("Jpeg") | end. equals ("BMP") {type = "image";} else if (end. equals ("APK") {/* android. permission. install_packages */type = "application/vnd. android. package-Archive ";}else {type =" * ";}/ * if it cannot be opened directly, select */If (! End. equals ("APK") {type + = "/*";} return type;} private void getversionxml (string resourceurl) {getver GV = new getver(registry.gv.exe cute (resourceurl );} private Boolean load () {properties Properties = new properties (); try {inputstream stream = mcontext. getassets (). open (filever); // fileinputstream stream = mcontext. openfileinput (filever); // read the file content properties. load (Stream);} catch (filenotfoundexception e) {return false;} catch (ioexception e) {return false;} catch (exception e) {return false;} pastversion = string. valueof (properties. get ("version "). tostring (); Return true ;} // ================================================ ==================================================================/// getver/ /======================================================== ====================================== class getver extends asynctask <string, integer, string >{@ override protected string doinbackground (string... urlver) {string DB = NULL; Url url = NULL; try {url = new URL (urlver [0]);} catch (malformedurlexception e) {e. printstacktrace ();} inputsource is = NULL; try {is = new inputsource (URL. openstream (); is. setencoding ("UTF-8"); DB = saxgetversionservice. readrssxml (is);} catch (exception e) {e. printstacktrace () ;}return dB ;}@ override protected void oncancelled () {super. oncancelled () ;}@ override protected void onpostexecute (string result) {nowversion = result; comparever ();}}}

Androidmanifest. xml:

    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.INSTALL_PACKAGES"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    <uses-permission android:name="android.permission.RESTART_PACKAGES" />    <uses-permission android:name="android.permission.READ_PHONE_STATE" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

References:

Http://download.csdn.net/detail/xtlvice/3510681

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.