SoFunction
Updated on 2025-03-01

Android programming method to automatically update, download and install applications

This article describes the method of Android programming to automatically update, download and install applications. Share it for your reference, as follows:

We have seen that many Android applications have automatic update function, and users can complete the software upgrade and update with one click. Thanks to the software package management and installation mechanism of the Android system, this function is quite simple to implement, so let’s practice it below.

1. Prepare knowledge

The version identity of each Android apk is defined in it:

<manifest xmlns:andro
   package=""
   android:versionCode="1"
   android:versionName="1.0.0">
<application></application>
</manifest>

Among them, the two fields android:versionCode and android:versionName represent the version code and the version name respectively. versionCode is an integer number, versionName is a string. Since version is for users to see, it is not easy to compare sizes. When upgrading and checking, you can mainly check versionCode to facilitate comparison of the size of the version before and after.

So, how to read versionCode and versionName in the application? You can use the PackageManager API, refer to the following code:

public static int getVerCode(Context context) {
      int verCode = -1;
      try {
        verCode = ().getPackageInfo(
            "", 0).versionCode;
      } catch (NameNotFoundException e) {
        (TAG, ());
      }
      return verCode;
    }
    public static String getVerName(Context context) {
      String verName = "";
      try {
        verName = ().getPackageInfo(
            "", 0).versionName;
      } catch (NameNotFoundException e) {
        (TAG, ());
      }
      return verName;
}

Or write android:versionName=”1.2.0” as android:versionName=”@string/app_versionName” in AndroidManifest, and then add the corresponding string in values/. After this implementation, you can use the following code to obtain the version name:

public static String getVerName(Context context) {
      String verName = ()
      .getText(.app_versionName).toString();
      return verName;
}

Similarly, the application name of apk can be obtained as follows:

public static String getAppName(Context context) {
      String verName = ()
      .getText(.app_name).toString();
      return verName;
}

2. Process framework

Compare》Download》Install.

3. Version check

Place the latest version of the apk file on the server, such as: http://localhost/myapp/

At the same time, place the version information corresponding to this apk on the server to call the interface or file, such as: http://localhost/myapp/
The contents in it are:

[{"appname":"jtapp12","apkname":"","verName":1.0.1,"verCode":2}]

Then, do version reading and checking on the mobile client:

private boolean getServerVer () {
  try {
    String verjson = (Config.UPDATE_SERVER
        + Config.UPDATE_VERJSON);
    JSONArray array = new JSONArray(verjson);
    if (() > 0) {
      JSONObject obj = (0);
      try {
        newVerCode = (("verCode"));
        newVerName = ("verName");
      } catch (Exception e) {
        newVerCode = -1;
        newVerName = "";
        return false;
      }
    }
  } catch (Exception e) {
    (TAG, ());
    return false;
  }
  return true;
}

Compare the versions of the server and client and perform update operations.

if (getServerVerCode()) {
       int vercode = (this); // Use the method written in the first section above       if (newVerCode &gt; vercode) {
         doNewVersionUpdate(); // Update new version       } else {
         notNewVersionShow(); // It is prompted that it is the latest version       }
}

Detailed method:

private void notNewVersionShow() {
    int verCode = (this);
    String verName = (this);
    StringBuffer sb = new StringBuffer();
    ("Current Version:");
    (verName);
    (" Code:");
    (verCode);
    (",/n is the latest version, no update is required!");
    Dialog dialog = new ().setTitle("Software Update")
        .setMessage(())// Set content        .setPositiveButton("Sure",// Set the OK button            new () {
              @Override
              public void onClick(DialogInterface dialog,
                  int which) {
                finish();
              }
            }).create();// Create    // Show dialog box    ();
  }
  private void doNewVersionUpdate() {
    int verCode = (this);
    String verName = (this);
    StringBuffer sb = new StringBuffer();
    ("Current Version:");
    (verName);
    (" Code:");
    (verCode);
    (", Discover new version:");
    (newVerName);
    (" Code:");
    (newVerCode);
    (", Updated?");
    Dialog dialog = new ()
        .setTitle("Software Update")
        .setMessage(())
        // Set content        .setPositiveButton("renew",// Set the OK button            new () {
              @Override
              public void onClick(DialogInterface dialog,
                  int which) {
                pBar = new ProgressDialog();
                ("Downloading");
                ("Please wait...");
                (ProgressDialog.STYLE_SPINNER);
                downFile(Config.UPDATE_SERVER + Config.UPDATE_APKNAME);
              }
            })
        .setNegativeButton("Not updated yet",
            new () {
              public void onClick(DialogInterface dialog,
                  int whichButton) {
                // Click the "Cancel" button to exit the program                finish();
              }
            }).create();// Create    // Show dialog box    ();
}

4. Download the module

void downFile(final String url) {
    ();
    new Thread() {
      public void run() {
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
          response = (get);
          HttpEntity entity = ();
          long length = ();
          InputStream is = ();
          FileOutputStream fileOutputStream = null;
          if (is != null) {
            File file = new File(
                (),
                Config.UPDATE_SAVENAME);
            fileOutputStream = new FileOutputStream(file);
            byte[] buf = new byte[1024];
            int ch = -1;
            int count = 0;
            while ((ch = (buf)) != -1) {
              (buf, 0, ch);
              count += ch;
              if (length > 0) {
              }
            }
          }
          ();
          if (fileOutputStream != null) {
            ();
          }
          down();
        } catch (ClientProtocolException e) {
          ();
        } catch (IOException e) {
          ();
        }
      }
    }.start();
}

The download is completed, and the main ui thread is notified through the handler to cancel the download dialog box.

void down() {
      (new Runnable() {
        public void run() {
          ();
          update();
        }
      });
}

5. Install the application

void update() {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    ((new File(Environment
        .getExternalStorageDirectory(), Config.UPDATE_SAVENAME)),
        "application/-archive");
    startActivity(intent);
}

If you publish the apk application to the market, you will find that the market has similar modules built-in, which can automatically update or remind you whether to update the application. So, if your own application needs to be automatically updated, is it more convenient to build one yourself? Most of the code mentioned in this article is implemented in. In order to make the update process more friendly, a thread can be established in the initial launcher's activity to check whether there are updates on the server. When there is an update, start UpdateActivity, so that the user experience is smoother.

For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android communication methods summary》、《Summary of the usage of basic Android components》、《Android View View Tips Summary》、《Android layout layout tips summary"and"Android control usage summary

I hope this article will be helpful to everyone's Android programming design.