Add the automatic version update function for the program + detailed analysis)

Source: Internet
Author: User
Tags time in milliseconds

Overview:

Check whether the program is up-to-date every day through the backgroundVersion

To update the currentVersion

In the displayed dialog box, select whether to update the software in the current market.
Knowledge points:

  • Sharedpreferences: a lightweight storage method, similar to a frequently used. ini file, it also retrieves corresponding values by retrieving keywords. The reason why it becomes lightweight is that it can apply only a limited number of numeric types and has a relatively low efficiency for storing large numeric values. Official reference
  • System. currenttimemillis: represents the current time in milliseconds and is used to compare the order of two times. (The value indicates the total number of milliseconds from 00:00:00 till the current time) official reference
  • Read information through the network: The checkupdate () method contains a URL to read network resources. For detailed operation steps, see source code.
  • Runnable: implements any code to be executed in its internal run () method. When this runnable interface is called, it can be regarded as a new thread.

Source code:

  1. Public class Hello extends activity {
  2. /** Called when the activity is first created .*/
  3. Private handler mhandler;
  4. @ Override
  5. Public void oncreate (bundle savedinstancestate ){
  6. Super. oncreate (savedinstancestate );
  7. Setcontentview (R. layout. Main );
  8. Mhandler = new handler ();
  9. /* Get last update time from preferences */
  10. Sharedpreferences prefs = getpreferences (0 );
  11. Long lastupdatetime = prefs. getlong ("lastupdatetime", system. currenttimemillis ());
  12. Int curversion = 0;
  13. Try {
  14. Curversion = getpackagemanager (). getpackageinfo ("linhai.com. Hello", 0). versioncode;
  15. } Catch (namenotfoundexception e ){
  16. // Todo auto-generated Catch Block
  17. E. printstacktrace ();
  18. }
  19. Log. I ("Demo", String. valueof (curversion ));
  20. /* Shocould activity check for updates now? */
  21. If (lastupdatetime + (24x60*60*1000) <system. currenttimemillis ()){
  22. /* Save current timestamp for next check */
  23. Lastupdatetime = system. currenttimemillis ();
  24. Sharedpreferences. Editor editor = getpreferences (0). Edit ();
  25. Editor. putlong ("lastupdatetime", lastupdatetime );
  26. Editor. Commit ();
  27. /* Start update */
  28. // Checkupdate. Start ();
  29. }
  30. }
  31. /* This thread checks for updates in the background */
  32. Private thread checkupdate = new thread ()
  33. {
  34. Public void run (){
  35. Try {
  36. URL updateurl = new URL ("http://my.company.com/update ");
  37. Urlconnection conn = updateurl. openconnection ();
  38. Inputstream is = conn. getinputstream ();
  39. Bufferedinputstream Bis = new bufferedinputstream (is );
  40. Bytearraybuffer BAF = new bytearraybuffer (50 );
  41. Int current = 0;
  42. While (current = bis. Read ())! =-1 ){
  43. BAF. append (byte) Current );
  44. }
  45. /* Convert the bytes read to a string .*/
  46. Final string S = new string (BAF. tobytearray ());
  47. /* Get current version number */
  48. Int curversion = getpackagemanager (). getpackageinfo ("Your. App. ID", 0). versioncode;
  49. Int newversion = integer. valueof (s );
  50. /* Is a higher version than the current already out? */
  51. If (newversion> curversion ){
  52. /* Post a handler for the UI to pick up and open the dialog */
  53. Mhandler. Post (showupdate );
  54. }
  55. } Catch (exception e ){
  56. }
  57. }
  58. };
  59. /* This runnable creates a dialog and asks the user to open the market */
  60. Private runnable showupdate = new runnable (){
  61. Public void run (){
  62. New alertdialog. Builder (hello. This)
  63. . Seticon (R. drawable. OK)
  64. . Settitle ("update available ")
  65. . Setmessage ("an update for is available! /N/nopen Android Market and see the details? ")
  66. . Setpositivebutton ("yes", new dialoginterface. onclicklistener (){
  67. Public void onclick (dialoginterface dialog, int whichbutton ){
  68. /* User clicked OK so do some stuff */
  69. Intent intent = new intent (intent. action_view, Uri. parse ("Market: // search? Q = pname: Your. App. ID "));
  70. Startactivity (intent );
  71. }
  72. })
  73. . Setnegativebutton ("no", new dialoginterface. onclicklistener (){
  74. Public void onclick (dialoginterface dialog, int whichbutton ){
  75. /* User clicked cancel */
  76. }
  77. })
  78. . Show ();
  79. }
  80. };
  81. }

Copy code

There are three parts:

  • Programs placed in the oncreate () method are used to determine whether update needs to be checked for the current time (if the last update time is greater than one day, check for updates will be started)
  • When the preceding conditions are met, start checkupdate to check whether the current program is up to date.Version

    .
  • If you are sureVersion

    If it has expired, you will log on to the market and direct it to the current program page.

**************************************** **************************************** ***********
Up:
I have posted a help post on this issue in the forum. Although the idea is similar to the above, the key point is how to update the program, now we can see that the update method mentioned here is actually logging on to the market. However, all the programs released later are in the market, and the problem does not exist.

  1. Intent intent = new intent (intent. action_view, Uri. parse ("Market: // search? Q = pname: Your. App. ID "));
  2. Startactivity (intent );

Copy code

Everyone is developing it on Eclipse. Do you notice the console prompt every time you update the code and run the simulator:

  1. [19:53:50-Hello] Android launch!
  2. [19:53:50-Hello] ADB is running normally.
  3. [19:53:50-Hello] Ming linhai.com. Hello. Hello activity launch
  4. [19:53:50-Hello] Automatic Target mode: using existing emulator 'emulator-5554 'running compatible avd'
  5. [19:53:50-Hello] Warning: application does not specify an API level requirement!
  6. [19:53:50-Hello] device API version is 3 (Android 1.5)
  7. [5554 19:53:50-Hello] uploading hello.apk onto device 'emulator-100'
  8. [19:53:50-Hello] installing hello.apk...
  9. [19:54:05-Hello] application already exists. Attempting to re-install instead...
  10. [19:54:31-Hello] success!

Copy code

Analysis:
1. Android running properly
2. Run our program in the configuration file androidmanifest. xml.
3. Uploading hello.apk onto device 'emulator-100'
This is the key. update our program.
4. Installing hello.apk...

5. Application already exists. Attempting to re-install instead...
// The program already exists. Try to reinstall it.

So if our program needs to be updated automatically, I guess it is the same as the above steps.
For details, see the log in logcat.

  1. 06-06 11:54:02. 567: Debug/packageparser (582): scanning package:/data/APP/vmdl12464.tmp
  2. 06-06 11:54:08. 048: INFO/packagemanager (582): removing non-system package: linhai.com. Hello
  3. 06-06 11:54:08. 187: Debug/packagemanager (582): removing package linhai.com. Hello
  4. 06-06 11:54:08. 286: Debug/packagemanager (582): Activities: linhai.com. Hello. Hello
  5. 06-06 11:54:11. 136: Debug/packagemanager (582): scanning package linhai.com. Hello
  6. 06-06 11:54:11. 301: INFO/packagemanager (582):/data/APP/vmdl12464.tmp changed; unpacking
  7. 06-06 11:54:11. 626: Debug/installd (555): dexinv: --- begin '/data/APP/vmdl12464.tmp '---
  8. 06-06 11:54:12. 987: Debug/dalvikvm (7756): dexopt: Load 224 ms, verify 265 ms, OPT 1 ms
  9. 06-06 11:54:13. 047: Debug/installd (555): dexinv: --- end '/data/APP/vmdl12464.tmp' (SUCCESS )---
  10. 06-06 11:54:13. 057: Debug/packagemanager (582): Activities: linhai.com. Hello. Hello
  11. 06-06 11:54:15. 608: INFO/installd (555): Move
    /Data/Dalvik-Cache/Data @ app@vmdl12464.tmp @ classes. Dex->
    /Data/Dalvik-Cache/data@app@linhai.com.hello.apk @ classes. Dex
  12. 06-06 11:54:15. 737: Debug/packagemanager (582): new package installed in/data/APP/linhai.com.hello.apk

Copy code

The third-party management software for such Automatic Updates has been calledAtrackdog
The principle is to use the above method.
About getVersion

Number, use:

  1. Int curversion = getpackagemanager (). getpackageinfo ("Your. App. ID", 0). versioncode;

Copy code

ProgramVersion

In the androidmanifest. xml file:

  1. <Manifest xmlns: Android = "http://schemas.android.com/apk/res/android"
  2. Package = "linhai.com. Hello" Android: versioncode = "2" Android: versionname = "2.0.1">

Copy code

The main point is about getpackagemanager (). There are many methods in this section. You can use it to obtain the programs installed on the current terminal. The Installation Package function is getpackagemanager (). installpackage (packageuri)

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.