Android Prompt version number update operation Flow
May 8, 2014:
Andorid app will have version number update operation, today spare time took a little thought to get a bit. The main technical aspects of the use of Asynctask asynchronous loading, HTTP protocol, JSON parsing, get version number and so on.
。
Let's take a look at 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= "Check the latest version number"/>
I'm just using a button here!
Next mainactivity code:
Initiates asynchronous loading to handle, assuming that the old version number is less than the new version number, start running 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 number of the latest version is named 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); Set the ProgressDialog progress bar is not clear false is not set to not understand 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) {// Suppose there is the latest version number Donewversionupdate (); Update the new version number}else {notnewversiondlgshow ();//Prompt is currently the latest version number}super.onpostexecute (result);} @Overrideprotected void OnPreExecute () {//TODO auto-generated method Stubsuper.onpreexecute ();}} /** * Obtain the current latest version number from the server, assuming the successful return of ture, assuming that the failure. Returns false * @return */private Boolean postchecknewestversioncommand2server () {StringBuilder builder = new StringBuilder (); Jsonarray Jsonarray = null;try {//Construct Post method {Name:value} parameters to list<namevaluepair> VPS = new Arraylist<namEvaluepair> ();//pass the reference 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 number */private void Donewversionupdate () {int vercode = Common.getvercode (Getapplicationcontext ()); String vername = Common.getvername (Getapplicationcontext ()); String str= "Current version number:" +vername+ "code:" +vercode+ ", found the new version number:" +m_newvername+ "Code:" +m_newvercode+ ", is it updated? "; Dialog Dialog = new Alertdialog.builder (this). Settitle ("Software Update"). Setmessage (str)//setup content. setposit Ivebutton ("Update",//settings OK button New Dialoginterface.onclicklistener () {@Override public voi D OnClick (dialoginterface dialog, int which) {M_progressdlg. Settitle ("Downloading"); M_progressdlg.setmessage ("Please wait ..."); Downfile (common.updatesoftaddress); Start the 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 number */private void Notnewversiondlgshow () {int vercode = Common.getvercode (this); String vername = Common.getvername (this); String str= "Current version number:" +vername+ "Code:" +vercode+ ",/n is the latest version, no update required!"; Dialog Dialog = new Alertdialog.builder (this). Settitle ("Software Update"). Setmessage (str)//set content. setposit Ivebutton ("OK",//settings OK button new Dialoginterface.onclicklistener () {@Overri De 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 = Entity.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 it has been downloaded and can install the} catch (Clientprotocolexception e) {e.printstacktrace (); } catch (IOException e) {e.printstacktrace (); }}}.start (); }/** * Tell hander already downloaded, can install */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. Very many methods are written in this area. When the download is complete, start 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 coming in to the value of * @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. Visit 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); Run if (response.getentity () = null) {//Assume that the server-side JSON is not written to. This sentence is going to be abnormal. is run just go to the bufferedreader reader = new BufferedReader (New InputStreamReader(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 to release the connection can} 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" in the corresponding Androidmanifest.xml package= "..." section vercode = Con Text.getpackagemanager (). Getpackageinfo ("Com.example.try_downloadfile_progress", 0). Versioncode; } catch (Namenotfoundexception e) {log.e ("msg", E.getmessage ()); } return Vercode; /** * Gets the version number name * @param context * @return */public static String Getvername (context context) {S TRing Vername = ""; try {vername = Context.getpackagemanager (). Getpackageinfo ("Com.example.try_downloadfile_pr Ogress ", 0). Versionname; } catch (Namenotfoundexception e) {log.e ("msg", E.getmessage ()); } return vername; }
has been posted to finish!
Android prompt version number update operation flow