Complete implementation solution + reference program for the automatic upgrade and update modules of Android applications

Source: Internet
Author: User
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. First, the interface effect is provided:

1. Preparation knowledge
The version ID of each android APK is defined in androidmanifest. xml:

  1. <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
  2. Package = "com. MyApp"
  3. Android: versioncode = "1"
  4. Android: versionname = "1.0.0">
  5. <Application> </Application>
  6. </Manifest>

Copy code

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:

  1. Public static int getvercode (context ){
  2. Int vercode =-1;
  3. Try {
  4. Vercode = context. getpackagemanager (). getpackageinfo (
  5. "Com. MyApp", 0). versioncode;
  6. } Catch (namenotfoundexception e ){
  7. Log. E (TAG, E. getmessage ());
  8. }
  9. Return vercode;
  10. }
  11. Public static string getvername (context ){
  12. String vername = "";
  13. Try {
  14. Vername = context. getpackagemanager (). getpackageinfo (
  15. "Com. MyApp", 0). versionname;
  16. } Catch (namenotfoundexception e ){
  17. Log. E (TAG, E. getmessage ());
  18. }
  19. Return vername;
  20. }

Copy code

You can also write Android: versionname = "1.2.0" in androidmanifest 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:

  1. Public static string getvername (context ){
  2. String vername = context. getresources ()
  3. . Gettext (R. String. app_versionname). tostring ();
  4. Return vername;
  5. }

Copy code

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

  1. Public static string getappname (context ){
  2. String vername = context. getresources ()
  3. . Gettext (R. String. app_name). tostring ();
  4. Return vername;
  5. }

Copy code

2. process framework

 

 

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:

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

Copy code

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

  1. Private Boolean getserverver (){
  2. Try {
  3. String verjson = networktool. getcontent (config. update_server
  4. + Config. update_verjson );
  5. Jsonarray array = new jsonarray (verjson );
  6. If (array. Length ()> 0 ){
  7. Jsonobject OBJ = array. getjsonobject (0 );
  8. Try {
  9. Newvercode = integer. parseint (obj. getstring ("vercode "));
  10. Newvername = obj. getstring ("vername ");
  11. } Catch (exception e ){
  12. Newvercode =-1;
  13. Newvername = "";
  14. Return false;
  15. }
  16. }
  17. } Catch (exception e ){
  18. Log. E (TAG, E. getmessage ());
  19. Return false;
  20. }
  21. Return true;
  22. }

Copy code

Compare the server and client versions and update them.

  1. If (getserververcode ()){
  2. Int vercode = config. getvercode (this); // use the method written in the first section.
  3. If (newvercode> vercode ){
  4. Donewversionupdate (); // update the new version
  5. } Else {
  6. Notnewversionshow (); // The latest version is displayed.
  7. }
  8. }

Copy code

Detailed method:

  1. Private void notnewversionshow (){
  2. Int vercode = config. getvercode (this );
  3. String vername = config. getvername (this );
  4. Stringbuffer sb = new stringbuffer ();
  5. SB. append ("current version :");
  6. SB. append (vername );
  7. SB. append ("Code :");
  8. SB. append (vercode );
  9. SB. append (", \ n is the latest version, no need to update! ");
  10. Dialog dialog = new alertdialog. Builder (update. This). settitle ("Software Update ")
  11. . Setmessage (sb. tostring () // sets the content
  12. . Setpositivebutton ("OK", // set the OK button
  13. New dialoginterface. onclicklistener (){
  14. @ Override
  15. Public void onclick (dialoginterface dialog,
  16. Int which ){
  17. Finish ();
  18. }
  19. }). Create (); // create
  20. // Display dialog box
  21. Dialog. Show ();
  22. }
  23. Private void donewversionupdate (){
  24. Int vercode = config. getvercode (this );
  25. String vername = config. getvername (this );
  26. Stringbuffer sb = new stringbuffer ();
  27. SB. append ("current version :");
  28. SB. append (vername );
  29. SB. append ("Code :");
  30. SB. append (vercode );
  31. SB. append (", new version found :");
  32. SB. append (newvername );
  33. SB. append ("Code :");
  34. SB. append (newvercode );
  35. SB. append (", update? ");
  36. Dialog dialog = new alertdialog. Builder (update. This)
  37. . Settitle ("Software Update ")
  38. . Setmessage (sb. tostring ())
  39. // Set content
  40. . Setpositivebutton ("Update", // set the OK button
  41. New dialoginterface. onclicklistener (){
  42. @ Override
  43. Public void onclick (dialoginterface dialog,
  44. Int which ){
  45. Pbar = new progressdialog (update. This );
  46. Pbar. settitle ("downloading ");
  47. Pbar. setmessage ("Please wait ...");
  48. Pbar. setprogressstyle (progressdialog. style_spinner );
  49. Downfile (config. update_server + config. update_apkname );
  50. }
  51. })
  52. . Setnegativebutton ("not updated now ",
  53. New dialoginterface. onclicklistener (){
  54. Public void onclick (dialoginterface dialog,
  55. Int whichbutton ){
  56. // Click "cancel" to exit the program
  57. Finish ();
  58. }
  59. }). Create (); // create
  60. // Display dialog box
  61. Dialog. Show ();
  62. }

Copy code

4. Download Module

  1. Void downfile (final string URL ){
  2. Pbar. Show ();
  3. New thread (){
  4. Public void run (){
  5. Httpclient client = new defaulthttpclient ();
  6. Httpget = new httpget (URL );
  7. Httpresponse response;
  8. Try {
  9. Response = client.exe cute (get );
  10. Httpentity entity = response. getentity ();
  11. Long length = entity. getcontentlength ();
  12. Inputstream is = entity. getcontent ();
  13. Fileoutputstream = NULL;
  14. If (is! = NULL ){
  15. File file = new file (
  16. Environment. getexternalstoragedirectory (),
  17. Config. update_savename );
  18. Fileoutputstream = new fileoutputstream (File );
  19. Byte [] Buf = new byte [1, 1024];
  20. Int CH =-1;
  21. Int COUNT = 0;
  22. While (CH = is. Read (BUF ))! =-1 ){
  23. Fileoutputstream. Write (BUF, 0, CH );
  24. Count + = CH;
  25. If (length> 0 ){
  26. }
  27. }
  28. }
  29. Fileoutputstream. Flush ();
  30. If (fileoutputstream! = NULL ){
  31. Fileoutputstream. Close ();
  32. }
  33. Down ();
  34. } Catch (clientprotocolexception e ){
  35. E. printstacktrace ();
  36. } Catch (ioexception e ){
  37. E. printstacktrace ();
  38. }
  39. }
  40. }. Start ();
  41. }

Copy code

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

  1. Void down (){
  2. Handler. Post (New runnable (){
  3. Public void run (){
  4. Pbar. Cancel ();
  5. Update ();
  6. }
  7. });
  8. }

Copy code

5. Install the application

  1. Void Update (){
  2. Intent intent = new intent (intent. action_view );
  3. Intent. setdataandtype (URI. fromfile (new file (Environment
  4. . Getexternalstoragedirectory (), config. update_savename )),
  5. "Application/vnd. Android. Package-Archive ");
  6. Startactivity (intent );
  7. }

Copy code

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.

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.