Android implements app version update case

Source: Internet
Author: User

Androidmainfest.xml. Configure related permissions

<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.mytest.versionupdate"Android:versioncode= "1"Android:versionname= "1.0" >    <USES-SDKandroid:minsdkversion= "+"android:targetsdkversion= "+" />    <uses-permissionAndroid:name= "Android.permission.INTERNET"/>    <uses-permissionAndroid:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    <uses-permissionAndroid:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>    <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" >        <ActivityAndroid:name=". Mainactivity "Android:label= "@string/app_name" >            <Intent-filter>                <ActionAndroid:name= "Android.intent.action.MAIN" />                <categoryAndroid:name= "Android.intent.category.LAUNCHER" />            </Intent-filter>        </Activity>    </Application></Manifest>
View Code

Main.xml,

<Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Com.mytest.autoupdate.MainActivity" >    <TextViewAndroid:layout_width= "Wrap_content"Android:layout_height= "Wrap_content"Android:text= "@string/hello_world" /></Relativelayout>
View Code

Downloadapk_progress.xml, customizing Download Progress view

<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"Tools:context= "Com.mytest.autoupdate.MainActivity" >    <ProgressBarAndroid:id= "@+id/download_progressbar"Android:layout_width= "Fill_parent"Android:layout_height= "Wrap_content"style= "? Android:attr/progressbarstylehorizontal"         /></LinearLayout>
View Code

Call Automatic Updates in Mainactivity.java

Package Com.mytest.autoupdate;import Android.app.activity;import Android.os.bundle;import android.view.Menu;import Android.view.menuitem;public class Mainactivity extends Activity {    @Override    protected void OnCreate (Bundle Savedinstancestate) {        super.oncreate (savedinstancestate);        Setcontentview (r.layout.activity_main);                New Autoupdatemanager (this). Checkisneedupdate ();    }}
View Code

Autoupdatemanager.java

Package Com.mytest.autoupdate;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 Org.json.jsonexception;import Org.json.jsonobject;import Org.json.jsontokener;import Android.app.alertdialog;import Android.app.alertdialog.builder;import Android.app.dialog;import Android.content.context;import Android.content.dialoginterface;import Android.content.intent;import Android.content.pm.packagemanager.namenotfoundexception;import Android.net.uri;import android.os.Environment; Import Android.os.handler;import Android.os.message;import Android.text.alteredcharsequence;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.widget.ProgressBar;    Import Android.widget.toast;public class Autoupdatemanager {private final String Log_tag = "Autoupdatemanager";    Private context context; Public AutoupdatemAnager (Context context) {This.context = context;    }//Judge version update URL private final String Check_version__url = "Http://192.168.23.1:8080/testapp/version_json";            /** * Check if you need to update */public void Checkisneedupdate () {//Get version Information new Thread (new Runnable () { @Override public void Run () {//Get version information String Versionjson = GetVersionInfo ()                ; if (Versionjson! = NULL &&! "".                    Equals (Versionjson.trim ())) {Message msg = Versioninfohandler.obtainmessage ();                    Msg.obj = Versionjson;                Versioninfohandler.sendmessage (msg);        }}). Start (); Compare version if (!islastversion ()) {new Alertdialog.builder (context). Settitle ("hint"). Setmessage ("The software has an update, whether to download the update ?                        "). Setpositivebutton (" Update Now ", new Dialoginterface.onclicklistener () {@Override PublIC void OnClick (Dialoginterface dialog, int which) {//Show download progress bar Show                            Downloaddialog ();                            Download apk file Downloadapkfile (); Install APK//Todo}}). Setnegativebutton ("Next time", NULL)        . Create (). Show ();        } else {Toast.maketext (context, "Already the latest version", Toast.length_short). Show ();    }} private ProgressBar Download_progressbar;    Private Alertdialog Downloaddialog;    Private Boolean iscanceldownload = false;    Private final int download_state_fininsh = 1;    Private final int download_state_load = 0;    private int downloadcurprogress; Private Handler Downloadhandler = new Handler () {public void Handlemessage (Message msg) {switch (msg.a       RG1) {case DOWNLOAD_STATE_LOAD:download_progressbar.setProgress (downloadcurprogress);         Break                                Case DOWNLOAD_STATE_FININSH:downLoadDialog.dismiss ();                                INSTALLAPK ();            Break    }        }    };                private void Showdownloaddialog () {downloaddialog = new Alertdialog.builder (context). Settitle ("in Download") . Setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public                    void OnClick (Dialoginterface dialog, int which) {iscanceldownload = true;        }}). Create ();        View view = Layoutinflater.from (context). Inflate (r.layout.downloadapk_progress, NULL);        Downloaddialog.setview (view);        Download_progressbar = (ProgressBar) View.findviewbyid (R.id.download_progressbar);    Downloaddialog.show (); }/** * Download apk file */private void Downloadapkfile () {LOG.V (Log_tag, "downloadapkfile->" + Versiondo        Wnloadurl); New Thread (New Runnable () {@Override public void run () {try {if (E Nvironment.getexternalstoragestate (). Equals (environment.media_mounted)) {String Dirpath = environm                        Ent.getexternalstoragedirectory () + "/";                        Saveapkpath = Dirpath + "AutoUpdate";                        File File = new file (Saveapkpath);                        if (file.exists () = = False) {File.mkdir ();                        } saveapkfilename = "version" + Versioncode;                        File Apkfile = new file (saveapkpath,saveapkfilename);                        FileOutputStream fos = new FileOutputStream (apkfile);                        HttpURLConnection conn = (httpurlconnection) new URL (Versiondownloadurl). OpenConnection ();                        int fileSize = Conn.getcontentlength ();                 InputStream is = Conn.getinputstream ();       int len = 0;                        int count = 0;                        byte[] buff = new byte[1024];                            while (!iscanceldownload) {len = Is.read (buff); Calculate current Progress Count + = len;//log.v (log_tag, "downloadcurprogress->" +                            "Count:" +count+ ", FileSize:" +filesize); downloadcurprogress = (int) ((float) count/filesize);//LOG.V (Log_tag, "Downloadcurpro                            Gress-> "+downloadcurprogress);                            Message msg = Downloadhandler.obtainmessage ();                            MSG.ARG1 = Download_state_load;                            Downloadhandler.sendmessage (msg);  if (len<0) {Message MSG2= Downloadhandler.obtainmessage (); Msg2.arg1= Download_state_fininsh; //Note A new Message object must be sent Downloadhandler.sendmessage (MSG2);                            Break                        } fos.write (Buff, 0, Len);                    } is.close (); }} catch (Exception e) {//TODO auto-generated catch block e.prints                Tacktrace ();        }}). Start ();  }/** * is the latest version * * @return */Private Boolean islastversion () {try {int curver = Context.getpackagemanager (). Getpackageinfo ("Com.mytest.autoupdate",0). Versioncode;            if (Curver < Versioncode) {return true;         }} catch (Namenotfoundexception e) {//TODO auto-generated catch block E.printstacktrace ();    } return false;    }//Version information.    private int versioncode;    Private String Versionname;    Private String Versiondesc;    Private String Versiondownloadurl;    Private String Saveapkfilename; Private String saveapkpath;//apk save path private Handler Versioninfohandler= newHandler () {public void Handlemessage (Message msg) {String Versionjson= (String)Msg.obj; try {Jsontokener JT= newJsontokener (Versionjson); Jsonobject obj= (jsonobject)Jt.nextvalue (); Demo Data//{"Versioncode": 3, "Versionname": "TestApp", "desc": "added xx function", "Versiondownloadurl": "http://192.168 .23.1:8080/testapp/versionupdate.apk "} versionname= obj.getstring ("Versionname"); Versiondesc= obj.getstring ("Versiondesc"); Versiondownloadurl= obj.getstring ("Versiondownloadurl"); Versioncode= Obj.getint ("Versioncode"); log.v (Log_tag, Versionname + "," + Versioncode);            } catch (Jsonexception e) {//TODO auto-generated catch block E.printstacktrace ();    }        };    }; /** * Get version information */private String GetVersionInfo () {StringBuffer Jsonrst= newStringBuffer (); try {HttpURLConnection conn= (httpurlconnection)new URL (Check_version__url). OpenConnection ();            Conn.setrequestmethod ("GET"); InputStream is= Conn.getinputstream (); int Len= 0; byte[] Buffer= newbyte[1024]; while (Len= is.read (buffer))!=-1){jsonrst.append (new String (buffer, 0, Len, "UTF-8"));        } is.close ();        } catch (Exception e) {e.printstacktrace ();    } return jsonrst.tostring (); }/** * Install APK */private void installapk () {File file= newFile (saveapkpath+ "/" +saveapkfilename); if (file.exists ()==false) {            return; } Intent Intent= newIntent (); Uri URI= Uri.parse ("file://" +file.tostring ()); Intent.setdataandtype (URI, "application/vnd.android.package-archive");    Context.startactivity (Intent);    }; }
View Code

Key points of knowledge:
1, handler and the use of the message;
2, the Use of custom dialog (in the download progress);
3. Download the file to SD.
4. Install apk file.
5, JSON network acquisition and parsing.

Android implements app version update case

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.