The method of automatically detecting version and automatic upgrade of Android programming _android

Source: Internet
Author: User
Tags stub

The example of this article is about the automatic detection version of Android programming and the method of auto upgrade. Share to everyone for your reference, specific as follows:

Steps:

1. Detect the current version of the information androidmanifest.xml-->manifest-->android:versionname.
2. Obtain the version number from the server (the version number exists in the XML file) and match the currently detected version, if it does not match, prompt the user for an upgrade, and if the match is entered into the program main interface.
3. When the user is prompted to upgrade the version, if the user clicked OK, the system will automatically download from the server and automatically upgrade, if the click Cancel will enter the program main interface.

Effect Chart:

Gets the version number of the current program:


 * * Get the version number of the current program
/Private String Getversionname () throws exception{
  //Get Packagemanager instance
  Packagemanager Packagemanager = Getpackagemanager ();
  Getpackagename () is the package name of your current class, and 0 represents the Get version information
  packageinfo packinfo = Packagemanager.getpackageinfo (Getpackagename (), 0 );
  return packinfo.versionname;
}

To get the version number on the server side:


 * * Using the Pull parser to resolve the XML file returned by the server (XML encapsulated version number)/public
static Updatainfo Getupdatainfo (InputStream is) throws exception{
  Xmlpullparser parser = Xml.newpullparser ();
  Parser.setinput (IS, "utf-8");/set resolved data source
  int type = Parser.geteventtype ();
  Updatainfo info = new Updatainfo ()//entity while
  (type!= xmlpullparser.end_document) {
    switch (type) {
    case Xmlpullparser.start_tag:
      if ("Version". Equals (Parser.getname ())) {
        info.setversion (Parser.nexttext ()); Gets the version number
      }else if ("url". Equals (Parser.getname ())) {
        Info.seturl (Parser.nexttext ());//Get the APK file to be upgraded
      } else if ("description". Equals (Parser.getname ())) {
        info.setdescription (Parser.nexttext ());//Get the information for the file
      } Break
      ;
    Type = Parser.next ();
  }
  return info;
}

Download apk from the server:

 public static File Getfilefromserver (String path, ProgressDialog PD) throws exception{ If equal, the current sdcard is mounted on the phone and is available if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {URL
    url = new URL (path);
    HttpURLConnection conn = (httpurlconnection) url.openconnection ();
    Conn.setconnecttimeout (5000);
    Gets the size of the file Pd.setmax (Conn.getcontentlength ());
    InputStream is = Conn.getinputstream ();
    File File = new file (Environment.getexternalstoragedirectory (), "updata.apk");
    FileOutputStream fos = new FileOutputStream (file);
    Bufferedinputstream bis = new Bufferedinputstream (IS);
    byte[] buffer = new byte[1024];
    int Len;
    int total=0;
      while (Len =bis.read (buffer)!=-1) {fos.write (buffer, 0, Len);
      total+= Len;
    Gets the current download amount pd.setprogress (total);
    } fos.close ();
    Bis.close ();
    Is.close ();
  return file;
  } else{return null; }
}

Matching, downloading, automatic installation:

* * Get XML parsing from server and compare version number */public class Checkversiontask implements runnable{public void run () {try {//
      Get server address from resource file String path = Getresources (). getString (R.string.serverurl);
      The object URL URL is wrapped as url = new URL (path);
      HttpURLConnection conn = (httpurlconnection) url.openconnection ();
      Conn.setconnecttimeout (5000);
      InputStream is =conn.getinputstream ();
      info = Updatainfoparser.getupdatainfo (IS);
        if (Info.getversion (). Equals (Versionname)) {log.i (TAG, "same version number without upgrade");
      Loginmain ();
        }else{log.i (TAG, "version number is different, prompt user upgrades");
        msg = new Message ();
        Msg.what = updata_client;
      Handler.sendmessage (msg);
      } catch (Exception e) {//Pending message msg = new Message ();
      Msg.what = Get_undatainfo_error;
      Handler.sendmessage (msg);
    E.printstacktrace (); }} Handler Handler = new Handler () {@Override public void Handlemessage (msg) {//TODO auto-generated Method Stub super.handlemessage (msg);
      Switch (msg.what) {case updata_client://dialog box notifies the user of the upgrade program Showupdatadialog ();
    Break
      Case GET_UNDATAINFO_ERROR://Server timeout Toast.maketext (Getapplicationcontext (), "Get Server update information failed", 1). Show ();
      Loginmain ();
    Break
      Case down_error://download apk failed Toast.maketext (Getapplicationcontext (), "Download new version failed", 1). Show ();
      Loginmain ();
    Break
}
  }
};
 /* * * * Pop-up dialog box to notify users of the update * * Pop-up dialog box: * 1. Create Alertdialog Builder. * 2. To set properties for Builder, dialog box content, Style, Button * 3. Create a dialog box by Builder * 4. dialog box Show () out/protected void Showupdatadialog () {Alertdia Log.
  Builder Builer = new Builder (this);
  Builer.settitle ("version Upgrade");
  Builer.setmessage (Info.getdescription ());  Download the new apk from the server when the button is clicked and then install Builer.setpositivebutton (OK), new Onclicklistener () {public void OnClick (dialoginterface
      dialog, int which) {log.i (TAG, "Download apk, update");
    DOWNLOADAPK ();
  }
  }); Log on when the click button is canceled BuilEr.setnegativebutton ("Cancel", new Onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {//T
    Odo auto-generated Method Stub Loginmain ();
  }
  });
  Alertdialog dialog = Builer.create ();
Dialog.show ();  * * * Download APK/protected void downloadapk () {final progressdialog PD from the server;
  Progress Bar dialog box PD = new ProgressDialog (this);
  Pd.setprogressstyle (progressdialog.style_horizontal);
  Pd.setmessage ("Downloading updates");
  Pd.show (); New Thread () {@Override public void run () {try {file = Downloadmanager.getfilefromserver (info
        . GETURL (), PD);
        Sleep (3000);
        installapk (file); Pd.dismiss ();
        End Off Progress bar dialog box catch (Exception e) {msg = new message ();
        Msg.what = Down_error;
        Handler.sendmessage (msg);
      E.printstacktrace ();
}}}.start ();
  }//install apk protected void installapk (file file) {Intent Intent = new Intent ();
  Perform action intent.setaction (Intent.action_view); //Executed data type Intent.setdataandtype (uri.fromfile (file), "application/vnd.android.package-archive");
StartActivity (Intent);
  * * * Enter the main interface of the program */private void Loginmain () {Intent Intent = new Intent (this,mainactivity.class);
  StartActivity (Intent);
End off the current Activity this.finish ();

 }

Updatainfo:

public class Updatainfo {
  private String version;
  Private String URL;
  Private String description;
  Public String GetVersion () {return
    version;
  }
  public void Setversion (String version) {
    this.version = version;
  }
  Public String GetUrl () {return
    URL;
  }
  public void SetUrl (String url) {
    this.url = URL;
  }
  Public String GetDescription () {return
    description;
  }
  public void SetDescription (String description) {
    this.description = description;
  }
}

Update.xml:

<?xml version= "1.0" encoding= "Utf-8"?>
<info>
  <version>2.0</version>
  < Url>http://192.168.1.187:8080/mobilesafe.apk</url>
  <description> detect the latest version, please update it in time! </description>
</info>

I hope this article will help you with the Android program.

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.