Android Apps Automatic Update code implementation _android

Source: Internet
Author: User

As a result of open source of Android project, the market of n many Android software appeared. In order for us to develop the software to have more users to use, we need to release to the N-market, software upgrades, we also have to go to the Android Market to update, to increase our workload. So it is necessary for us to add Automatic Updates to our Android apps.

Now that we have Automatic updates, we must first let our application know if there is a new version of the software, so we can place the configuration file on our website and 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 am using an XML file for easy reading. Because XML file content is relatively small, file parsing can be done through DOM:

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 (); 
    Get a document builder from the document Builder factory Documentbuilder builder = Factory.newdocumentbuilder (); 
    Building a document instance through the document builder through documents document = Builder.parse (instream); 
    Gets the XML file root node Element root = Document.getdocumentelement (); 
    Get all child nodes nodelist childnodes = Root.getchildnodes (); for (int j = 0; J < Childnodes.getlength (); j + +) {//Traversing child node node Childnode = (node) childnodes.item (j 
      ); 
        if (childnode.getnodetype () = = Node.element_node) {element childelement = (element) Childnode; The version number if ("Version". Equals (Childelement.getnodename ())) {Hashmap.put ("version"), Childelement. GetfirstchILD (). Getnodevalue ()); ///software name else if (("Name". Equals (Childelement.getnodename ())) {hashmap.put ("name"), 
        Childelement.getfirstchild (). Getnodevalue ()); ///download address else if (("url". Equals (Childelement.getnodename ())) {hashmap.put ("url", ch 
        Ildelement.getfirstchild (). Getnodevalue ()); 
  }} return hashMap; 
 }

With the Parsexml () method, we can get the version, filename, and download address of the application on the server. Then we need to get to the version information we have on our phone:

 /** 
 * Get software version number 
 * * 
 @param context 
 * @return 
/private int Getversioncode (context) 
{ 
  int versioncode = 0; 
  Try 
  { 
    //Get software version number, 
    Versioncode = Context.getpackagemanager (). Getpackageinfo ("Com.szy.update", 0). Versioncode; 
  } catch (namenotfoundexception e) 
  { 
    e.printstacktrace (); 
  } 
  return versioncode; 
} 

By this method we obtain the versioncode corresponding to the androidmanifest.xml under Android:versioncode. The Android:versioncode and Android:versionname two properties represent the version number, the version name, respectively. Versioncode is an integer, and Versionname is a string. Because Versionname is for the user to see, not too easy to compare size, upgrade check, you can check versioncode. The application can be used to determine whether the software needs to be updated by comparing the available versions of the phone to the server-side version.

Processing process

Handling 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.content.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; 
  public class Updatemanager {/* download */private static final int DOWNLOAD = 1; 
  /* Download end/private static final int download_finish = 2; /* Save parsed XML Information * * hashmap<string, string> mhashmap; 
  /* Download Save path */private String Msavepath; 
  /* Record progress bar number * * Private int progress; 
 
  /* Cancel Update */private Boolean cancelupdate = false; 
  Private context Mcontext; 
  * * Update progress bar * * Private ProgressBar mprogress; 
 
  Private Dialog Mdownloaddialog; 
      Private Handler Mhandler = new Handler () {public void Handlemessage (msg) {switch (msg.what) 
        {//Download case DOWNLOAD://Set progress bar position mprogress.setprogress (progress); 
      Break 
        Case Download_finish://Installation file installapk (); 
      Break 
      Default:break; 
  } 
    }; 
 
  }; 
  Public Updatemanager {this.mcontext = context; /** * Detection software update/public void Checkupdate () {if (Isupdate ()) {//Display prompt dialog box show 
    Noticedialog (); else {toast.maketext (Mcontext, R.string.soft_update_nO, Toast.length_long). Show (); }/** * Check if software has an updated version * * @return/private Boolean isupdate () {//get current software version int 
    Versioncode = Getversioncode (Mcontext); Put the version.xml on the network and get the file information InputStream instream = ParseXmlService.class.getClassLoader (). getResourceAsStream (" 
    Version.xml "); Parse the XML file. 
    Because the XML file is relatively small, the DOM method is used 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")); 
      Version judgment if (Servicecode > Versioncode) {return true; 
  return false; /** * Get software version number * * @param context * @return/private int Getversioncode (context) {int Versio 
  ncode = 0; try {//Get software version number, corresponding to androidmanifest.xml under Android:versioncode versIoncode = Context.getpackagemanager (). Getpackageinfo ("Com.szy.update", 0). Versioncode; 
  catch (Namenotfoundexception e) {e.printstacktrace (); 
return versioncode;  /** * Show Software Update dialog box */private void Shownoticedialog () {//construct dialog 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 Download dialog box Showdownloaddialog (); 
    } 
    }); Later update Builder.setnegativebutton (R.string.soft_update_later, New Onclicklistener () {@Override PU 
      Blic void OnClick (dialoginterface dialog, int which) {Dialog.dismiss (); 
    } 
    }); 
Dialog Noticedialog = Builder.create ();    Noticedialog.show (); /** * Display software Download dialog box */private void Showdownloaddialog () {//Construct software Download dialog Alertdialog.builder Bui 
    Lder = new Builder (mcontext); 
    Builder.settitle (r.string.soft_updating); 
    Add progress bar to download dialog box final Layoutinflater inflater = Layoutinflater.from (Mcontext); 
    View v = inflater.inflate (r.layout.softupdate_progress, NULL); 
    Mprogress = (ProgressBar) V.findviewbyid (r.id.update_progress); 
    Builder.setview (v); Cancel Update Builder.setnegativebutton (R.string.soft_update_cancel, New Onclicklistener () {@Override P 
        ublic void OnClick (dialoginterface dialog, int which) {Dialog.dismiss (); 
      Set Cancel state CancelUpdate = true; 
    } 
    }); 
    Mdownloaddialog = Builder.create (); 
    Mdownloaddialog.show (); 
  Now file downloadapk ();  
  /** * Download apk file */private void downloadapk () {//start new thread download software (). Start () 
 
  }/** * Download File thread * * @author coolszy/Private class Downloadapkthread extends thread {@Override public void Run () {try {///determine if the SD card exists and has read and write permission if (environment.getexternalsto Ragestate (). Equals (environment.media_mounted)) {//Get the path to the memory card String Sdpath = environment.ge 
          Texternalstoragedirectory () + "/"; 
          Msavepath = Sdpath + "Download"; 
          URL url = new URL (mhashmap.get ("url")); 
          Create connection HttpURLConnection conn = (httpurlconnection) url.openconnection (); 
          Conn.connect (); 
          Gets the file size int length = Conn.getcontentlength (); 
 
          Create an input stream inputstream is = Conn.getinputstream (); 
          File File = new file (Msavepath); 
          Determine if 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; 
            Calculates progress bar position progress = (int) ((float) count/length) * 100); 
            Update Progress Mhandler.sendemptymessage (DOWNLOAD); 
              if (numread <= 0) {//Download complete mhandler.sendemptymessage (download_finish); 
            Break 
          }//Write file Fos.write (buf, 0, Numread); 
          while (!cancelupdate),//Click Cancel to stop downloading. 
          Fos.close (); 
        Is.close (); 
      } catch (Malformedurlexception e) {e.printstacktrace (); 
      catch (IOException e) {e.printstacktrace (); 
    //Cancel Download dialog box display Mdownloaddialog.dismiss (); 
 
  } 
  }; 
 /** * Install apk files  * * private void installapk () {File apkfile = new File (Msavepath, Mhashmap.get ("name")); 
    if (!apkfile.exists ()) {return; 
    ////install APK file via Intent Intent i = new Intent (Intent.action_view); 
    I.setdataandtype (Uri.parse ("file://" + apkfile.tostring ()), "application/vnd.android.package-archive"); 
  Mcontext.startactivity (i); 

 } 
}

Effect chart

Check to see if there is a download file for the emulator sdcard:
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.