Android Launch page for version check update

Source: Internet
Author: User
Tags diff

1. Introduction module

Checkupdatelibrary's github address is as follows:

Https://github.com/qiangxi/CheckUpdateLibrary

Package download, copy the two folders under the file into the project's Extras folder,

The two modules are added to the project Setting.gradle.

Include': App',        ': Extras:okhttputils',        ': Extras:flycotablayout_lib',        ': Extras:viewpagerindicator_library',        ': Extras:checkupdatelib',        ': Extras:annotation'
Add in App folder under Build.gradle
Compile project (': extras:annotation') Compile project (': Extras: Checkupdatelib')
Then put Gradle sync now, if prompted GBK encoding error, in the app folder Build.gradle add

Results GBK the problem of error
Tasks.withtype (javacompile) {    "UTF-8"}
If you still get an error, add this to the Checkupdatelib,annotation two folder under Build.gradle.

In this way, the work of introducing the module has been completed. PS: The author of this stuff is a bit lazy, may also be more busy, may forget to upload the package. Ha ha. So everyone has to pay attention to his GitHub.

2. Key code
Version.json issued by the service side
{"code ":","msg ":" Success ","data ": {"appname ":" Teset ","filename ":" Skpda ","filepath ":"/demo.apk ","ImageUrl ":" Http://skpda.xxx.com/version/1520427805_108185.png ","isforceupdate ":" True ","newappsize ":" 4 ","Newappupdatedesc ":" 1. Update content 1/n2. Update content 23. Update Content 3 ","newappurl ":" http://skpda.xxx.com/version/app-debug.apk ","newappversionname ":" 3.0 ","notificationsuccesscontent ":" Prompt succeeds ","notificationfailurecontent ":" Prompt Failed ","notificationiconresid ":" ","notificationtitle ":" App has been updated "}}

In a word, this is mainly a local version of the Versionname and the server to fetch the versionname to compare, if the local than the remote value is smaller then the update prompt.

Key code 1, import content

Import Com.alibaba.fastjson.json;import Com.alibaba.fastjson.jsonobject;import Com.bumptech.glide.glide;import Com.qiangxi.checkupdatelibrary.checkupdateoption;import Com.qiangxi.checkupdatelibrary.callback.downloadcallback;import Com.qiangxi.checkupdatelibrary.callback.stringcallback;import Com.qiangxi.checkupdatelibrary.imageloader.imageloader;import COM.QIANGXI.CHECKUPDATELIBRARY.UTILS.L;

Key Code 2, one is the form must be appcompatactivity, the second is to introduce the module provides several interfaces, Stringcallback, Downloadcallback, Imageloader

class Splashactivity extends Appcompatactivity implements Stringcallback, Downloadcallback, Imageloader {...}

Key code 3, business functions-----The entry to perform this function

Public void Checkupdate (view view) {Map<String,String> params = new hashmap<>();Params.put ("key "," cacfae015af2ff98ce235bf4c5a4c662 ");//test pass//GET RequestQ.get (API, params). Callback (This). Execute ();//Test Pass//Direct DownloadQ.download (Download, PATH, NAME). Execute ();//Test Pass//DemoQ.show (this, generateoption (), this);//Test Pass//POST Request//q.post (API, params). Callback (This). Execute ();//Add the request address and the parameter Q.get (CONSTANTS.UPGRADE_API, params). ca Llback (This). Execute ();//Test Pass}

Key code 4, this activity to rewrite several interfaces provided by the method

@Override//Check the version to start executing content public void Checkupdatestart () {L.E ("checkupdatestart...+thread= "+ thread.currentthread ());} @Override//Check version execution failed execution content public void Checkupdatefailure (Throwable t) {L.E ("checkupdatefailure...+t= "+ t.tostring () +", thread= "+ thread.currentthread ());} @Override//Check the version to perform a check execution of the contents public void Checkupdatefinish () {L.E ("checkupdatefinish...+thread= "+ thread.currentthread ());} @Override//Check the version success, get the JSON information returned to the server, parse the JSON, start the next operation, that is, pop up the updated prompt window public void checkupdatesuccess (StringJSON) {L.E ("checkupdatesuccess...+json= "+ JSON +", thread= "+ thread.currentthread ());        StringCode ="";        Stringmsg ="";        Stringdata ="";try {jsonobject jsonobj=Json.parseobject (JSON); Code= Jsonobj.getstring ("code ");msg = Jsonobj.getstring ("msg ");data = Jsonobj.getstring ("data ");} catch (Exception e) {toast.maketext (Splashactivity.this,"the server has a communication error message: "+ MSG, Toast.length_short). Show ();} if (!code.equals ("200 ")) {Toast.maketext (Splashactivity.this,the serverAn error message occurred: "+ MSG, Toast.length_short)." Show ();} else {Upgradebean bean=json.parseobject (data, upgradebean.class); StringRemoteversionname =Bean.getnewappversionname (); StringLocalversionname =(New Upgradetool ()). Getversionname (this); StringLocalversioncode =Integer. ToString ((New Upgradetool ()). GetVersion (this)); LOG.E ("local version name ", localversionname);LOG.E ("local version number ", Localversioncode);LOG.E ("remote Version name ", remoteversionname);int flag=upgradetool.compareversion (Remoteversionname, localversionname);//compare local and Remote versions LOG.E ("comparison result "," checkupdatesuccess: "+ flag);if (Flag >0{q.show (this, generateoption (Bean), splashactivity.this);//test through generateoption (bean); } else {IsVersion=true;//Set version check work execution end flag startlogin ();///Execute entry to the next job}} }    //download the successful execution content @Override public void downloadprogress (LongCurrentlength,Longtotallength) {L.E ("downloadprogress...+currentlength= "+ currentlength +", totallength= "+ Totallength +", thread= "+ Thread.CurrentThread ());    }    //download failed execution @Override public void downloadsuccess (File apk) {L.E ("downloadsuccess...+apk.size= "+ apk.length () +", thread= "+ thread.currentthread ());    }    //Set picture @Override public void LoadImage (ImageView view,StringimageUrl)        {View.setscaletype (ImageView.ScaleType.FIT_XY);    Glide.with (this). Load (IMAGEURL). into (view); }

Key code 5, the option to construct an update hint Popup

 //set pop-up window content    Privatecheckupdateoption generateoption (Upgradebean mbean) {return NewCheckupdateoption.builder (). Setappname (Mbean.getappname ()). Setfilename ("/" +constants.upgrade_name). SetFilePath (Constants.upgrade_file_path). Setimageurl (mbean.ge                Timageurl ()). Setisforceupdate (Mbean.getforce ()). Setnewappsize (Mbean.getfloatnewappsize ())                . Setnewappupdatedesc (Mbean.getnewappupdatedesc ()). Setnewappurl (Mbean.getnewappurl ()) . Setnewappversionname (Mbean.getnewappversionname ()). Setnotificationsuccesscontent (Mbean.getNotifi                Cationsuccesscontent ()). Setnotificationfailurecontent (Mbean.getnotificationfailurecontent ())                . Setnotificationiconresid (R.mipmap.ic_launcher). Setnotificationtitle (Mbean.getnotificationtitle ())    . build (); }
This is basically done.
Add three functions: Get app Local version number, version name, compare two version name
  //get the app version number     Public intgetversion (Context context) {intVersion = 0; Try{version=Context.getpackagemanager (). Getpackageinfo (Context.getpackagename (),0). Versioncode; } Catch(Exception e) {System.out.println ("Get the version number exception!" "); }        returnversion; }    //get the app version name     Publicstring Getversionname (Context context) {string Versionname=NULL; Try{versionname=Context.getpackagemanager (). Getpackageinfo (Context.getpackagename (),0). Versionname; } Catch(Exception e) {System.out.println ("Get version name exception!" "); }        returnVersionname; }    /*** Compare the size of the version number * The former large returns a positive number * The latter large returns a negative number * equals returns 0 *@paramVersion1 the former *@paramVersion2 the latter *@return     */     Public Static intcompareversion (String version1, String version2) {if(Version1 = =NULL|| Version2 = =NULL) {            Throw NewRuntimeException ("The version number cannot be empty"); } string[] VersionArray1= Version1.split ("\ \");//Note that this is a regular match and cannot be used.;string[] VersionArray2 = version2.split ("\ \.")); intIDX = 0; intMinLength = Math.min (Versionarray1.length, versionarray2.length);//take the minimum length value        intdiff = 0;  while(IDX <MinLength&& (diff = versionarray1[idx].length ()-versionarray2[idx].length ()) = = 0//Compare length First&& (diff = versionarray1[idx].compareto (versionarray2[idx)) = = 0) {//Compare characters again++idx; }        //If the size has been divided, then the direct return, if the size is not, then compare the number of digits, there is a child version of the large;diff = (diff! = 0)? Diff:versionArray1.length-versionarray2.length; returndiff; }



Android Launch page for version check update

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.