Android App detects version updates with viewer mode

Source: Internet
Author: User

First step: Define the viewer

Public interface Checkversionobserver {/** * Detected version update succeeded in Mainactivity * @param mainentity */public void Onchecknewversucci Nmain (mainentity mainentity);/** * Detect new version failure * @param errorCode * @param msg */public void onchecknewverfail (int errorcode,s Tring msg);/** * Detect new version Success * @param token * @param msg */public void Onchecknewversucc (checkupdataentity newentity);/** * Detection To version can be upgraded and able to upgrade (contains memory card) * @param token * @param msg */public void Oncheckvercanupdate (String promt, String versionname);/** * Detected version can be upgraded, but not upgradeable (no memory card) */public void Oncheckvercannotupdate ();/** * Download failed * @param code * @param err */public void ONUPDA Teerror (string topic, String msg, string btnstr, final int type);/** * Updating download * @param totalsize * @param downsize */publi c void ondataupdating (int totalsize, int downsize);}

Step Two: Detect if the system version upgrades the logic

public class Checknewversionlogic extends Baselogic<checkversionobserver>implements updatedownloadresponse { Private Context mcontext;private Activity mactivity;private final static int download_update = 1;private final static int download_updating = 2;private final static int download_error = 3;public Handler mdownloadhandler;private String Downloadu Rl;private ProgressDialog mdialog = null;private int mdownfilesize = 0;private int mdownsize = 0;public CheckNewVersionLog IC () {}public checknewversionlogic (context context) {This.mcontext = Context;mactivity = (Activity) mcontext; Mdownloadhandler = new Downloadhandler ();} /** * Determine if the test update request was successful * * @param vercode */public void checknewversion (final String vercode) {new Backforetask (true) {Checku Pdataentity result = null, @Overridepublic void Onfore () {//TODO auto-generated method stubif (result = = null) {FIRECHECKN Ewversionfail ( -1, null);} else if (Result.getretcode ()! = 0) {firechecknewversionfail (Result.getretcode (), Result.getmessage ());} else {FIRECHECKNEWVERSIONSUCC (result);}} @Overridepublic void Onback () {//TODO auto-generated Method Stubresult = Protocolimpl.getinstance (). Checkversion ( Vercode);}};} /** * Main interface Check UPDATE * @param token * @param firstopen * @param mobiletype * @param mobilesys * @param vercode */public void Chec Knewverinmain (final int firstopen,final string mobiletype, final string mobilesys, final string vercode) {New Backforetask (true) {mainentity result = null; @Overridepublic void Onfore () {//TODO auto-generated method stubif (result = = null) {FIRECHECKN Ewversionfail ( -1, null);} else if (Result.getretcode ()! = 0) {firechecknewversionfail (Result.getretcode (), Result.getmessage ());} else { Firechecknewversuccinmain (result);}} @Overridepublic void Onback () {//TODO auto-generated Method Stubresult = Protocolimpl.getinstance (). Checkverinmain ( Firstopen, Mobiletype, Mobilesys, Vercode);}};} private void Firechecknewversuccinmain (mainentity mainentity) {list<checkversionobserver> tmpList = Getobservers (); foR (Checkversionobserver observer:tmplist) {observer.onchecknewversuccinmain (mainentity);}} /** * Version update request failed * * @param errorCode * @param msg */private void firechecknewversionfail (int errorCode, String msg) {list& Lt checkversionobserver> tmplist = Getobservers (); for (Checkversionobserver observer:tmplist) { Observer.onchecknewverfail (ErrorCode, MSG);}} /** * Version update request succeeded * * @param newentity */private void firechecknewversionsucc (checkupdataentity newentity) {List<checkver sionobserver> tmplist = Getobservers (); for (Checkversionobserver observer:tmplist) {OBSERVER.ONCHECKNEWVERSUCC ( newentity);}} /** * Detected version can be upgraded and can upgrade (contains memory card) * * @param promt * @param versionname */private void Firecheckvercanupdate (String promt, St Ring versionname) {list<checkversionobserver> tmplist = Getobservers (); for (Checkversionobserver Observer: Tmplist) {observer.oncheckvercanupdate (promt, Versionname);}} /** * Detected version can be upgraded, but cannot be upgraded (no memory card) */private void Firecheckvercannotupdate () {List<checkversionobserver> tmplist = Getobservers (); for (Checkversionobserver observer:tmplist) {observer.oncheckvercannotupdate ();}} /** * Download Failed * * @param code * @param err */private void Fireonerror (String topic, String msg, string btnstr,final int type ) {list<checkversionobserver> tmplist = Getobservers (); for (Checkversionobserver observer:tmplist) { Observer.onupdateerror (topic, MSG, BTNSTR, type);}} /** * Downloading * * @param totalsize * @param downsize */private void fireondataupdating (int downfilesize, int downsize) {List <CheckVersionObserver> tmplist = Getobservers (); for (Checkversionobserver observer:tmplist) { Observer.ondataupdating (downfilesize, downsize);}} /** * Download update */public void Downloadupdate () {mdownloadhandler.sendemptymessage (download_update);} /** * Downloading Updates * * @param totalsize * @param downsize */public void downloadupdating (int totalsize, int downsize) {Mdownfil Esize = Totalsize;mdownsize = Downsize;mdownloadhandler.sendemptymessage (download_updating);} /** * Download Failed */pubLIC void Downloaderror () {mdownloadhandler.sendemptymessage (download_error);} /*** * Select whether to update version */public void checkversion (int serververcode, String promt, String versionname, string url) {log.i ("Ciyunu Pdate ", Serververcode +" "); System.out.println ("Serververcode" + serververcode); int appvercode = 1;try {Appvercode = Mcontext.getpackagemanager (). Getpackageinfo (Mcontext.getpackagename (), 0). Versioncode; LOG.I ("Ciyunupdate", Appvercode + ""); System.out.println ("Appvercode" + Appvercode);} catch (Namenotfoundexception e) {e.printstacktrace ();} if (Serververcode > Appvercode) {if (! Fileutil.issdcardexist ()) {/* * ShowDialog (mcontext.getstring (r.string.str_version_update), * mcontext.getresources (). getString (R.string.no_sdcard), * mcontext.getresources (). getString (R.string.sure), 0); */firecheckvercannotupdate ();} else {//Popupdatedlg (promt,versionname);d Ownloadurl = Url;firecheckvercanupdate (promt, Versionname);}}} /** * * @Description: Download Update processor * @author: * @see: * @since: * @copyright ©ciyun.cn * @Date: August 12, 2014 */private class Downloadhandler extends Handler {/** * {@inheritDoc} * * @see Android.os.Handler #handleMessage (android.os.Message) */@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Switch (msg.what) {case download_update: {new Thread () {@Overridepublic void run () {super.run (); if ( Utils.isexternalstorageremovable ()) {Fileutil.createfileex (healthapplication.updatafilename); Httppostengine service = new Httppostengine (); Service.downloadupdatefile (Checknewversionlogic.this,downloadurl, FileUtil.updateFile.getPath ());}}. Start ();} Break;case download_updating:fireondataupdating (mdownfilesize, mdownsize); Break;case DOWNLOAD_ERROR:fireOnError ( Mcontext.getstring (R.string.str_version_update), mcontext.getstring (R.string.str_download_err), Mcontext.getresources (). getString (R.string.sure), 0); break;}}}  @Overridepublic void OnError (int code, String err) {//TODO auto-generated method stublog.v ("Update", Code + "/" + err); (Mdialog! = null &&Mdialog.isshowing ()) {Mdialog.dismiss ();} Mdownloadhandler.sendemptymessage (download_error);} @Overridepublic void ondataupdated (int totalsize, int downsize) {//TODO auto-generated method stubmdownfilesize = Totalsi Ze;mdownsize = Downsize;mdownloadhandler.sendemptymessage (download_updating);} @Overridepublic void Onupdatedfinish () {//TODO auto-generated method Stuburi uri = Uri.fromfile (fileutil.updatefile); Ntent Intent = new Intent (Intent.action_view); Intent.setdataandtype (URI, "application/vnd.android.package-archive") ; mactivity.startactivity (intent);}}

Step three: Write the following code in the main interface button event:
Checknewversionlogic checknewversionlogic = new Checknewversionlogic (aboutappactivity.this); Checknewversionlogic.checknewversion (Vercode + "");

The fourth step: the main interface class to implement Checkversionobserver, and implement the following methods:

void ShowDialog (String topic, String msg, string btnstr, final int type) {Alertdialog.builder Builder = new Alertdialog.bu Ilder (this); Builder.seticon (Android. R.drawable.ic_dialog_info); builder.settitle (topic); Builder.setmessage (msg); Builder.setnegativebutton (BTNSTR, New Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {Dialog.dismiss (); Type = = 1) {AboutAppActivity.this.finish ();} else {}}}); builder.setcancelable (false); Builder.create (). Show (); private void Popupdatingdlg (long totalsize) {if (Mdialog = = null) {Mdialog = new ProgressDialog (this); Mdialog.setmax (100) ; String size = (totalsize*0.000001 + ""). Substring (0, 4); Mdialog.settitle (Getresources (). getString (R.string.now_ loading_new_version) (+size+ "M)"); Mdialog.setprogressstyle (progressdialog.style_horizontal); Mdialog.setcanceledontouchoutside (false); Mdialog.setonkeylistener (new Onkeylistener () {@Overridepublic Boolean OnKey (dialoginterface dialog, int keycode,keyevent event) {if (keycode = = Keyevent.keycode_search) | | (keycode = = Keyevent.keycode_back)) {return true;} return false;}}); Mdialog.setcancelable (false); Mdialog.show ();}} @Overridepublic void Oncheckvercanupdate (String promt, String versionname) {//TODO auto-generated method Stubpopupdatedlg (promt,versionname);} @Overridepublic void Oncheckvercannotupdate () {//TODO auto-generated method Stubshowdialog (getString (r.string.str_ Version_update), Getresources (). getString (R.string.no_sdcard), Getresources (). getString (R.string.sure), 0);} @Overridepublic void Onupdateerror (String topic, String msg, string btnstr, int type) {//TODO auto-generated method stubs Howdialog (topic,msg, btnstr, type);} @Overridepublic void ondataupdating (int totalsize, int downsize) {//TODO auto-generated method Stubpopupdatingdlg ( TotalSize); if (mdialog! = null && mdialog.isshowing ()) {if (Downsize < totalsize) {mdialog.setprogress ( downsize*100/totalsize);} else {Mdialog.dismiss ();}}} @Overridepublic void Onchecknewverfail (int errorCode,String msg) {//TODO auto-generated method Stubhalotoast.dismisswaitdialog ();//Close the Prompt box if (! Textutils.isempty (msg)) Toast.maketext (this, MSG, up). Show (); if (ErrorCode = =) {Intent Intent = new Intent ( Aboutappactivity.this,loginactivity.class); startactivity (intent);} if (Textutils.isempty (msg)) {Toast.maketext (this, r.string.str_network_error_msg,.). Show ();}} @Overridepublic void Onchecknewversucc (checkupdataentity newentity) {//TODO auto-generated method Stubhalotoast.dismisswaitdialog (); if (newentity.getretcode () = = 0) {HealthApplication.mUserCache.setToken ( Newentity.gettoken ()); if (Newentity.getdata ()!=null) {int serververcode = Newentity.getdata (). Getvercode (); String prompt = Newentity.getdata (). GetMessage (); String vername = Newentity.getdata (). Getvername (); checknewversionlogic.checkversion (Serververcode, prompt, VerName, Newentity.getdata (). Getappurl ());}} @Overridepublic void Onchecknewversuccinmain (mainentity mainentity) {//TODO auto-generated method stub}

The fifth step: Some of the network methods used:

/** * Detection System Version Upgrade * @param vercode * @return */public checkupdataentity checkversion (String vercode) {Jsonobject j = Httpjsonr Equesproxy.getinstance (). Getcheckverreques (Vercode); String jsondata=null;try {jsondata = Httputil.senddatatoserver (Lovehealthconstant.hosturl, j.toString ());} catch ( Exception e) {e.printstacktrace ();} if (jsondata==null) {return null;} Return Jsonutil.parse (Jsondata, checkupdataentity.class);} /** * Main interface Detection system version upgrade * @param token * @param firstopen * @param mobiletype * @param mobilesys * @param vercode * @return * * Public mainentity checkverinmain (int firstopen,string mobiletype, string Mobilesys, String vercode) {Jsonobject j = HttpJs Onrequesproxy.getinstance (). Gethomepagereques (Firstopen, Mobiletype, Mobilesys, Vercode); String jsondata=null;try {jsondata = Httputil.senddatatoserver (Lovehealthconstant.hosturl, j.toString ());} catch ( Exception e) {e.printstacktrace ();} if (jsondata==null) {return null;} Return Jsonutil.parse (Jsondata, mainentity.class);}

/** * Version Updated *  * @param token * @param vercode * @return */public jsonobject getcheckverreques (String vercode) {Jsonobje CT title = Getcontextjsonobj ("CheckUp"); try {//Another JSON object requires a new jsonobject Mqrinfo = new Jsonobject (); Mqrinfo.put (" Vercode ", vercode);//Add user and code values to the entire JSON title.put (" data ", Mqrinfo);} catch (Jsonexception e) {//key is NULL or use JSON unsupported number format (NaN, infinities) throw new RuntimeException (e);} return title;}

/** * Home * *  @param token * @param firstopen * @param mobiletype * @param mobilesys * @param vercode * @return */publi C jsonobject gethomepagereques (int firstopen,string mobiletype, string Mobilesys, String vercode) {jsonobject title = GetC Ontextjsonobj ("homepage"); try {//Another JSON object requires a new jsonobject Mqrinfo = new Jsonobject (); Mqrinfo.put ("Firstopen", Firstopen) mqrinfo.put ("Mobiletype", Mobiletype); Mqrinfo.put ("Mobilesys", Mobilesys); Mqrinfo.put ("Vercode", Vercode);//Add user and code values to the entire JSON title.put ("data", Mqrinfo);} catch (Jsonexception e) {//key is NULL or use JSON unsupported number format (NaN, infinities) throw new RuntimeException (e);} return title;}

public string senddatatoserver (string URL, String body) throws Exception {HttpPost HttpPost = new HttpPost (URL); Bytearrayentity postdata = new Bytearrayentity (Body.getbytes ()); httppost.setentity (postdata); int res = 0; Httpparams httpparameters = new Basichttpparams (); Httpconnectionparams.setconnectiontimeout (Httpparameters, time_out); Httpconnectionparams.setsotimeout (Httpparameters, time_out);D efaulthttpclient httpClient = new Defaulthttpclient ( Httpparameters); HttpResponse HttpResponse = Httpclient.execute (httppost); res = Httpresponse.getstatusline (). GetStatusCode (); if (res = = $) {String result = entityutils.tostring (httpresponse.getentity ()); XLOG.D ("result==", result); return result;} return null;}






Android App detects version updates with viewer mode

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.