Android Implementation detection version, download apk update (with source)

Source: Internet
Author: User

In fact, this is not a difficult thing, there are hot update technology, just record, the great God do not laugh.

First of all, the idea, the first to have updated interface, as long as the app, monitoring the interface, whether updated, updated, to detect whether the local version is less than the version returned by the interface, low, then download the APK update according to the path returned. The field returned by the interface has at least update flag, updated version, update description, apk.

Update flag should have three states, update, ask for updates, force updates, you can start a service ( do not forget to register in the manifest file ) to check the update and download the work;

This is all the code in the service, and it's not hard to understand, there are comments in the important places. After the service is written, StartService () is ready to start in the code.

This pop up a interrogation box, need to add permissions in the manifest file, <uses-permission android:name= "Android.permission.SYSTEM_ALERT_WINDOW"/> This is the permission to eject the global interrogation box.

Import Android.app.alertdialog;import Android.app.dialog;import Android.app.service;import Android.content.dialoginterface;import Android.content.intent;import Android.content.pm.packageinfo;import Android.content.pm.packagemanager;import Android.graphics.color;import Android.net.uri;import Android.os.environment;import Android.os.handler;import Android.os.ibinder;import Android.os.Message;import Android.support.annotation.nullable;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.view.windowmanager;import Android.widget.progressbar;import Android.widget.textview;import Com.example.sdtz.wenmingweifang.r;import Com.example.sdtz.wenmingweifang.tool.okhttputil;import Com.example.sdtz.wenmingweifang.util.app;import Com.example.sdtz.wenmingweifang.util.myurl;import Org.json.jsonexception;import Org.json.JSONObject;import Java.io.file;import Java.io.fileoutputstream;import Java.io.inputstream;import Java.net.HttpURLConnection;import Java.net.url;/** * Created by Sdtz on 2017/7/1.    */public class Updateservice extends Service {private ProgressBar mprogressbar;//progress bar private TextView TV1;    Private TextView TV2;    Private String URL = myurl.httpurl;    Private String Versioncode;    Private String result;    Private app app;    private string msavepath;//apk Save address private string Mversion_path;    Private String Mversion_name = "app.apk";//apk name private float length;    Private Dialog mdownloaddialog;//dialog box private int mprogress;//Progress value private static final int downloading = 1;//apk download    private static final int download_finish = 2;//apk Download Complete private Boolean miscancel = false;//whether to cancel the download identifier @Nullable    @Override public IBinder onbind (Intent Intent) {return null; } private Handler Mupdateprogresshandler = new Handler () {public void Handlemessage (Message msg) {SW Itch (msg.what) {case downloading://Set progress bar Mprogressbar.setproGress (mprogress);                    Tv1.settext (mprogress + "/100");                    Float len = length/1024/1024;//converts length to M-unit float B = (float) (Math.Round (len*100))/100;//reserved two-bit decimal point                    Tv2.settext (b + "M");                Break                    Case Download_finish://Hide current Download dialog box Mdownloaddialog.dismiss ();                    Install APK file installapk ();                Break            Default:break;    }        };    }; @Override public int Onstartcommand (Intent Intent, int flags, int startid) {try {Versioncode = Getv         Ersionname ();                /* GETJSONREUSLT (); */New Okhttputil (). Getjson (Myurl.appdown, New Okhttputil.httpcallback () { @Override public void onsusscess (String data) throws Jsonexception {Jsonobject Jo1 = NE                    W jsonobject (data); App = new ApP ();                    App.setversion (jo1.getstring ("version"). ToString ());                    App.setdescription (jo1.getstring ("description"). ToString ());                    App.seturl (myurl.httpurl+jo1.getstring ("url"). toString ());                    App.setupdate_flag (jo1.getstring ("Update_flag"). toString ());                    Mversion_path = App.geturl ();                    Phone current version String phoneversion = versioncode.substring (0,versioncode.lastindexof ("."));                    Double Jiekou = double.parsedouble (App.getversion ());                    Double Bendi = null;                    try {Bendi = double.parsedouble (Getversionname ());                    } catch (Exception e) {e.printstacktrace ();                    } log.d ("= =", "Interface:" +jiekou+ "Local:" +bendi+ "::" +app.tostring ()); The local version is inconsistent with the interface return version, and the update flag is 1, update if (! Versioncode.equals (App.getversion ()) && (Jiekou>bendi) && App.getupdate_flag () Equals ("1")) {log.d ("= =", ":: Enter");                    ShowDialog (App.getdescription ()); }else if (!                        Versioncode.equals (App.getversion ()) && (Jiekou>bendi) && app.getupdate_flag (). Equals ("2")) {                    Showdownloaddialog ();        }                }            });        } catch (Exception e) {e.printstacktrace ();        } catch (Throwable throwable) {throwable.printstacktrace ();    } return Super.onstartcommand (intent, flags, Startid); }/* Gets the version number of the current program */private String Getversionname () throws exception{//Get instance of Packagemanager P        Ackagemanager Packagemanager = Getpackagemanager ();        Getpackagename () is the package name of your current class, and 0 means to get version information PackageInfo packinfo = Packagemanager.getpackageinfo (Getpackagename (), 0);    return packinfo.versionname; } private void ShowDialog (StringDRC) {Final Alertdialog.builder Builder = new Alertdialog.builder (this,alertdialog.theme_holo_light);        Builder.setmessage (DRC); Builder.setpositivebutton ("OK", new Dialoginterface.onclicklistener () {@Override public void onclic            K (dialoginterface dialoginterface, int i) {showdownloaddialog ();        }        }); Builder.setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void onclic            K (dialoginterface dialoginterface, int i) {Dialoginterface.dismiss ();        }        });        Alertdialog Alertdialog = Builder.create ();        Alertdialog.getwindow (). SetType (WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);        Alertdialog.setcanceledontouchoutside (TRUE);        Alertdialog.show ();        Alertdialog.getbutton (alertdialog.button_positive). SetTextColor (Color.green);   Alertdialog.getbutton (alertdialog.button_negative). SetTextColor (color.red); }/* * Open new Thread download file */private void downloadapk () {New Thread (new Runnable () {@Override public void Run () {try{//checks if the SD is mounted if (environment.getexternalstoragestate (). eq                        Uals (environment.media_mounted)) {String Sdpath = environment.getexternalstoragedirectory () + "/";                        Msavepath = Sdpath + "Wenmingdownload";                        File dir = new file (Msavepath);                        if (!dir.exists ()) Dir.mkdir ();                        Download file HttpURLConnection conn = (httpurlconnection) new URL (Mversion_path). OpenConnection ();                        Conn.connect ();                        InputStream is = Conn.getinputstream ();                        Length = Conn.getcontentlength ();                        File Apkfile = new file (Msavepath, mversion_name); FileOutputStream fos = new FileoutputsTream (Apkfile);                        int count = 0;                        byte[] buffer = new byte[1024];                            while (!miscancel) {int numread = is.read (buffer);                            Count + = Numread;                            Calculates the current position of the progress bar mprogress = (int) ((count/length) * 100);                            Update progress bar mupdateprogresshandler.sendemptymessage (downloading); Download complete if (Numread < 0) {Mupdateprogresshandler.sendemptymes                                Sage (download_finish);                            Break                        } fos.write (buffer, 0, numread);                        } fos.close ();                    Is.close ();                }}catch (Exception e) {e.printstacktrace ();            }}}). Start ();        }/* * Download to local after performing installation */protected void installapk () {File Apkfile = new file (Msavepath, mversion_name);        if (!apkfile.exists ()) return;        Intent Intent = new Intent (Intent.action_view);        Uri uri = uri.parse ("file://" + apkfile.tostring ());        Intent.setdataandtype (URI, "application/vnd.android.package-archive");        Intent.addflags (Intent.flag_activity_new_task);    This.startactivity (Intent); }/* * Displays the download dialog box */protected void Showdownloaddialog () {Alertdialog.builder Builder = new alertdial og.        Builder (this); Builder.settitle ("version update, download ...        ");        View view = Layoutinflater.from (this). Inflate (r.layout.dialog_progress, NULL);        Mprogressbar = (ProgressBar) View.findviewbyid (r.id.id_progress);        TV1 = (TextView) View.findviewbyid (R.ID.TV1);        TV2 = (TextView) View.findviewbyid (R.ID.TV2);        Builder.setview (view);   Mdownloaddialog = Builder.create ();     Mdownloaddialog.getwindow (). SetType (WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);        Mdownloaddialog.show ();    Download file downloadapk (); }}

  

Android Implementation detection version, download apk update (with source)

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.