Initial Implementation of Automatic update for Android apps

Source: Internet
Author: User

This is only a preliminary implementation and does not include functions such as automatic compilation. You need to manually change the updated XML file and the latest APK.
Four files are involved!
I. Client
Androidupdatetestactivity. CS: Application Homepage
Main. xml: homepage Layout
Update. CS: Update class
Softupdate_progress: Update wait Interface

Updage. CS

Package majier. test; 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 Java. util. hashmap; import javax. XML. parsers. documentbuilder; import javax. XML. parsers. documentbuilderfactory; import Org. w3C. dom. document; import Org. w3C. dom. element; import Org. w3C. Dom. node; import Org. w3C. dom. nodelist; import android. app. alertdialog; import android. app. dialog; import android. app. alertdialog. builder; import android. content. context; import android. content. dialoginterface; import android. content. intent; import android. content. dialoginterface. onclicklistener; import android. content. PM. packagemanager. namenotfoundexception; import android.net. uri; import android. OS. environ Ment; import android. OS. handler; import android. OS. message; import android. view. layoutinflater; import android. view. view; import android. widget. progressbar; import android. widget. toast; public class update {Private Static final int download = 1; Private Static final int download_finish = 2; Private Static final int connect_failed = 0; Private Static final int connect_success = 1; hashmap <string, string> mhas Hmap; private string msavepath; private int progress; private Boolean cancelupdate = false; private context mcontext; private progressbar mprogress; private dialog mdownloaddialog; private string mxmlpath; // server update XML storage address public Update (context, string xmlpath, string savepath) {This. mcontext = context; this. mxmlpath = xmlpath; this. msavepath = savepath;} private handler mhandler = new handler () {Publ IC void handlemessage (Message MSG) {Switch (MSG. what) {Case download: mprogress. setprogress (Progress); break; Case download_finish: installapk (); break; default: Break ;};};/*** check for updates */Public void checkupdate () {New thread (New runnable () {@ overridepublic void run () {try {URL url = new URL (mxmlpath); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. setconnecttimeout (5000); inputstream Instream = Conn. getinputstream (); mhashmap = parsexml (instream); message MSG = new message (); MSG. what = connect_success; handler. sendmessage (MSG);} catch (exception e) {message MSG = new message (); MSG. what = connect_failed; handler. sendmessage (MSG );}}}). run ();}/*** Access Server Update XML */handler = new handler () {@ overridepublic void handlemessage (Message MSG) {super. handlemessage (MSG); Switch (MSG. what) {Case connect_failed: Toast. maketext (mcontext, "failed to access the server! ", Toast. length_short). Show (); break; Case connect_success: If (null! = Mhashmap) {int servicecode = integer. valueof (mhashmap. get ("version"); If (servicecode> getversioncode (mcontext) {shownoticedialog () ;}} break ;}}}; /*** get the program version */private int getversioncode (context) {int versioncode = 0; try {versioncode = context. getpackagemanager (). getpackageinfo (mcontext. getpackagename (), 0 ). versioncode;} catch (namenotfoundexception e) {e. printstacktrace ();} return versi Oncode;}/*** update Prompt window */private void shownoticedialog () {alertdialog. builder = new Builder (mcontext); builder. settitle ("Software Update"); builder. setmessage ("New Version Detected, updated? "); Builder. setpositivebutton ("Update", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss (); showdownloaddialog () ;}}); builder. setnegativebutton ("cancel", new onclicklistener () {@ overridepublic void onclick (dialoginterface dialog, int which) {dialog. dismiss () ;}}); dialog noticedialog = builder. create (); noticedialog. show ();}/*** download wait window */private void showdownl Oaddialog () {alertdialog. builder = new Builder (mcontext); builder. settitle ("Updating"); Final layoutinflater Inflater = layoutinflater. from (mcontext); view v = Inflater. inflate (R. layout. softupdate_progress, null); mprogress = (progressbar) v. findviewbyid (R. id. update_progress); builder. setview (V); builder. setnegativebutton ("cancel download", new onclicklistener () {@ overridepublic void onclick (dialoginterface Dia Log, int which) {dialog. dismiss (); cancelupdate = true ;}}); mdownloaddialog = builder. create (); mdownloaddialog. show (); downloadapk ();}/*** APK */private void downloadapk () {New downloadapkthread (). start ();}/*** download program */private class downloadapkthread extends thread {@ overridepublic void run () {try {If (environment. getexternalstoragestate (). equals (environment. media_mounted) {URL url = new URL (Mhashmap. get ("url"); httpurlconnection conn = (httpurlconnection) URL. openconnection (); Conn. connect (); int length = Conn. getcontentlength (); inputstream is = Conn. getinputstream (); file = new file (msavepath); If (! File. exists () {file. mkdir ();} file apkfile = new file (msavepath, mhashmap. get ("name"); 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); mhandler. sendemptymessage (download); If (numread <= 0) {mhandler. sendemptymessage (download_finish); break;} FOS. write (BUF, 0, Numread);} while (! Cancelupdate); FOS. close (); is. close () ;}} catch (malformedurlexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace ();} mdownloaddialog. dismiss () ;}};/*** install APK */private void installapk () {file apkfile = new file (msavepath, mhashmap. get ("name"); 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);} private hashmap <string, string> parsexml (inputstream instream) throws exception {hashmap <string, string> hashmap = new hashmap <string, string> (); // instantiate a document builder factory documentbuilderfactory factory = documentbuilderfactory. newinstance (); // obtain a document builder documentbuilder builder = factory through the document builder factory. newdocumentbuilder (); // you can use the document builder to create a document instance document = builder. parse (instream); // get the root node of the XML file, element root = document. getdocumentelement (); // obtain all subnodes nodelist childnodes = root. getchildnodes (); For (Int J = 0; j <childnodes. getlength (); j ++) {// traverse the subnode node childnode = (node) childnodes. item (j); If (childnode. getnodetype () = node. element_node) {element childelement = (element) childnode; // version if ("version ". equals (childelement. getnodename () {hashmap. put ("version", childelement. getfirstchild (). getnodevalue ();} // software name else if ("name ". equals (childelement. getnodename () {hashmap. put ("name", childelement. getfirstchild (). getnodevalue ();} // else if ("url ". equals (childelement. getnodename () {hashmap. put ("url", childelement. getfirstchild (). getnodevalue () ;}}return hashmap ;}}

Androidupdatetestactivity. CS

package majier.test;import android.app.Activity;import android.os.Bundle;import android.os.Environment;public class AndroidUpdateTestActivity extends Activity {    /** Called when the activity is first created. */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        update();    }    private void update() {String sdpath = Environment.getExternalStorageDirectory() + "/";String mSavePath = sdpath + "boiler/";Update updateManager = new Update(this,"http://localhost:8011/abcd.xml", mSavePath);updateManager.checkUpdate();}}

Main. xml

<?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="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/hello" /></LinearLayout>

Softupdate_progress.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="wrap_content"><ProgressBarandroid:id="@+id/update_progress"android:layout_width="fill_parent"android:layout_height="wrap_content"style="?android:attr/progressBarStyleHorizontal" /></LinearLayout>

You must modify the system version number before generating a new APK.

Modify the version code and name. The code above shows that the system determines whether to update the version code. Version name as a version name
Here, we recommend that you change the version code from 10 to 1.1 ).
After the modification is completed, the system is generated. Then, place the APK file under the Server File.
Ii. Server
The server mainly creates a website for users to download the APK. Create a new website on IIS

Http: // localhost: 8011 /. Store the updated file and updated XML in the directory.


Version. XML format

<update><version>12</version><name>BoilerAndroid_1.1</name><url>http://192.168.0.33:8011/boilerandroid.apk</url></update>

The version corresponds to the version code of the new program;
Name;
The URL corresponds to the download path of the APK.

There may be a problem here. IIS reports an error when accessing the URL path. This is mainly because IIS does not know APK and does not know how to handle it.
Here, we add the MIME type of the android program in IIS to enable APK download.
In "IIS manager", view the created website-MIME type-add.
File Extension:. APK
Mime Type: Application/vnd. Android. Package-Archive

In this way, you can download it.
Currently, it is only a simple automatic update program. We can see that the version number must be filled in by the user, and must correspond to the XML. The APK must be generated and placed under the updated URL.
Such human operations can easily lead to mistakes. Therefore, we need to study the automatic release of the updated version, and the version number corresponds to SVN. After submitting SVN, the version number of the program is automatically changed.

Related Article

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.