Android prompt version update operation flow

Source: Internet
Author: User
Tags vps

Android Prompt version update operation flow

May 8, 2014:

Andorid app will have version update operation, today's idle time spent a bit of thought, the main technical aspects of the use of Asynctask asynchronous loading, HTTP protocol, JSON parsing, get version number, etc...

Let's introduce the approximate process, first of all:

Activity_main.xml:

    <button         android:id= "@+id/chek_newest_version"        android:layout_width= "fill_parent"        android:layout _height= "Wrap_content"        android:layout_margin= "5dip"        android:text= "detect latest Version"/>


I just used a button here!

Next mainactivity code:

Asynchronous loading is started to handle, if the old version is less than the new version number, start the download operation, otherwise it will not be updated!

Take a step-by-step look!

public class Mainactivity extends Activity {Button m_btnchecknewestversion;long m_newvercode;//version number of the latest version string m_ Newvername; The version name of the latest edition is String m_appnamestr; Download to local name handler M_mainhandler to give this app a life; ProgressDialog M_progressdlg; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main);//Initialize related variable initvariable (); m_ Btnchecknewestversion.setonclicklistener (Btnclicklistener);} private void Initvariable () {m_btnchecknewestversion = (Button) Findviewbyid (r.id.chek_newest_version); M_mainhandler = new Handler (); M_progressdlg = new ProgressDialog (this); M_progressdlg.setprogressstyle (Progressdialog.style_ horizontal);    Sets whether the ProgressDialog progress bar is not explicitly false is not set to ambiguous m_progressdlg.setindeterminate (false); M_appnamestr = "haha.apk";} Onclicklistener Btnclicklistener = new View.onclicklistener () {@Overridepublic void OnClick (View v) {//TODO Auto-generat Ed method Stubnew Checknewestversionasynctask (). Execute ();}; Class ChecknewestVersionasynctask extends Asynctask<void, void, boolean>{@Overrideprotected Boolean doinbackground (void ... params) {//TODO auto-generated method Stubif (Postchecknewestversioncommand2server ()) {int vercode = Common.getvercode ( Getapplicationcontext ());         Use the method written in the first section above if (M_newvercode > Vercode) {return true;         } else {return false; }}return false;} @Overrideprotected void OnPostExecute (Boolean result) {//TODO auto-generated method stubif (Result) {// If you have the latest version donewversionupdate (); Update new version}else {notnewversiondlgshow ();//Prompt is currently the latest version}super.onpostexecute (result);} @Overrideprotected void OnPreExecute () {//TODO auto-generated method Stubsuper.onpreexecute ();}} /** * Gets the current latest version number from the server, if successful return ture, if failed, returns false * @return */private Boolean postchecknewestversioncommand2server () { StringBuilder builder = new StringBuilder (); Jsonarray Jsonarray = null;try {//Construct Post method {Name:value} parameter to list<namevaluepair> VPS = new Arraylist<namevaluePair> ();//pass parameters into the Post method Vps.add (new Basicnamevaluepair ("Action", "Checknewestversion"); builder = Common.post_to_ Server (VPS); LOG.E ("msg", Builder.tostring ()), Jsonarray = new Jsonarray (builder.tostring ()), if (Jsonarray.length () >0) {if ( Jsonarray.getjsonobject (0). GETINT ("id") = = 1) {m_newvername = Jsonarray.getjsonobject (0). getString ("Vername"); m_ Newvercode = Jsonarray.getjsonobject (0). Getlong ("Vercode"); return true;}} return false;} catch (Exception e) {log.e ("msg", E.getmessage ()); M_newvername= ""; M_newvercode=-1;return false;}}      /** * Hint update new version */private void Donewversionupdate () {int vercode = Common.getvercode (Getapplicationcontext ());          String vername = Common.getvername (Getapplicationcontext ()); String str= "Current version:" +vername+ "code:" +vercode+ ", found the new version:" +m_newvername+ "Code:" +m_newvercode+ ", is it updated?      "; Dialog Dialog = new Alertdialog.builder (this). Settitle ("Software Update"). Setmessage (str)//setup content. setposit Ivebutton ("Update",//Set OK button nEW Dialoginterface.onclicklistener () {@Override public void OnClick (Dia Loginterface dialog, int which) {M_progressdlg.settitle ("under                              ");                              M_progressdlg.setmessage ("Please wait ...");  Downfile (common.updatesoftaddress); Start download}). Setnegativebutton ("Not updated", New D                                  Ialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog,                          int Whichbutton) {//click "Cancel" button to exit the program after finish ();  }). Create ();//Creates a dialog box Dialog.show ();      }/** * Hint is currently the latest version */private void Notnewversiondlgshow () {int vercode = Common.getvercode (this);     String Vername = Common.getvername (this); StringStr= "Current version:" +vername+ "Code:" +vercode+ ",/n is the latest version, no need to update!"; Dialog Dialog = new Alertdialog.builder (this). Settitle ("Software Update"). Setmessage (str)//set content. setposit                          Ivebutton ("OK",//Set OK button new Dialoginterface.onclicklistener () {@Override                              public void OnClick (Dialoginterface dialog, int which) {                          Finish ();  }). Create ();//Creates a dialog box Dialog.show ();      }private void Downfile (final String URL) {m_progressdlg.show ();              New Thread () {public void run () {HttpClient client = new Defaulthttpclient ();              HttpGet get = new HttpGet (URL);              HttpResponse response;                  try {response = Client.execute (get);                  httpentity entity = response.getentity ();         Long length = Entity.getcontentlength ();                         M_progressdlg.setmax (int) length);//Set the maximum value of the progress bar inputstream is = ent                  Ity.getcontent ();                  FileOutputStream fileoutputstream = null; if (is = null) {File File = new file (Environment.getexternalstoragedi                      Rectory (), M_APPNAMESTR);                      FileOutputStream = new FileOutputStream (file);                      byte[] buf = new byte[1024];                      int ch =-1;                      int count = 0;                          while (ch = is.read (BUF))! =-1) {fileoutputstream.write (buf, 0, ch);                          Count + = ch;                        if (length > 0) {m_progressdlg.setprogress (count);                  }}} Fileoutputstream.flush (); if (FileOutputStream! = null){Fileoutputstream.close ();  } down ();              Tell hander that the download is complete and that you can install the} catch (Clientprotocolexception e) {e.printstacktrace ();              } catch (IOException e) {e.printstacktrace ();  }}}.start (); }/** * Tell hander that the download is complete, you can install the */private void Down () {M_mainhandler.post (new Runnable () {public void run                () {m_progressdlg.cancel ();            Update (); }        });}        /** * Setup program */void Update () {Intent Intent = new Intent (Intent.action_view);                Intent.setdataandtype (Uri.fromfile (New File (Environment. getExternalStorageDirectory (), m_appnamestr)),        "Application/vnd.android.package-archive");    StartActivity (Intent); }}


Finally, the Common.java class:

Similar to a tool class, a lot of methods are written in here, after the download is complete, start to perform the installation operation!

public class Common {public static final string server_ip= "http://192.168.1.105/";p ublic static final string Server_addre ss=server_ip+ "try_downloadfile_progress_server/index.php";//Software update package address public static final String updatesoftaddress= server_ip+ "try_downloadfile_progress_server/update_pakage/baidu.apk";//Software update package address/** * Send a query request to the server, Returns the StringBuilder type data found * * @param ArrayList * <NameValuePair> VPS Post incoming parameter pairs * @return StringBuilder Bui Lder return results found * @throws Exception */public static StringBuilder post_to_server (list<namevaluepair> VPS) { Defaulthttpclient httpclient = new defaulthttpclient (); try {httpresponse response = null;//Create Httpost. Accessing the local server URL HttpPost Httpost = new HttpPost (server_address); StringBuilder builder = new StringBuilder (); Httpost.setentity (New Urlencodedformentity (VPS, HTTP. utf_8)); response = Httpclient.execute (httpost); Executes if (response.getentity () = null) {//If the server-side JSON is not written to, this is an exception and is not performed bufferedreader reader = new BufferedReader (New in Putstreamreader(Response.getentity (). GetContent ())); String s = reader.readline (); for (; s! = null; s = Reader.readline ()) {builder.append (s);}} return builder;} catch (Exception e) {//Todo:handle EXCEPTIONLOG.E ("msg", E.getmessage ()); return null;} finally {try { Httpclient.getconnectionmanager (). Shutdown ()//close connection//both of the methods of releasing the connection can be} catch (Exception e) {//TODO auto-generated catch BLOCKLOG.E ("msg", E.getmessage ());}}}        /** * Get software version number * @param context * @return */public static int Getvercode (context context) {int vercode =-1; try {//Note: "Com.example.try_downloadfile_progress" corresponds to Androidmanifest.xml in package= "..." section Vercode = Cont        Ext.getpackagemanager (). Getpackageinfo ("Com.example.try_downloadfile_progress", 0). Versioncode;        } catch (Namenotfoundexception e) {log.e ("msg", E.getmessage ());    } return Vercode; }/** * Gets the version name * @param context * @return */public static String Getvername (context context) {St Ring vername = ""; try {vername = Context.getpackagemanager (). Getpackageinfo ("Com.example.try_downloadfile_pr        Ogress ", 0). Versionname;        } catch (Namenotfoundexception e) {log.e ("msg", E.getmessage ());   } return vername; }

Already posted!

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.