Android about version update issues

Source: Internet
Author: User

In Android, detecting version updates is a common feature of every app, and we're trying to make it simple.
Layout code here does not need to write, a button to detect updates, here I am a Gson file as an example of the request version ...
The first step is to parse the data:
Request version Final String url= "Http://192.168.253.2:8080/gson/banbenwenjian.json" on the network server; Httputils utils=new httputils () utils.configtimeout; Utils.send (httpmethod.get, url, new requestcallback< String> () {@Overridepublic void OnFailure (HttpException arg0, String arg1) {//TODO auto-generated method stub} @Overri depublic void onsuccess (responseinfo<string> arg0) {//TODO auto-generated method stubmnetdata = Arg0.result; Gson gson=new Gson () Banben = Gson.fromjson (Mnetdata, banben.class); mUrl1 = Banben.geturl (); mname = Banben.getname (); Mversion = Banben.getversion (); handler.sendemptymessage (0);}});

Handler accepts data through construction methods toUpdatemanager class
Private Handler handler=new Handler () {public void Handlemessage (Android.os.Message msg) {LOG.D ("U", murl1+mname+ Mversion); Updatemanager manager = new Updatemanager (getactivity (), murl1,mname,mversion); Manager.checkupdate ();};};


-------------------------Parse Bean class------------get version number and name
public class Banben implements Serializable{private string Version;private string name;private string Url;public string ge Tversion () {return version;} public void Setversion (String version) {this.version = version;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} Public String GetUrl () {return URL;} public void SetUrl (String url) {this.url = URL;} @Overridepublic String toString () {return "Banben [version=" + version + ", name=" + name + ", url=" + url+ "]";}}

-----------------------------Updatemanager-------------------
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.ArrayList; Import Com.hao.happyshoppingapp.r;import Com.seven.bean.banben;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.environment;import Android.os.handler;import Android.os.Message;import Android.util.log;import Android.view.layoutinflater;import Android.view.view;import Android.widget.ProgressBar; Import Android.widget.toast;public class Updatemanager {/* download */private static final int DOWNLOAD = 1;/* Download End */private s tatic Final int download_finish = 2;/* Download Save path */privaTe String msavepath;/* records the number of progress bars */private int progress;/* whether to cancel update */private boolean cancelupdate = False;private Context mCo ntext;/* Update progress bar */private ProgressBar mprogress;private banben banben;private Dialog mdownloaddialog;private String url1; private string Name;private string version;private Handler Mhandler = new Handler () {public void Handlemessage (Message msg) {switch (msg.what) {//Is downloading case download://setting progress bar position mprogress.setprogress (progress); Break;case download_finish:// Installation file installapk (); break;default:break;};}; Public Updatemanager (Context mcontext, String url1, String name,string version) {super (); this.mcontext = Mcontext; THIS.URL1 = Url1;this.name = Name;this.version = version;} /** * detection software update */public void Checkupdate () {if (Isupdate ()) {shownoticedialog ();//Display Prompt Dialog} else{toast.maketext (Mcontext, R.string.soft_update_no, Toast.length_long). Show ();}} /** * Check if the software has an updated version * * @return */private boolean isupdate () {//get current software version int versioncode = Getversioncode (Mcontext); LOG.D ("Versioncode", versIoncode+ ""); if (null! = name) {int servicecode = integer.valueof (version);//versions determine if (Servicecode > Versioncode) {return true;}} return false;} private void Request_serverban () {//TODO auto-generated method Stubtoast.maketext (Mcontext, "performed to", 0). Show (); /** * Get software version number * * @param context * @return */private int Getversioncode (context context) {int versioncode = 0;try{//Get Software edition This number corresponds to androidmanifest.xml under Android:versioncodeversioncode = Context.getpackagemanager (). Getpackageinfo (" Com.hao.happyshoppingapp ", 0). Versioncode;} catch (Namenotfoundexception e) {e.printstacktrace ();} return versioncode;} /** * Show software Updates dialog box */private void Shownoticedialog () {//construct dialog Alertdialog.builder builder = new Builder (mcontext); Builder.settitle (R.string.soft_update_title); Builder.setmessage (r.string.soft_update_info);// Update Builder.setpositivebutton (R.STRING.SOFT_UPDATE_UPDATEBTN, New Onclicklistener () {@Overridepublic void OnClick ( Dialoginterface dialog, int which) {Dialog.dismiss ();//Display Download dialog box Showdownloaddialog ();}); /Later update Builder.setnegativebutton (R.string.soft_update_later, New Onclicklistener () {@Overridepublic void OnClick ( Dialoginterface dialog, int which) {Dialog.dismiss ();}});D Ialog Noticedialog = Builder.create (); Noticedialog.show ();} /** * Show software download dialog box */private void Showdownloaddialog () {//Construct software Download dialog box Alertdialog.builder builder = new Builder (mcontext); Builder.settitle (r.string.soft_updating);//Add a progress bar to the download dialog 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);//Cancel Update Builder.setnegativebutton (R.string.soft_update_cancel, New Onclicklistener () { @Overridepublic void OnClick (dialoginterface dialog, int which) {Dialog.dismiss ();//Set cancel status CancelUpdate = True;}}); Mdownloaddialog = Builder.create (); Mdownloaddialog.show ();//Now File downloadapk ();} /** * Download apk file */private void downloadapk () {//start new thread to download software new Downloadapkthread (). Start (); /** * Download File thread * * @author COOLSZY * @date 2012-4-26 * @blog http://blog.92coding.com */private class Downloadapkthread extends thread{@Overridepublic void Run () {try{//determines if the SD card exists and has read and write permissions if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {// Get the path to the memory card string sdpath = Environment.getexternalstoragedirectory () + "/"; Msavepath = Sdpath + "Download"; URL url = new URL (url1);//Create connection HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.connect ();// Gets the file size int length = Conn.getcontentlength ();//Create input stream InputStream is = Conn.getinputstream (); File File = new file (msavepath);//Determine if the directory exists if (!file.exists ()) {File.mkdir ();} File Apkfile = new file (msavepath, name); FileOutputStream fos = new FileOutputStream (apkfile); int count = 0;//cache byte buf[] = new byte[1024];//write to file Do{int Numrea D = Is.read (BUF); count + = numread;//Calculate progress bar Position progress = (int) ((float) count/length) * 100);//Update Progress Mhandler.sendemptymes Sage (DOWNLOAD); if (numread <= 0) {//Download complete mhandler.sendemptymessage (download_finish); break;}Write file Fos.write (buf, 0, numread);} while (!cancelupdate);//Click Cancel to stop the download. Fos.close (); Is.close ();}} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} The Cancel Download dialog box displays Mdownloaddialog.dismiss ();}};/ * * Install APK file */private void installapk () {File Apkfile = new File (msavepath, name); if (!apkfile.exists ()) {return;} Install apk file via Intent Intent i = new Intent (Intent.action_view); I.setdataandtype (Uri.parse ("file://" + apkfile.tostring () ), "application/vnd.android.package-archive"); mcontext.startactivity (i);}}

The important method in the above class has comments to be able to take a look at a number of useful methods ~ ~

Finally to show you the server Gson file, I use the Tomcat server as a test, of course, you can do as you wish.
{    "name": "Happyshopping",    "url": "http://192.168.253.2:8080/anzhuangbao/HappyShoppingApp.apk",    " Version ": 2}



Android about version update issues

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.