Code Implementation of the Android app automatic update function

Source: Internet
Author: User
Due to the open-source Android project, N more Android software markets have emerged on the market. To allow more users to use the software we developed, we need to release it to N multi-market. After the software upgrade, we must also update it on the Android Market, this increases the workload for us. Therefore, it is necessary to add the automatic update function for our Android applications. Since automatic updates are implemented, we must first let our applications know whether new versions of software exist. Therefore, we can place configuration files on our own websites to store the software version information: <update> <version> 2 </version> <name> baidu_xinwen_1.1.0 </name> <url> http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk </url> </update> here I use XML files, easy to read. Because the XML file contains a small amount of content, you can use DOM to parse the file: public class ParseXmlService {public HashMap <String, String> parseXml (InputStream inStream) throws Exception {HashMap <String, string> hashMap = new HashMap <String, String> (); // instantiate a document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory. newInstance (); // obtain a document builder DocumentBuilder builder = factory through the document builder factory. newDocumentBuilder (); // construct a document instance using the document builder. example E Nt document = builder. parse (inStream); // get the root node of the XML file, Element root = document. getDocumentElement (); // obtain all subnodes NodeList childNodes = root. getChildNodes (); for (int j = 0; j <childNodes. getLength (); j ++) {// traverse the subnode Node childNode = (Node) childNodes. item (j); if (childNode. getNodeType () = Node. ELEMENT_NODE) {Element childElement = (Element) childNode; // version if ("version ". equals (childElement. getNodeNa Me () {hashMap. put ("version", childElement. getFirstChild (). getNodeValue ();} // software name else if ("name ". equals (childElement. getNodeName () {hashMap. put ("name", childElement. getFirstChild (). getNodeValue ();} // else if ("url ". equals (childElement. getNodeName () {hashMap. put ("url", childElement. getFirstChild (). getNodeValue () ;}}return hashMap ;}} using the parseXml () method, we can get the version, file name, and name of the application on the server. Then we need to get the version information of the app on our mobile phone:/*** get the software version ** @ param context * @ return */private int getVersionCode (Context context) {int versionCode = 0; try {// obtain the software version number, versionCode = context. getPackageManager (). getPackageInfo ("com. szy. update ", 0 ). versionCode;} catch (NameNotFoundException e) {e. printStackTrace ();} return versionCode;} The versionCode obtained through this method corresponds to AndroidManifest. android: versionCode in xml. Android: versionCode and android: versionName indicate the version number and version name respectively. VersionCode is an integer, while versionName is a string. Because versionName is for users, it is not easy to compare the size. During the upgrade check, you can check versionCode. Compare the obtained app version on the mobile phone with the server version to determine whether the app needs to update the software. Processing Process processing code package com. szy. 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 android. app. alertDialog; import android. app. dialog; import android. app. alertDialog. builder; import android. content. context; import android. con Tent. 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. OS. message; import android. view. layoutInflater; import android. view. view; import android. widget. progressBar; import android. widget. toast ;/** * @ Author coolszy * @ date 2012-4-26 * @ blog http://blog.92coding.com */public class UpdateManager {/* DOWNLOAD */private static final int DOWNLOAD = 1; /* download complete */private static final int DOWNLOAD_FINISH = 2;/* Save the parsed XML Information */HashMap <String, String> mHashMap; /* download and save path */private String mSavePath;/* record progress bar quantity */private int progress;/* whether to cancel update */private boolean cancelUpdate = false; private Context mCo Ntext;/* update progress bar */private ProgressBar mProgress; private Dialog mDownloadDialog; private Handler mHandler = new Handler () {public void handleMessage (Message msg) {switch (msg. what) {// DOWNLOAD case DOWNLOAD: // set the progress bar position mProgress. setProgress (progress); break; case DOWNLOAD_FINISH: // Installation File installApk (); break; default: break ;}}; public UpdateManager (Context context) {this. mContext = context; }/*** Check software update */public void checkUpdate () {if (isUpdate () {// display the prompt dialog box showNoticeDialog ();} else {Toast. makeText (mContext, R. string. soft_update_no, Toast. LENGTH_LONG ). show () ;}}/*** check whether the software has an updated version ** @ return */private boolean isUpdate () {// get the current software version int versionCode = getVersionCode (mContext); // set version. put xml on the network, and then obtain the file information InputStream inStream = ParseXmlService. class. getClassLoader (). getRe SourceAsStream ("version. xml"); // parse the XML file. Because the XML file is small, use DOM to parse ParseXmlService service = new ParseXmlService (); try {mHashMap = service. parseXml (inStream);} catch (Exception e) {e. printStackTrace ();} if (null! = MHashMap) {int serviceCode = Integer. valueOf (mHashMap. get ("version"); // determine if (serviceCode> versionCode) {return true ;}} return false ;} /*** obtain the software version ** @ param context * @ return */private int getVersionCode (Context context) {int versionCode = 0; try {// obtain the software version, corresponding to AndroidManifest. android: versionCode = context. getPackageManager (). getPackageInfo ("com. szy. update ", 0 ). versi OnCode;} catch (NameNotFoundException e) {e. printStackTrace ();} return versionCode;}/*** display software update dialog box */private void showNoticeDialog () {// create 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 onClick (DialogInterface dialog, int which) {dialog. dismiss (); // display the Download Dialog Box showDownloadDialog () ;}}); // update builder later. setNegativeButton (R. string. soft_update_later, new OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog. dismiss () ;}}); Dialog noticeDialog = builder. create (); noticeDialog. show ();}/*** show Software Download Dialog Box */private void showDownloadDialog () {// Construct the Software Download Dialog Box AlertDialog. builder builder = new Builder (mContext); builder. setTitle (R. string. soft_updating); // Add the progress bar final LayoutInflater inflater = LayoutInflater to the download dialog box. from (mContext); View v = inflater. inflate (R. layout. softupdate_progress, null); mProgress = (ProgressBar) v. findViewById (R. id. update_progress); builder. setView (v); // cancel the builder update. setNegativeButton (R. string. soft_update_cancel, n Ew OnClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {dialog. dismiss (); // set the canceled state cancelUpdate = true ;}}); mDownloadDialog = builder. create (); mDownloadDialog. show (); // current file downloadApk ();}/*** download apk file */private void downloadApk () {// start a new thread to download the software new downloadApkThread (). start ();}/*** download file thread ** @ author coolszy * @ date 2012-4-26 * @ blog http: // blog.92codin G.com */private class downloadApkThread extends Thread {@ Override public void run () {try {// determine whether the SD card exists and whether it has read and write permissions if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {// obtain the path of the storage card String sdpath = Environment. getExternalStorageDirectory () + "/"; mSavePath = sdpath + "download"; URL url = new URL (mHashMap. get ("url"); // create a connection HttpURLConnection conn = (HttpURLConnection) Url. openConnection (); conn. connect (); // get the file size int length = conn. getContentLength (); // create the input stream InputStream is = conn. getInputStream (); File file = new File (mSavePath); // checks whether the File directory exists 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; // calculate the progress bar position progress = (int) (float) count/length) * 100); // update the progress of mHandler. sendEmptyMessage (DOWNLOAD); if (numread <= 0) {// DOWNLOAD completed mHandler. s EndEmptyMessage (DOWNLOAD_FINISH); break;} // write the file fos. write (buf, 0, numread);} while (! CancelUpdate); // click Cancel to stop the download. fos. close (); is. close () ;}} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();} // The cancel download dialog box displays mDownloadDialog. dismiss () ;}};/*** install APK File */private void installApk () {File apkfile = new File (mSavePath, mHashMap. get ("name"); if (! Apkfile. exists () {return;} // install the APK file Intent I = new Intent (Intent. ACTION_VIEW); I. setDataAndType (Uri. parse ("file: //" + apkfile. toString (), "application/vnd. android. package-archive "); mContext. startActivity (I );}}
Related Article

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.