Hello everyone, I found that my blog has not been updated for half a year and has been busy recently. I decided to take a break in the early morning at Premier League arsenal vs. Fulham, we will share with you the implementation of the app version update function in Android.
A good application software requires good maintenance. From the initial publication to the final product, this process requires constant updates of the version. So how can users get the latest application installation package immediately? Therefore, we need to upgrade the module from the first version.
The implementation principle of the automatic update function is that we negotiate an interface with the background in advance. We access this interface in the main activity of the application. If you need to update the interface, the background will return some data (such as prompts and the latest URL ). In the prompt box, click Start download to overwrite the installer after the download is complete, so that your application remains up to date.
To make it easy for everyone to understand, I have prepared a small example as usual. For convenience, I am saving the time to interact with the background. The steps are as follows:
Step 1: Create an android project named updatedemo. The code structure is shown in:
Step 2: Create an updatemanager. Java class to update the software module. The Code is as follows:
Package COM. tutor. update; import Java. io. file; import Java. io. fileoutputstream; import Java. io. ioexception; import Java. io. inputstream; import java.net. httpurlconnection; import java.net. malformedurlexception; import java.net. URL; import android. app. alertdialog; import android. app. dialog; import android. app. alertdialog. builder; import android. content. context; import android. content. dialoginterface; import Andro Id. content. intent; import android. content. dialoginterface. onclicklistener; import android.net. uri; import android. OS. handler; import android. OS. message; import android. view. layoutinflater; import android. view. view; import android. widget. progressbar; public class updatemanager {private context mcontext; // prompt private string updatemsg = "you have the latest software package. Download it now ~ "; // Returned package urlprivate string apkurl =" http://softfile.3g.qq.com: 8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk "; private dialog noticedialog; private dialog downloaddialog; /* download package installation path */Private Static final string savepath = "/sdcard/updatedemo/"; Private Static final string savefilename = savepath + "updatedemorelease.apk "; /* progress bar and handler and MSG constant for notifying UI refreshing */private progressbar mprogress; Private Static Final int down_update = 1; Private Static final int down_over = 2; private int progress; private thread downloadthread; private Boolean interceptflag = false; private handler mhandler = new handler () {public void handlemessage (Message MSG) {Switch (MSG. what) {Case down_update: mprogress. setprogress (Progress); break; Case down_over: installapk (); break; default: Break ;};}; public updatemanager (contex T context) {This. mcontext = context;} // The external interface allows the main activity to call public void checkupdateinfo () {shownoticedialog ();} private void shownoticedialog () {alertdialog. builder = new Builder (mcontext); builder. settitle ("Software Version Update"); builder. setmessage (updatemsg); builder. setpositivebutton ("Download", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss (); showdownloaddialo G () ;}}); builder. setnegativebutton ("later", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss () ;}}); noticedialog = builder. create (); noticedialog. show ();} private void showdownloaddialog () {alertdialog. builder = new Builder (mcontext); builder. settitle ("Software Version Update"); Final layoutinflater Inflater = layoutinflater. from (mcontext); view v = Inflater. INF Late (R. layout. progress, null); mprogress = (progressbar) v. findviewbyid (R. id. progress); builder. setview (V); builder. setnegativebutton ("cancel", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss (); interceptflag = true ;}}); downloaddialog = builder. create (); downloaddialog. show (); downloadapk ();} private runnable mdownapkrunnable = new runnable () {@ overridepu BLIC void run () {try {URL url = new URL (apkurl); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. connect (); int length = Conn. getcontentlength (); inputstream is = Conn. getinputstream (); file = new file (savepath); If (! File. exists () {file. mkdir ();} string apkfile = savefilename; file apkfile = new file (apkfile); fileoutputstream Fos = new fileoutputstream (apkfile); int COUNT = 0; byte Buf [] = new byte [1024]; do {int numread = is. read (BUF); count + = numread; Progress = (INT) (float) count/length) * 100); // Update Progress mhandler. sendemptymessage (down_update); If (numread <= 0) {// install mhandler after the download is complete. sendemptymessage (down_over); br Eak;} FOS. Write (BUF, 0, numread);} while (! Interceptflag); // click Cancel to stop the download. FOS. close (); is. close ();} catch (malformedurlexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}};/*** download APK * @ Param URL */private void downloadapk () {downloadthread = new thread (mdownapkrunnable); downloadthread. start ();}/*** install APK * @ Param URL */private void installapk () {file apkfile = new file (savefilename); If (! Apkfile. exists () {return;} intent I = new intent (intent. action_view); I. setdataandtype (URI. parse ("file: //" + apkfile. tostring (), "application/vnd. android. package-Archive "); mcontext. startactivity (I );}}
Step 3: In mainactivity. Java, that is, the main activity call, the Code is as follows:
Package COM. tutor. update; import android. app. activity; import android. OS. bundle; public class mainacitivity extends activity {private updatemanager mupdatemanager; @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); // check whether the version needs to be updated by mupdatemanager = new updatemanager (this); mupdatemanager. checkupdateinfo ();}}
Step 4: add the resources and permissions used by the Program:
The progressbar is used for downloading, so a progress. xml layout file is written in advance. The Code is as follows:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content"> <ProgressBar android:id="@+id/progress" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal" /></LinearLayout>
The network is used during the download. Therefore, you must add the network permission to androidmanifest. xml. The Code is as follows:
<uses-permission android:name="android.permission.INTERNET" />
Step 5: view the running result as follows:
Figure 1: The latest package is displayed. Figure 2: Click to download
Figure 3: Installation starts after the download. The simulator space is insufficient here.
OK ~ It was a success. Let's continue watching the ball. Arsenal is already. I hope General fan can rescue me! Good night ~ I will share more with you later!
Click to enter the source code ==>