The program is always updated, Apple and other AppStore processing, the Android version of the automatic Update, on the code
/** * Check and update app */(function (Cordova) {var define = Cordova.define; Define ("Cordova/plugin/updateapp", function (require, exports, module) {var Argscheck = require (' Cordova/argscheck '), exec = require (' cordova/exec '); Exports.checkandupdate = function (content, SUCCESSCB, FAILCB) {exec (SUCCESSCB, FAILCB, "Updateapp", "Checkand Update ", content); }; Exports.getcurrentversion = function (SUCCESSCB, FAILCB) {exec (SUCCESSCB, FAILCB, "Updateapp", "getcurrentvers Ion ", []); } exports.update = function (Downurl, SUCCESSCB, FAILCB) {exec (SUCCESSCB, FAILCB, "Updateapp", "Update" , [Downurl]); } }); Cordova.addconstructor (function () {if (!window.plugins) {window.plugins = {}; } console.log ("Inject plug-in cordovaupdateapp ..."); WINDOW.PLUGINS.UPDATEAPP = Cordova.require ("Cordova/plugin/updateapp"); Console.log ("Updateapp injection Result:" + typeof (Window.plugins.updateApp)); });}) (Cordova);
<feature name= "Updateapp" ><param name= "Android-package" value= "package name. Updateappplugin "/></feature>
public class Updateappplugin extends Cordovaplugin {/* version number check path */private String checkpath;/* new version number */private int Newvercode ;/* New version name */private string newvername= "yooshownewversion";/* APK download path */private String downloadpath;/* download */private Stati c final int DOWNLOAD = 1;/* Download end */private static final int download_finish = 2;/* Download save path */private String msavepath;/* record Number of progress bars */private int progress;/* whether to cancel update */private Boolean cancelupdate = false;/* context */private Contextual mcontext;/* update progress bar * /private ProgressBar mprogress;private Dialog mdownloaddialog;private progressdialog pd = NULL; String update_serverapk = "yooshowupdate.apk"; @Overridepublic Boolean execute (String action, Jsonarray args, Callbackcontext Callbackcontext) throws jsonexception {This.mcontext = cordova.getactivity (); if (Action.equals (" Checkandupdate ")) {log.i (" our "," Check Version "), This.checkpath = args.getstring (0); Checkandupdate ();} else if (Action.equals ( "Getcurrentversion")) {//optimize to shorten the transmission content, reduce the flow//Jsonobject obj = new Jsonobject ();//Obj.put ("Versioncode", This.getcurrentvercode ());//Obj.put ("Versionname", This.getcurrentvername ()); Callbackcontext.success (This.getcurrentvercode () + "");} else if (action.equals ("Getserverversion")) {This.checkpath = args.getstring (0); if (This.getserververinfo ()) {//optimization Shorten the transmission of content, reduce traffic//jsonobject obj = new Jsonobject ();//Obj.put ("Serverversioncode", newvercode);//Obj.put (" Serverversionname ", newvername); Callbackcontext.success (Newvercode +" ");} else {callbackcontext.error ("can ' t connect to the Server!please check [Checkpath]");}} else if (action.equals ("Update")) {This.downloadpath = args.getstring (0); Showdownloaddialog ();} return false;} /** * Check for updates */private void Checkandupdate () {if (Getserververinfo ()) {int currentvercode = Getcurrentvercode (); if (Newverco De > Currentvercode) {this.shownoticedialog ();}}} /** * Get app Current Version code * * @param context * @return */private int getcurrentvercode () {String PackageName = This.mContext.getPa Ckagename (); int currentver = -1;try {currentver = this.Mcontext.getpackagemanager (). Getpackageinfo (PackageName, 0). Versioncode;} catch (Namenotfoundexception e) {e.printstacktrace ();} return currentver;} /** * Get app Current version name * * @param context * @return */private string Getcurrentvername () {String packagename = this.mContext.ge Tpackagename (); String currentvername = ""; try {currentvername = This.mContext.getPackageManager (). Getpackageinfo (PackageName, 0). Versionname;} catch (Namenotfoundexception e) {e.printstacktrace ();} return currentvername;} /** * Get App Name * * @param context * @return */private String getappname () {return this.mContext.getResources (). GetText (R.st Ring.app_name). toString ();} /** * Get version information on the server * * @param path * @return * @throws Exception */private boolean getserververinfo () {try {StringBuilder Verinfostr = new StringBuilder (); URL url = new URL (checkpath); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setconnecttimeout (conn.setreadtimeout); (Conn.connect); BufferedReader reader = new BufferedReader(New InputStreamReader (Conn.getinputstream (), "UTF-8"), 8192); String line = null;while (line = Reader.readline ())! = null) {Verinfostr.append (line + "\ n");} Reader.close (); Jsonarray array = new Jsonarray (verinfostr.tostring ()), if (Array.Length () > 0) {jsonobject obj = array.getjsonobject (0 ); Newvercode = Obj.getint ("Vercode"); newvername = obj.getstring ("Vername");d Ownloadpath = obj.getstring ("ApkPath"); LOG.I ("Our", Newvercode + newvername + Downloadpath);}} catch (Exception e) {e.printstacktrace (); return false;} return true;} /** * Show software Updates dialog box */private void Shownoticedialog () {//construct dialog Alertdialog.builder builder = new Builder (mcontext); builder.se Ttitle ("Software Update"); Builder.setmessage ("New version needs to be updated");//Update Builder.setpositivebutton ("OK", new Onclicklistener () {public void OnClick (Dialoginterface dialog, int which) {//Dialog.dismiss ();//Display Download dialog box Showdownloaddialog ();}); /Update Builder.setnegativebutton later ("Cancel", new Onclicklistener () {public void OnClick (Dialoginterface dialog, int which) { Dialog.dismISS ();});D Ialog Noticedialog = Builder.create (); Noticedialog.show ();} /** * Show software download dialog box */private void Showdownloaddialog () {PD = new ProgressDialog (mcontext);pd. Settitle ("Downloading"); Pd.setmessage ("Please later ...");pd. Setprogressstyle (progressdialog.style_horizontal);pd. Setcancelable (false);// Sets whether the progress bar can press the bounce key to cancel//set the area outside the Click Progress dialog box does not disappear Pd.setcanceledontouchoutside (false);d ownloadapk ();} /** * Download apk file */private void downloadapk () {//start new thread download software//New Downloadapkthread (). Start ();d ownfile (Downloadpath);} Private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {//is downloading case DOWNLOAD: Set the progress bar position//mprogress.setprogress (progress); Pd.setprogress (progress); break;case download_finish://installation file//installapk (); update (); break;default:break;}};};/ * * Download file thread */private class Downloadapkthread extends thread {@Overridepublic void run () {try {//To determine if the SD card exists and has read and write permissions if ( Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//Get the path to the memory card string Sdpath = Environment.getextErnalstoragedirectory () + "/"; Msavepath = Sdpath + "Download"; URL url = new URL (downloadpath);//Create connection HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.connect () ;//Get file size int length = Conn.getcontentlength ();//Create input stream InputStream is = Conn.getinputstream (); File File = new file (msavepath);//Determine if the directory exists if (!file.exists ()) {File.mkdir ();} File Apkfile = new file (Msavepath, newvername); FileOutputStream fos = new FileOutputStream (apkfile); int count = 0;//cache byte buf[] = new byte[1024];//write to file do {int numre AD = Is.read (BUF); count + = numread;//Calculate progress bar Position progress = (int) ((float) count/length) * 100);//Update Progress Mhandler.sendemptyme Ssage (DOWNLOAD); if (numread <= 0) {//Download complete mhandler.sendemptymessage (download_finish); break;} Write file Fos.write (buf, 0, numread);} while (!cancelupdate);//Click Cancel to stop the download. Fos.close (); Is.close ();}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} The Cancel Download dialog box displays Mdownloaddialog.dismiss ();}};/ * * Install APK file */private void installapk () {File apkfile = new File (Msavepath, newvername); if (!apkfile.exists ()) {return;} Install apk file via Intent Intent i = new Intent (Intent.action_view); I.setdataandtype (Uri.parse ("file://" + apkfile.tostring () ), "application/vnd.android.package-archive"); mcontext.startactivity (i);} /** * Download apk */public void downfile (final String URL) {pd.show (); new Thread () {public void run () {HttpClient client = new D Efaulthttpclient (); 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 (), UPDATE_SERVERAPK); fileoutputstream = new FileOutputStream (file); byte[] B = new Byte[1024];int Charb = -1;int count = 0;whi Le ((Charb = Is.read (b))! =-1) {fileoutputstream.write (b, 0, Charb); count + = Charb;progress = (int) ((float) count/leNGTH) * 100);//Update Progress Mhandler.sendemptymessage (DOWNLOAD); }}fileoutputstream.flush (); if (fileoutputstream! = null) {Fileoutputstream.close ();} Down ();} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}. Start ();} Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg);pd. Cancel (); Update ();}};/ * * Download complete via handler The Download dialog box is canceled */public void down () {new Thread () {public void run () {Message message = Handler.obtainmessage (); handler.sendmessage (message);}}. Start ();} /** * Install application */public void Update () {Intent Intent = new Intent (Intent.action_view); Intent.setdataandtype (Uri.fromfile (new File (Environment.getexternalstoragedirectory (), update_serverapk)), "application/vnd.android.package-archive"); Mcontext.startactivity (intent);}}
Check for updates every time the app is activated
Onresume:function () { setTimeout (function () { //check for update updateclient.check (); }, 0); }
Document.addeventlistener ("Resume", Yooshowapp.onresume, false);
var updateclient = {Check:function (Isalert) {if (typeof device)! = "undefined" && device.platform = = "Android") {if (Localstorage.getitem ("Yooshowsession")) {//delete reminder Remind.delper Sonremind ({"ModuleID": "Update"}); } window.plugins.updateApp.getCurrentVersion (function (currentversioncode) {yooshow. Postapp ("Checkversion", {}, function (result) {//Latest version var version = result. Version; Whether to force update of var = result. Force; var url = result. URL; Describes var description = result. Description; if (parseint (version) > parseint (currentversioncode)) {//Mandatory update if (force) {window.plugins.updateApp.update (URL, function () {}, function () {}); } else {navigator.notification.confirm (description, Function (button) { if (Button = = 1) {window.plugins.updateApp.update (URL, function () { }, function () {}); }}, ' Discover new version ', ' Update Now, update later '); }} else {if (Isalert) {Yooshow.alert ("You are the latest version"); } } }); }, function () {}); } }}
PhoneGap (Cordova) Custom Plugin Code chapter (ii)----Android Auto-update