The steps to proactively update the app are divided into three steps:
- Check for updates (assuming there is an update for step 2nd, otherwise returned)
- Download the new APK installation package
- Install APK
These three steps are explained in the following. It will be interspersed with the corresponding code. All three steps of the app's own initiative are encapsulated in a single updater class that can be used directly, and I'll post the source code github address at the end of the article.
Updater using Demo sample
Through a single class Updater can be easily implemented to proactively check for updates, download the installation package and self-active installation. Be able to monitor the download progress, can define the update prompt and so on. The save path can be written freely, assuming that a folder in the path does not exist and is created on its own initiative. The streaming API interface is easy to use. The following is an example of using a demo. A line of code to take care of their own active update:
String savePath = Environment.getExternalStorageDirectory() "/whinc/download/whinc.apk";"http://192.168.1.168:8000/update.xml";Updater.with(mContext) .downloadListener(mListener) .update(updateUrl) .save(savePath) .create() .checkUpdate();
First step: Check for Updates
This step requires a service-side collaboration. The server stores an XML-formatted configuration file (which can also be used in JSON or other formats) to check for updates with the client. The update.xml format is as follows:
<?xml version= "1.0" encoding= "Utf-8"?><info> <version> <code>4</Code> <name>1.0.4</name> </version> <URL>http://192.168.1.168:8000/test.apk</URL> <description>Update-bar bar, fix-bar, add-blblblb</Description></Info>
<version>The label specifies the version number and version number name of the server side, the version number and the version number name corresponding to the and in the Android project configuration versionCode versionName (the Eclipse ADT Project can be found in the tags in androidmanifest.xml. The Android Studio project was found in the Defaultconfig in the module's Build.gradle).
<url>tag to specify the APK,
<description>Label to specify the update content.
The client requests the server-side Update.xml file via HTTP. Then parse the Update.xml, compare the server version number and the local version number, assuming that the server version number is greater than the local version number description is updated, according to the APK specified in the Update.xml download the latest apk, the following will be described in detail.
Here's the code to check for updates:
/** * Check the APP version number * * @return Assume that a new version number returns TRUE. Otherwise returns false * / Private Boolean checkversion() {URL url; HttpURLConnection Httpconn =NULL;Try{URL =NewURL (Mcheckupdateurl); Httpconn = (httpurlconnection) url.openconnection (); Httpconn.setconnecttimeout (200000); Httpconn.setreadtimeout (200000); Httpconn.setusecaches (false);//Disable cache for current HTTP connectionHttpconn.connect ();if(Httpconn.getresponsecode () = = HTTPURLCONNECTION.HTTP_OK) {InputStream InputStream = Httpconn.getinputstream ();//Parse XML data if(!parsexml (InputStream)) {return false; }//Compare local version number to server version numberPackageInfo PackageInfo = Mcontext.getpackagemanager (). Getpackageinfo (Mcontext.getpackagename (),0);if(Packageinfo.versioncode < Mremoteversioncode) {return true; } }Else{return false; } }Catch(Malformedurlexception e) {E.printstacktrace (); }Catch(IOException e) {E.printstacktrace (); }Catch(Packagemanager.namenotfoundexception e) {E.printstacktrace (); }finally{Httpconn.disconnect (); }return false; }
First create the HttpURLConnection access server Update.xml file, then parse the Update.xml file returned by the server and save the version number information, APK, and update log. After parsing, the version number of the current client is compared with the server version number. Assume that the service-side version number is larger, indicating that the server has an updated version number. The Checkversion () method returns True, otherwise false is returned.
Check the updated code as follows. It is important to note that. Different in Android is intended to initiate a network request in the main thread (UI thread), so checkVersion() the call needs to be placed in a non-main thread. There are many ways to implement asynchronous requests, where I use Asynctask.
Public void checkupdate() {NewAsynctask<void, Void, boolean> () {@Override protectedBooleanDoinbackground(Void ... params) {BooleanHasnewversion = Checkversion ();returnHasnewversion; }@Override protected void OnPostExecute(Boolean hasnewversion) {Super. OnPostExecute (Hasnewversion);if(Mcheckupdatelistener = =NULL|| !mcheckupdatelistener.oncompleted (Hasnewversion, Mremoteversioncode, Mremoteversionname, MUpdateLog , Mapkdownloadurl)) {if(hasnewversion) {Showupdatedialog (); }}}}.execute (); }
Download the new APK installation package
showUpdateDialog()After the call displays the Update prompt dialog box, in the dialog box confirming the button click event, first create the Downloadmanager.request object, and then set the various properties of the object such as the following to download the save path, notification bar title, etc. Finally, the download request is placed in the download queue of the system service Downloadmanager. To the system to process the download logic. In order to listen to the download completed event, the code is registered in the broadcast DownloadManager.ACTION_DOWNLOAD_COMPLETE . Download progress through the register contentobserver to listen.
/** * Show update dialog box * / Private void Showupdatedialog() {Alertdialog.builder Builder =NewAlertdialog.builder (Mcontext); Builder.settitle (Mtitle); Builder.setmessage (Mupdatelog); Builder.setpositivebutton (Mdialogokbtntxt,NewDialoginterface.onclicklistener () {@Override Public void OnClick(Dialoginterface Dialog,intwhich) {Dialog.dismiss ();//Background DownloadMdownloadmgr = (Downloadmanager) mcontext.getsystemservice (Context.download_service); Downloadmanager.request Request =NewDownloadmanager.request (Uri.parse (Mapkdownloadurl));if(Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {//Assuming the save path includes subfolders, you need to recursively create the folder if(!createdirifabsent (Msavepath)) {LOG.E ("TAG","APK save path can not be created:"+ Msavepath);return; } Request.setdestinationuri (Uri.fromfile (NewFile (Msavepath)); Request.settitle (Mnotificationtitle); Request.settitle (Mnotificationmessage);//Register the broadcast, listen to the download completed eventMcontext.registerreceiver (Mcompletereceiver,NewIntentfilter (Downloadmanager.action_download_complete));//Register to monitor download progressMcontext.getcontentresolver (). Registercontentobserver (Uri.parse ("Content://downloads/my_downloads"),true, Mcontentobserver); Mdownloadid = Mdownloadmgr.enqueue (request); }Else{LOG.E ("TAG","Can not access external storage!");return; } toast.maketext (Mcontext,"Downloading in the background ...", Toast.length_short). Show (); } }); Builder.setnegativebutton (Mdialogcancelbtntxt,NewDialoginterface.onclicklistener () {@Override Public void OnClick(Dialoginterface Dialog,intwhich) {dialog.cancel (); } }); Builder.create (). Show (); }/** * Assumes the path specified by path is not present in the folder, create the specified folder * * @param path absolute path (including file name, such as '/sdcard/storage/download/te st.apk ') * @return Assume that the successful creation of the folder returns TRUE, otherwise false * / Private Boolean createdirifabsent(String Path) {string[] array = Path.trim (). Split (File.separator); list<string> dirnames = arrays.aslist (array). Sublist (1, Array.Length-1); StringBuilder Pathbuilder =NewStringBuilder (File.separator); for(String d:dirnames) {Pathbuilder.append (d); File f =NewFile (Pathbuilder.tostring ());if(!f.exists () &&!f.mkdir ()) {return false; } pathbuilder.append (File.separator); }return true; }
Install APK
Once the APK has been downloaded, you will be able to run the install APK action, just by downloading the ID to infer if the broadcast event is due to our apk download, because the system may have multiple download tasks at the same time, by downloading the ID to differentiate.
new BroadcastReceiver() { @Override publicvoidonReceive(Context context, Intent intent) { long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1); if (downloadId == mDownloadId) { installApk(); release(); } } };
The following is the installapk () method, which first retrieves the downloaded APK storage path from the Downloadmanager through the download ID, and then installs the downloaded apk from the intent, which is easy to code. Note that the intent setting is identified as Intent.FLAG_ACTIVITY_NEW_TASK . Otherwise, the Setup program will not start properly.
/** * 替换安装当前App。注意:签名一致 */ privatevoidinstallApk() { // 获取下载的 APK 地址 Uri apkUri = mDownloadMgr.getUriForDownloadedFile(mDownloadId); new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); "application/vnd.android.package-archive"); mContext.startActivity(intent); }
GitHub Source Code
Whinc/android-updatemanager
A better reference:
Downloadmanager | Android Developers
Android system Download Management Downloadmanager function Introduction and Use Demo sample
"Android" Android program to update itself actively