Automatic update, download, and installation of Android applications

Source: Internet
Author: User

From: http://daosrc.com /? P = 439

We can see that many Android applications have the automatic update function. You can update the software with one click. Thanks to the software package management and installation mechanism of the Android system, this function is quite simple to implement. Let's take a look at it.
1. Preparation knowledge
The version ID of 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>

The Android: versioncode and Android: versionname fields represent the version code and version name respectively. Versioncode is an integer and versionname is a string. Because the version is for users, it is not easy to compare the size. During the upgrade check, you can check versioncode to compare the size before and after the publication.
So, how do I read versioncode and versionname in androidmanifest. xml? You can use the packagemanager API by referring to the following code:

    public static int getVerCode(Context context) {              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(Context context) {              String verName = "";              try {                  verName = context.getPackageManager().getPackageInfo(                          "com.myapp", 0).versionName;              } catch (NameNotFoundException e) {                  Log.e(TAG, e.getMessage());              }              return verName;         }

Alternatively, in androidmanifest, write Android: versionname = "1.2.0" as Android: versionname = "@ string/app_versionname", and then in values/strings. add the corresponding string to the XML file. After implementation, you can use the following code to obtain the version name:

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

Similarly, the APK Application name can be obtained as follows:

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

 

2. process framework

Comparison, download, and install.

 

3. Version Check
Place the latest APK file on the server, such as http: // localhost/MyApp/myapp.apk.
At the same time, place the corresponding APK version information on the server to call the interface or file, for example, http: // localhost/MyApp/VER. JSON
The content in ver. JSON is:

[{"Appname": "jtapp12", "apkname": "jtapp-12-updateapksamples.apk", "vername": 1.0.1, "vercode": 2}]

Then, read and check the version on the mobile client:

    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 them.

If (getserververcode () {int vercode = config. getvercode (this); // use the method written in the previous section if (newvercode> vercode) {donewversionupdate (); // update the new version} else {notnewversionshow (); // The latest version is displayed }}

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 the latest version. No updates are required! "); Dialog = new alertdialog. builder (update. this ). settitle ("Software Update "). setmessage (sb. tostring () // sets the content. setpositivebutton ("OK", // set the OK button new dialoginterface. onclicklistener () {@ override public void onclick (dialoginterface dialog, int which) {finish ();}}). create (); // create // display the dialog box dialog. show ();} private void donewversionupdate () {int vercode = config. getvercode (this); string vername = Conf IG. getvername (this); stringbuffer sb = new stringbuffer (); sb. append ("current version:"); sb. append (vername); sb. append ("Code:"); sb. append (vercode); sb. append (", new version found:"); sb. append (newvername); sb. append ("Code:"); sb. append (newvercode); sb. append (", update? "); Dialog = new alertdialog. builder (update. this ). settitle ("Software Update "). setmessage (sb. tostring () // sets the content. setpositivebutton ("Update", // set the OK button new dialoginterface. onclicklistener () {@ override public void onclick (dialoginterface dialog, int which) {pbar = new progressdialog (update. this); pbar. settitle ("downloading"); pbar. setmessage ("Please wait... "); pbar. setprogressstyle (progressdialog. style_spinner); downfile (config. update_server + config. update_apkname );}}). setnegativebutton ("not updated now", new dialoginterface. onclicklistener () {public void onclick (dialoginterface Diener, int whichbutton) {// click the "cancel" button and exit the program finish ();}}). create (); // create // display the dialog box dialog. show ();}

 

4. Download Module

Note, this part refer to the previous implementation, see http://apps.hi.baidu.com/share/detail/24172508

    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();      }

After the download is completed, Handler notifies the main UI thread to cancel the download dialog box.

    void down() {              handler.post(new Runnable() {                  public void run() {                      pBar.cancel();                      update();                  }              });      }

5. Install the 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 an APK application to the market, you will find that a similar module is built in the market, which can automatically update or remind you whether to update the application. If your application needs to be updated automatically, is it more convenient to create one on your own? Most of the Code mentioned in this article is implemented in updateactivity. java. To make the update process more friendly, you can create a thread in the initial launcher activity to check whether the server has updates. When there is an update, start updateactivity, which makes the user experience smoother.

View/download the source code of this routine:
Http://code.google.com/p/androidex/source/browse/trunk/jtapp-12-updateapksamples

 

From: http://blog.csdn.net/xjanker2/archive/2011/04/06/6303937.aspx

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.