Android prompt version update operation procedure

Source: Internet
Author: User
Tags vps

Android prompt version update operation procedure

April May 8, 2014:

All Android apps have version update operations. When I was idle today, I thought about it, the main technical aspects include AsyncTask asynchronous loading, http protocol, json parsing, and version number retrieval...

The following describes the general process:

Activity_main.xml:

    


Here I only use one button!

The mainactivity code is as follows:

Asynchronous loading is enabled for processing. If the old version is earlier than the new version, the download operation starts. Otherwise, the update will not be performed!

Step by step!

Public class MainActivity extends Activity {Button m_btnCheckNewestVersion; long m_newVerCode; // The latest version number String m_newVerName; // The latest version name String m_appNameStr; // The name Handler m_mainHandler of the APP to be downloaded locally; ProgressDialog m_progressDlg; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); // initialization 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 whether the progress bar of ProgressDialog is ambiguous. false means m_progressDlg.setIndeterminate (false); m_appNameStr = "haha.apk";} OnClickListener btnClickListener = new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubnew checknewestversionasynctask(.exe cute () ;}; class checkNewestVersionAsyncTask extends AsyncTask
 
  
{@ Overrideprotected Boolean doInBackground (Void... params) {// TODO Auto-generated method stubif (postCheckNewestVersionCommand2Server () {int vercode = Common. getVerCode (getApplicationContext (); // use the method written in the previous section if (m_newVerCode> vercode) {return true;} else {return false ;} @ Overrideprotected void onPostExecute (Boolean result) {// TODO Auto-generated method stubif (result) {// if the latest version of doNewVersionUpdate () is available (); // update new version} else {notNewVersionDlgShow (); // The latest version is displayed.} super. onPostExecute (result) ;}@ Overrideprotected void onPreExecute () {// TODO Auto-generated method stubsuper. onPreExecute () ;}}/*** get the latest version number from the server. If the current version number is successful, true is returned. If the current version number fails, FALSE * @ return */private Boolean postCheckNewestVersionCommand2Server () is returned () {StringBuilder builder = new StringBuilder (); JSONArray jsonArray = null; try {// construct the {name: value} parameter of the POST method to List
  
   
Vps = new ArrayList
   
    
(); // Pass the parameter to the vps in the post method. 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"); r Eturn true ;}}return false;} catch (Exception e) {Log. e ("msg", e. getMessage (); m_newVerName = ""; m_newVerCode =-1; return false ;}/ *** new version */private void doNewVersionUpdate () {int verCode = Common. getVerCode (getApplicationContext (); String verName = Common. getVerName (getApplicationContext (); String str = "current version:" + verName + "Code:" + verCode + ", new version:" + m_newVerName + "Code: "+ m_newVerCode +", update? "; Dialog dialog = new AlertDialog. builder (this ). setTitle ("Software Update "). setMessage (str) // set the content. setPositiveButton ("Update", // set the OK button new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {m_progressDlg.setTitle ("downloading"); m_progressDlg.setMessage ("Please wait... "); downFile (Common. UPDATESOFTADDRESS); // start download }}). setNegativeButton ("not updated now", new DialogInterface. onClick Listener () {public void onClick (DialogInterface dialog, int whichButton) {// click the "cancel" button and exit the program finish ();}}). create (); // create // display the dialog box dialog. show ();}/*** prompts the latest version */private void notNewVersionDlgShow () {int verCode = Common. getVerCode (this); String verName = Common. getVerName (this); String str = "current version:" + verName + "Code:" + verCode + ",/n is the latest version, no updates required! "; Dialog dialog = new AlertDialog. builder (this ). setTitle ("Software Update "). setMessage (str) // set the content. setPositiveButton ("OK", // set the OK button new DialogInterface. onClickListener () {@ Override public void onClick (DialogInterface dialog, int which) {finish ();}}). create (); // create // display the 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.exe cute (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. getExternalStorageDirectory (), 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 (); // tells HANDER that the download is complete. You can install} catch (ClientProtocolException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}. start ();}/*** tells HANDER that the download is complete. You can install */private void down () {m_mainHandler.post (new Runnable () {public void run () {m_progressDlg.cancel (); update () ;}}) ;}/ *** installer */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, many methods are written here. After the download is complete, start the installation operation!

Public class Common {public static final String SERVER_IP = "http: // 192.168.1.105/"; public static final String SERVER_ADDRESS = SERVER_IP + "try_downloadFile_progress_server/index. php "; // public static final String UPDATESOFTADDRESS = SERVER_IP +" try_downloadFile_progress_server/update_pakage/baidu.apk "; // The software update package address/*** sends a query request to the server and returns the StringBuilder type data. ** @ param ArrayList *
 
  
Parameter value pairs in vps POST * @ return StringBuilder builder returns the result * @ throws Exception */public static StringBuilder post_to_server (List
  
   
Vps) {DefaultHttpClient httpclient = new DefaultHttpClient (); try {HttpResponse response = null; // create httpost. visit the local server URL HttpPost httpost = new HttpPost (SERVER_ADDRESS); StringBuilder builder = new StringBuilder (); httpost. setEntity (new UrlEncodedFormEntity (vps, HTTP. UTF_8); response = httpclient.exe cute (httpost); // execute if (response. getEntity ()! = Null) {// if the server side JSON is not correctly written, this sentence will cause an exception. It is because 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 the connection // both methods can release the connection} catch (Exception e) {// TODO Auto-generated catch blockLog. e ("msg", e. getMessage () ;}}/ *** obtain the software version * @ param context * @ return */public static int getVerCode (Co Ntext context) {int verCode =-1; try {// note: "com. example. try_downloadfile_progress" corresponds to package = "...... "Part verCode = context. getPackageManager (). getPackageInfo ("com. example. try_downloadfile_progress ", 0 ). versionCode;} catch (NameNotFoundException e) {Log. e ("msg", e. getMessage ();} return verCode;}/*** get version name * @ param context * @ return */public static String getVerName (Context context) {String verName = ""; try {verName = context. getPackageManager (). getPackageInfo ("com. example. try_downloadfile_progress ", 0 ). versionName;} catch (NameNotFoundException e) {Log. e ("msg", e. getMessage ();} return verName ;}
  
 

Already pasted!

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.