Android programming implementation of Automatic Updates, downloads, installation methods _android

Source: Internet
Author: User
Tags getmessage gettext stringbuffer

This article describes the application of Android programming to automatically update, download, install the method. Share to everyone for your reference, specific as follows:

We see a lot of Android apps with Automatic Updates, and the user can update the software with one click. Thanks to the Android software package management and installation mechanism, this feature is fairly simple to implement.

1. Preparation of knowledge

The version ID for each Android apk is defined in Androidmanifest.xml:

<manifest xmlns:android= "http://schemas.android.com/apk/res/android"
   package= "Com.myapp"
   android: Versioncode= "1"
   android:versionname= "1.0.0" >
<application></application>
</ Manifest>

Where the Android:versioncode and Android:versionname two fields represent the version code, the version name, respectively. Versioncode is an integer number, Versionname is a string. Because version is for users to see, not too easy to compare the size of the upgrade check, you can check the main versioncode, easy to compare the size of the version before and after.

So, how do you read the Versioncode and Versionname in the Androidmanifest.xml in the application? You can use the Packagemanager API to refer to the following code:

public static int Getvercode {
      int vercode =-1;
      try {
        Vercode = Context.getpackagemanager (). Getpackageinfo (
            "Com.myapp", 0). Versioncode;
      } catch ( Namenotfoundexception e) {
        log.e (TAG, E.getmessage ());
      }
      return vercode;
    }
    public static string Getvername {
      string vername = "";
      try {
        vername = Context.getpackagemanager (). Getpackageinfo (
            "Com.myapp", 0). Versionname;
      } catch ( Namenotfoundexception e) {
        log.e (TAG, E.getmessage ());
      }
      return vername;
}

or in Androidmanifest android:versionname= "1.2.0″ written android:versionname=" @string/app_versionname ", and then in values/ Strings.xml, you can use the following code to get the version name after you implement it:

public static string Getvername {
      string vername = Context.getresources ()
      . GetText ( R.string.app_versionname). toString ();
      return vername;
}

Similarly, APK's application name can be obtained as follows:

public static string Getappname {
      string vername = Context.getresources ()
      . GetText ( R.string.app_name). toString ();
      return vername;
}

2. Process Framework

Comparison "Download" installation.

3. Version check

Place the latest version of the APK file on the service side, such as: http://localhost/myapp/myapp.apk

At the same time, place the version information that corresponds to this apk on the server to call the interface or file, such as: Http://localhost/myapp/ver.json
The contents of the Ver.json are:

[{"AppName": "JTAPP12", "Apkname": "jtapp-12-updateapksamples.apk", "Vername": 1.0.1, "Vercode": 2}]

Then, on the phone client for version read and check:

Private Boolean Getserverver () {
  try {
    String Verjson = networktool.getcontent (config.update_server
        + Config.update_verjson);
    Jsonarray array = new Jsonarray (Verjson);
    if (Array.Length () > 0) {
      jsonobject obj = array.getjsonobject (0);
      try {
        Newvercode = Integer.parseint (obj.getstring ("Vercode"));
        Newvername = obj.getstring ("Vername");
      } catch (Exception e) {
        newvercode =-1;
        Newvername = "";
        return false;}}
  catch (Exception e) {
    log.e (TAG, E.getmessage ());
    return false;
  }
  return true;
}

Compare the server and client versions and update the operation.

if (Getserververcode ()) {
       int vercode = Config.getvercode (this);//Using the method written in the previous section
       if (Newvercode > Vercode) { C26/>donewversionupdate (); Update new version
       } else {
         notnewversionshow ();//Prompt is currently latest version
       }
}

Detailed method:

private void Notnewversionshow () {int vercode = Config.getvercode (this);
    String Vername = Config.getvername (this);
    StringBuffer sb = new StringBuffer ();
    Sb.append ("Current version:");
    Sb.append (Vername);
    Sb.append ("Code:");
    Sb.append (Vercode);
    Sb.append (",/n is already the latest version, no need to update!"); Dialog Dialog = new Alertdialog.builder (update.this). Settitle ("Software Update"). Setmessage (Sb.tostring ())/set content. s
              Etpositivebutton (OK,//Set OK button new Dialoginterface.onclicklistener () {@Override
              public void OnClick (Dialoginterface dialog, int which) {finish ();
  ()). Create ();//Show dialog Box Dialog.show ();
    private void Donewversionupdate () {int vercode = Config.getvercode (this);
    String Vername = Config.getvername (this);
    StringBuffer sb = new StringBuffer ();
    Sb.append ("Current version:");
    Sb.append (Vername);
    Sb.append ("Code:");
    Sb.append (Vercode); Sb. Append (", Discovery New version:");
    Sb.append (Newvername);
    Sb.append ("Code:");
    Sb.append (Newvercode);
    Sb.append (", whether update?");
        Dialog Dialog = new Alertdialog.builder (update.this). Settitle ("Software Update"). Setmessage (Sb.tostring ()) Set the content. Setpositivebutton (update,//Set OK button new Dialoginterface.onclicklistener () {@Overr IDE public void OnClick (Dialoginterface dialog, int which) {pbar = new Pr
                Ogressdialog (Update.this);
                Pbar.settitle ("Downloading");
                Pbar.setmessage ("Please wait ...");
                Pbar.setprogressstyle (Progressdialog.style_spinner);
              Downfile (Config.update_server + config.update_apkname); }). Setnegativebutton ("Temporarily not updated", new Dialoginterface.onclicklistener () {Publ
       IC void OnClick (dialoginterface dialog, int whichbutton) {//click the "Cancel" button to exit the program         Finish ();
()). Create ();//Show dialog Box Dialog.show ();

 }

4. Download module

void Downfile (final String URL) {pbar.show ();
        New Thread () {public void run () {httpclient client = new Defaulthttpclient ();
        HttpGet get = new HttpGet (URL);
        HttpResponse response;
          try {response = Client.execute (get);
          httpentity entity = response.getentity ();
          Long length = Entity.getcontentlength ();
          InputStream is = Entity.getcontent ();
          FileOutputStream fileoutputstream = null;
                if (is!= null) {File File = new file (Environment.getexternalstoragedirectory ()),
            Config.update_savename);
            FileOutputStream = new FileOutputStream (file);
            byte[] buf = new byte[1024];
            int ch =-1;
            int count = 0;
              while (ch = is.read (buf))!=-1) {fileoutputstream.write (buf, 0, ch);
              Count + = ch;
    if (length > 0) {}}}      Fileoutputstream.flush ();
          if (FileOutputStream!= null) {fileoutputstream.close ();
        } down ();
        catch (Clientprotocolexception e) {e.printstacktrace ();
        catch (IOException e) {e.printstacktrace ();
}}.start ();

 }

The download completes and notifies the main UI thread via handler to cancel the Download dialog box.

void Down () {handler.post () {The
      new Runnable () {public
        void run () {
          pbar.cancel ();
          Update ();}}
      );


5. Installation Application

void Update () {
    Intent Intent = new Intent (intent.action_view);
    Intent.setdataandtype (uri.fromfile new File (Environment
        . getExternalStorageDirectory (), Config.update_ Savename)),
        "application/vnd.android.package-archive");
    StartActivity (intent);
}

If you publish the APK application to market, you will find that a similar module is built inside market, which automatically updates or alerts you to update the application. So, for your own applications need to automatically update, it is more convenient to build one yourself? Most of the code mentioned in this article is implemented in Updateactivity.java, in order to make the update process more user-friendly, you can create a thread in the initial launcher activity to check for updates to the server. Start updateactivity when updates are available, and the experience is smoother.

More interested readers of Android-related content can view this site: "Introduction to Android Development and advanced Course", "Android Communication Summary", "Android Basic Components Usage Summary", "Android View Summary", " Android Layout layout Tips and a summary of the use of Android controls

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.