Android app to implement the most basic method of applying internal automatic updating example _android

Source: Internet
Author: User
Tags svn

This is only a preliminary implementation, and does not include automatic compilation and other functions. You need to manually change the updated XML file and the latest apk.
A total of four documents involved!
First, the client
androidupdatetestactivity: Program Home
Main.xml: Home Layout
Update: Updating classes
Softupdate_progress: Update Wait interface

Updage

Package majier.test; 
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 Javax.xml.parsers.DocumentBuilder; 
 
Import Javax.xml.parsers.DocumentBuilderFactory; 
Import org.w3c.dom.Document; 
Import org.w3c.dom.Element; 
Import Org.w3c.dom.Node; 
 
Import org.w3c.dom.NodeList; 
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.Widgets. 
ProgressBar; 
 
Import Android.widget.Toast; 
  public class Update {private static final int DOWNLOAD = 1; 
  private static final int download_finish = 2; 
  private static final int connect_failed = 0; 
  private static final int connect_success = 1; 
  Hashmap<string, string> Mhashmap; 
  Private String Msavepath; 
  private int progress; 
  Private Boolean cancelupdate = false; 
  Private context Mcontext; 
  Private ProgressBar mprogress; 
  Private Dialog Mdownloaddialog; Private String Mxmlpath; 
    Server Update XML store address Public Update (context context, string Xmlpath, String savepath) {This.mcontext = context; 
    This.mxmlpath = Xmlpath; 
  This.msavepath = Savepath;  
      Private Handler Mhandler = new Handler () {public void Handlemessage (msg) {switch (msg.what) { 
        Case DOWNLOAD:mProgress.setProgress (progress); 
      Break 
        Case download_finish:installapk (); 
      Break 
   Default     Break 
  } 
    }; 
 
  }; /** * Check update/public void Checkupdate () {New Thread (new Runnable () {@Override public void 
          Run () {try {URL url = new URL (mxmlpath); 
          HttpURLConnection conn = (httpurlconnection) URL. OpenConnection (); 
          Conn.setconnecttimeout (5000); 
          InputStream instream = Conn.getinputstream (); 
          Mhashmap = Parsexml (instream); 
          msg = new Message (); 
          Msg.what = connect_success; 
        Handler.sendmessage (msg); 
          catch (Exception e) {msg = new message (); 
          Msg.what = connect_failed; 
        Handler.sendmessage (msg); 
  and}}). Run (); /** * Access Server update XML/Handler Handler = new Handler () {@Override public void Handlemessage (Mess 
      Age msg) {super.handlemessage (msg); Switch (msg.what) {case CONNECT_FAILED:Toast.makEText (Mcontext, "Access server failed!") 
        ", Toast.length_short). Show (); 
      Break Case connect_success:if (null!= mhashmap) {int servicecode = integer.valueof (Mhashmap.get ("version" 
          )); 
          if (Servicecode > Getversioncode (mcontext)) {shownoticedialog (); 
      }} break; 
 
  } 
    } 
  }; 
    /** * Get Program Version number */private int Getversioncode (context context) {int versioncode = 0; try {versioncode = Context.getpackagemanager (). Getpackageinfo (Mcontext.getpackagename (), 0). versioncod 
    E 
    catch (Namenotfoundexception e) {e.printstacktrace (); 
  return versioncode; /** * Update prompt window/private void Shownoticedialog () {Alertdialog.builder Builder = new Builder (mcont 
    EXT); 
    Builder.settitle ("Software Update"); Builder.setmessage ("New version detected, update?") 
    "); 
         Builder.setpositivebutton ("Update", new Onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {Dialog.dismiss (); 
          Showdownloaddialog (); 
 
    } 
        }); Builder.setnegativebutton ("Cancel", new Onclicklistener () {@Override public void OnClick (Dialo 
          Ginterface dialog, int which) {Dialog.dismiss (); 
    } 
        }); 
    Dialog Noticedialog = Builder.create (); 
  Noticedialog.show (); /** * Download wait window/private void Showdownloaddialog () {Alertdialog.builder Builder = new Builder (mcont 
    EXT); 
    Builder.settitle ("being updated"); 
    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); Builder.setnegativebutton ("Cancel Download", New Onclicklistener () {@Override public void OnClick (Dia 
       Loginterface dialog, int which) {     Dialog.dismiss (); 
          CancelUpdate = true; 
    } 
        }); 
    Mdownloaddialog = Builder.create (); 
    Mdownloaddialog.show (); 
  DOWNLOADAPK (); 
  /** * Trickle 嬭 poured apk file continents Huan/private void downloadapk () {new Downloadapkthread (). Start (); 
      /** * Download Program/Private class Downloadapkthread extends Thread {@Override public void run () { 
 
          try {if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { 
          URL url = new URL (mhashmap.get ("url")); 
          HttpURLConnection conn = (httpurlconnection) URL. OpenConnection (); 
          Conn.connect (); 
          int length = Conn.getcontentlength (); 
 
          InputStream is = Conn.getinputstream (); 
          File File = new file (Msavepath); 
          if (!file.exists ()) {File.mkdir (); 
          File Apkfile = new file (Msavepath, Mhashmap.get ("name")); FileoutpUtstream fos = new FileOutputStream (apkfile); 
          int count = 0; 
          byte buf[] = new byte[1024]; 
            do {int numread = Is.read (BUF); 
            Count + = Numread; 
            progress = (int) (((float) count/length) * 100); 
            Mhandler.sendemptymessage (DOWNLOAD); 
              if (numread <= 0) {mhandler.sendemptymessage (download_finish); 
            Break 
          } fos.write (buf, 0, Numread); 
          while (!cancelupdate); 
          Fos.close (); 
        Is.close (); 
      } catch (Malformedurlexception e) {e.printstacktrace (); 
      catch (IOException e) {e.printstacktrace (); 
    } Mdownloaddialog.dismiss (); 
   
  } 
  }; 
    /** * Install APK */private void installapk () {File Apkfile = new file (Msavepath, Mhashmap.get ("name")); 
    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); Private hashmap<string, string> parsexml (InputStream instream) throws Exception {Hashmap<stri 
    Ng, 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 + +) {//Traverse child node Node Childnode = (node) childnodes.item (j); 
        if (childnode.getnodetype () = = Node.element_node) {element childelement = (element) Childnode; 
       Version number if ("Version". Equals (Childelement.getnodename ())) {Hashmap.put ("version", Childelement.getfirstchild () 
        . Getnodevalue ()); ///software name else if (("Name". Equals (Childelement.getnodename ())) {hashmap.put ("name"), Childel 
        Ement.getfirstchild (). Getnodevalue ()); ///download address else if (("url". Equals (Childelement.getnodename ())) {hashmap.put ("url", Childelem 
        Ent.getfirstchild (). Getnodevalue ()); 
  }} return hashMap; 
 } 
}

Androidupdatetestactivity

Package majier.test; 
 
Import android.app.Activity; 
Import Android.os.Bundle; 
Import android.os.Environment; 
 
The public class Androidupdatetestactivity extends activity {/** called the ' when ' is the ' The activity ' is the ' the ' 
  ---' 
  @Overr IDE public 
  void OnCreate (Bundle savedinstancestate) { 
    super.oncreate (savedinstancestate); 
    Setcontentview (r.layout.main); 
    Update (); 
  } 
   
  private void Update () { 
    String Sdpath = environment.getexternalstoragedirectory () + "/"; 
    String Msavepath = Sdpath + "boiler/"; 
    Update Updatemanager = new update (this, 
        "Http://localhost:8011/abcd.xml", Msavepath); 
    Updatemanager.checkupdate (); 
  } 
 

Main.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
"http://schemas.android.com/apk/" Res/android " 
  android:layout_width=" fill_parent " 
  android:layout_height=" fill_parent " 
  android:o" rientation= "vertical" > 
 
  <textview 
    android:layout_width= "Fill_parent" 
    Wrap_content " 
    android:text=" @string/hello "/> 
 
</LinearLayout> 

Softupdate_progress.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android= 
  "http://" Schemas.android.com/apk/res/android " 
  android:layout_width=" fill_parent " 
  android:layout_height=" Wrap_ Content "> 
  <progressbar 
    android:id=" @+id/update_progress " 
    android:layout_width=" Fill_ Parent " 
    android:layout_height=" wrap_content " 
    style="? Android:attr/progressbarstylehorizontal "/> 
</LinearLayout> 

The version number of the system needs to be modified each time a new apk is generated.

Modify version code and version name. The above code shows that the system is based on the version code to determine whether the need to update. Version name as one of the versions.
Here I recommend that the version code start with 10, so that the aspect name is modified (1.1, 1.2).
After the modification is complete, build the system. The apk file is then placed under the server's file.

Second, the service side
The main service side is to create a Web site for users to download apk. Create a new Web site on IIS

http://localhost:8011/. Place the update files and the updated XML in the directory.

Version.xml format

<update> 
  <version>12</version> 
  <name>BoilerAndroid_1.1</name> 
  < Url>http://192.168.0.33:8011/boilerandroid.apk</url> 
</update> 

Version corresponds to the version code of the new program;
Name casually named;
The URL corresponds to the apk download path.

A problem may be encountered here, and IIS will complain when accessing the URL path. The main reason is that IIS does not know apk and how to handle it.
Here we add the MIME type of the Android program in IIS to enable APK support downloads.
In IIS Manager, view the type of site--mime you have created--Add.
File name extension:. apk
MIME type: application/vnd.android.package-archive

So you can download it.
Now it's just a simple automatic update program. We can see that the version number needs to be filled out by itself, and to correspond to the XML, apk need to be generated and placed under the update URL.
Such artificial operation, it is easy to cause mistakes. So, next we're going to look at the automatic release of the updated version, and the version number corresponds to SVN, which automatically changes the version number of the program after submitting SVN.

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.