Android prompt version update

Keywords: Android Apache Java xml

Foreword: At the end of software development, we should all encounter this problem. Fortunately, there are a lot of information on the internet, so it's almost done with little effort. Now it's recorded. Used here PHP The server.

Effects: (PHP Server)

After testing, if it is the latest version

                                        

If it's not the latest version, prompt for updates. Download. Install new programs.

     

I. Preparing Knowledge

Define each in Android Manifest.xml Android The version identifier of apk:

  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     package="com.example.try_downloadfile_progress"  
  3.     android:versionCode="1"  
  4.     android:versionName="1.0" >  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.try_downloadfile_progress"
    android:versionCode="1"
    android:versionName="1.0" >

Among them, android: version code and android: version Name fields represent version code and version name respectively. versionCode is an integer number and versionName is a string. Because version is for users to see, it is not easy to compare sizes, upgrade checks, you can check version Code mainly, to facilitate the comparison of the size of the publication before and after.
So how do you read version Code and version Name in Android Manifest. XML in your application? You can use the PackageManager API, refer to the following code:

  1.     /** 
  2.      * Get the software version number 
  3.      * @param context 
  4.      * @return 
  5.      */  
  6.     public static int getVerCode(Context context) {  
  7.         int verCode = -1;  
  8.         try {  
  9.             //Note: "com. example. try_download file_progress" corresponds to package ="..." in Android Manifest. xml. Part  
  10.             verCode = context.getPackageManager().getPackageInfo(  
  11.                     "com.example.try_downloadfile_progress"0).versionCode;  
  12.         } catch (NameNotFoundException e) {  
  13.             Log.e("msg",e.getMessage());  
  14.         }  
  15.         return verCode;  
  16.     }  
  17.    /** 
  18.     * Get version name 
  19.     * @param context 
  20.     * @return 
  21.     */  
  22.     public static String getVerName(Context context) {  
  23.         String verName = "";  
  24.         try {  
  25.             verName = context.getPackageManager().getPackageInfo(  
  26.                     "com.example.try_downloadfile_progress"0).versionName;  
  27.         } catch (NameNotFoundException e) {  
  28.             Log.e("msg",e.getMessage());  
  29.         }  
  30.         return verName;     
  31. }  
    /**
     * Get the software version number
     * @param context
     * @return
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            // Note that "com. example. try_download file_progress" corresponds to package="... in Android Manifest. xml. "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;   
}

Here's one thing to note: the "com. example. try_download file_progress" in the code corresponds to the package="... In Android Manifest. xml. Part

II. XML Code

The XML code is very simple, just like the initialization interface, adding a BUTTON to it. The code is as follows:

  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     tools:context=".MainActivity" >  
  6.   
  7.     <Button   
  8.         android:id="@+id/chek_newest_version"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_margin="5dip"  
  12.         android:text="Check the latest version"/>  
  13.   
  14. </RelativeLayout>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".MainActivity" >

    <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"/>

</RelativeLayout>

3. Auxiliary Class Construction (Common)

In order to develop conveniently, some common functions are implemented in Common class separately. The code is as follows:

  1. package com.example.try_downloadfile_progress;  
  2. /** 
  3.  * @author harvic 
  4.  * @date 2014-5-7 
  5.  * @address http://blog.csdn.net/harvic880925 
  6.  */  
  7. import java.io.BufferedReader;  
  8. import java.io.InputStreamReader;  
  9. import java.util.List;  
  10.   
  11. import org.apache.http.HttpResponse;  
  12. import org.apache.http.NameValuePair;  
  13. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  14. import org.apache.http.client.methods.HttpPost;  
  15. import org.apache.http.impl.client.DefaultHttpClient;  
  16. import org.apache.http.protocol.HTTP;  
  17.   
  18. import android.content.Context;  
  19. import android.content.pm.PackageManager.NameNotFoundException;  
  20. import android.util.Log;  
  21.   
  22. public class Common {  
  23.     public static final String SERVER_IP="http://192.168.1.105/";  
  24.     public static final String SERVER_ADDRESS=SERVER_IP+"try_downloadFile_progress_server/index.php";//Software update package address  
  25.     public static final String UPDATESOFTADDRESS=SERVER_IP+"try_downloadFile_progress_server/update_pakage/baidu.apk";//Software update package address  
  26.   
  27.     /** 
  28.      * Send a query request to the server and return the StringBuilder type data found 
  29.      *  
  30.      * @param ArrayList 
  31.      *            <NameValuePair> vps POST Incoming pairs of parameters 
  32.      * @return StringBuilder builder Returns the results found 
  33.      * @throws Exception 
  34.      */  
  35.     public static StringBuilder post_to_server(List<NameValuePair> vps) {  
  36.         DefaultHttpClient httpclient = new DefaultHttpClient();  
  37.         try {  
  38.             HttpResponse response = null;  
  39.             //Create httpost. Access the local server web site  
  40.             HttpPost httpost = new HttpPost(SERVER_ADDRESS);  
  41.             StringBuilder builder = new StringBuilder();  
  42.   
  43.             httpost.setEntity(new UrlEncodedFormEntity(vps, HTTP.UTF_8));  
  44.             response = httpclient.execute(httpost); //Execution  
  45.   
  46.             if (response.getEntity() != null) {  
  47.                 //If the server-side JSON is not correctly written, this sentence will be exceptional and can not be executed.  
  48.                 BufferedReader reader = new BufferedReader(  
  49.                         new InputStreamReader(response.getEntity().getContent()));  
  50.                 String s = reader.readLine();  
  51.                 for (; s != null; s = reader.readLine()) {  
  52.                     builder.append(s);  
  53.                 }  
  54.             }  
  55.             return builder;  
  56.   
  57.         } catch (Exception e) {  
  58.             // TODO: handle exception  
  59.             Log.e("msg",e.getMessage());  
  60.             return null;  
  61.         } finally {  
  62.             try {  
  63.                 httpclient.getConnectionManager().shutdown();//Close the connection  
  64.                 //Both methods of releasing connections can be used  
  65.             } catch (Exception e) {  
  66.                 // TODO Auto-generated catch block  
  67.                 Log.e("msg",e.getMessage());  
  68.             }  
  69.         }  
  70.     }  
  71.       
  72.     /** 
  73.      * Get the software version number 
  74.      * @param context 
  75.      * @return 
  76.      */  
  77.     public static int getVerCode(Context context) {  
  78.         int verCode = -1;  
  79.         try {  
  80.             //Note: "com. example. try_download file_progress" corresponds to package ="..." in Android Manifest. xml. Part  
  81.             verCode = context.getPackageManager().getPackageInfo(  
  82.                     "com.example.try_downloadfile_progress"0).versionCode;  
  83.         } catch (NameNotFoundException e) {  
  84.             Log.e("msg",e.getMessage());  
  85.         }  
  86.         return verCode;  
  87.     }  
  88.    /** 
  89.     * Get version name 
  90.     * @param context 
  91.     * @return 
  92.     */  
  93.     public static String getVerName(Context context) {  
  94.         String verName = "";  
  95.         try {  
  96.             verName = context.getPackageManager().getPackageInfo(  
  97.                     "com.example.try_downloadfile_progress"0).versionName;  
  98.         } catch (NameNotFoundException e) {  
  99.             Log.e("msg",e.getMessage());  
  100.         }  
  101.         return verName;     
  102. }     
  103.       
  104. }  
package com.example.try_downloadfile_progress;
/**
 * @author harvic
 * @date 2014-5-7
 * @address http://blog.csdn.net/harvic880925
 */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.util.Log;

public class Common {
    public static final String SERVER_IP="http://192.168.1.105/";
    Public static final String SERVER_ADDRESS = SERVER_IP+ "try_download File_progress_server/index.php"; //Software update package address
    Public static final String UPDATESOFTADDRESS = SERVER_IP+ "try_download File_progress_server/update_pakage/baidu.apk";//software update package address

    /**
     * Send a query request to the server and return the StringBuilder type data found
     * 
     * @param ArrayList
     * <NameValuePair> VPS POST incoming parameter pairs
     *@ return StringBuilder builder returns the results found
     * @throws Exception
     */
    public static StringBuilder post_to_server(List<NameValuePair> vps) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {
            HttpResponse response = null;
            // Create httpost. Access the local server address
            HttpPost httpost = new HttpPost(SERVER_ADDRESS);
            StringBuilder builder = new StringBuilder();

            httpost.setEntity(new UrlEncodedFormEntity(vps, HTTP.UTF_8));
            response = httpclient.execute(httpost);//execution

            if (response.getEntity() != null) {
                // If the server-side JSON is not written correctly, this sentence will be exceptional and can not be executed.
                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 exception
            Log.e("msg",e.getMessage());
            return null;
        } finally {
            try {
                httpclient.getConnectionManager().shutdown(); // Close the connection
                // Both methods of releasing connections can be used.
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e("msg",e.getMessage());
            }
        }
    }

    /**
     * Get the software version number
     * @param context
     * @return
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            // Note that "com. example. try_download file_progress" corresponds to package="... in Android Manifest. xml. "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;   
}   

}


In addition to the two functions getVerCode and getVerName mentioned above, there are several constants and a function definition with the following meanings:

SERVER_IP: Server IP address (when you get the test, you need to change it to your own server IP address)
SERVER_ADDRESS: The android program does not need to change the page address to which the request is sent.
UPDATE SOFTADDRESS: Update the location of the installation package without changing it.

The function StringBuilder post_to_server (List < NameValuePair > vps) is a functional encapsulation that accesses the server and returns the results. Pass in the name-value pair and return the StringBuilder object

4. Code Construction of Home Page

1. Set up AndroidManifest.xml to access the network and SD card.

On the </manifest> tab, add:

  1. <uses-permission android:name="android.permission.INTERNET" >  
  2. </uses-permission>  
  3. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >  
  4. </uses-permission>  
  5. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >  
  6. </uses-permission>  
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>

2. Home page code:

First paste out all the code, then explain it step by step. The whole code is as follows:

  1. package com.example.try_downloadfile_progress;  
  2. /** 
  3.  * @author harvic 
  4.  * @date 2014-5-7 
  5.  * @address http://blog.csdn.net/harvic880925 
  6.  */  
  7. import java.io.File;  
  8. import java.io.FileOutputStream;  
  9. import java.io.IOException;  
  10. import java.io.InputStream;  
  11. import java.util.ArrayList;  
  12. import java.util.List;  
  13.   
  14. import org.apache.http.HttpEntity;  
  15. import org.apache.http.HttpResponse;  
  16. import org.apache.http.NameValuePair;  
  17. import org.apache.http.client.ClientProtocolException;  
  18. import org.apache.http.client.HttpClient;  
  19. import org.apache.http.client.methods.HttpGet;  
  20. import org.apache.http.impl.client.DefaultHttpClient;  
  21. import org.apache.http.message.BasicNameValuePair;  
  22. import org.json.JSONArray;  
  23.   
  24. import android.net.Uri;  
  25. import android.os.AsyncTask;  
  26. import android.os.Bundle;  
  27. import android.os.Environment;  
  28. import android.os.Handler;  
  29. import android.app.Activity;  
  30. import android.app.AlertDialog;  
  31. import android.app.Dialog;  
  32. import android.app.ProgressDialog;  
  33. import android.content.DialogInterface;  
  34. import android.content.Intent;  
  35. import android.util.Log;  
  36. import android.view.View;  
  37. import android.view.View.OnClickListener;  
  38. import android.widget.Button;  
  39.   
  40. public class MainActivity extends Activity {  
  41.   
  42.     Button m_btnCheckNewestVersion;  
  43.     long m_newVerCode; //The latest version number  
  44.     String m_newVerName; //The name of the latest edition  
  45.     String m_appNameStr; //Download to the local name to give this APP life  
  46.       
  47.     Handler m_mainHandler;  
  48.     ProgressDialog m_progressDlg;  
  49.     @Override  
  50.     protected void onCreate(Bundle savedInstanceState) {  
  51.         super.onCreate(savedInstanceState);  
  52.         setContentView(R.layout.activity_main);  
  53.           
  54.         //Initialization of related variables  
  55.         initVariable();  
  56.           
  57.         m_btnCheckNewestVersion.setOnClickListener(btnClickListener);  
  58.     }  
  59.     private void initVariable()  
  60.     {  
  61.         m_btnCheckNewestVersion = (Button)findViewById(R.id.chek_newest_version);  
  62.         m_mainHandler = new Handler();  
  63.         m_progressDlg =  new ProgressDialog(this);  
  64.         m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);  
  65.          //Whether the progress bar setting ProgressDialog is ambiguous or not is ambiguous.  
  66.         m_progressDlg.setIndeterminate(false);      
  67.         m_appNameStr = "haha.apk";  
  68.     }  
  69.       
  70.     OnClickListener btnClickListener = new View.OnClickListener() {  
  71.           
  72.         @Override  
  73.         public void onClick(View v) {  
  74.             // TODO Auto-generated method stub  
  75.             new checkNewestVersionAsyncTask().execute();  
  76.         }  
  77.     };  
  78.       
  79.     class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean>  
  80.     {  
  81.   
  82.         @Override  
  83.         protected Boolean doInBackground(Void… params) {  
  84.             // TODO Auto-generated method stub  
  85.             if(postCheckNewestVersionCommand2Server())  
  86.             {  
  87.                 int vercode = Common.getVerCode(getApplicationContext()); //Use the method described in the first section above.  
  88.                  if (m_newVerCode > vercode) {    
  89.                      return true;  
  90.                  } else {    
  91.                      return false;  
  92.                  }    
  93.             }  
  94.             return false;  
  95.         }  
  96.           
  97.         @Override  
  98.         protected void onPostExecute(Boolean result) {  
  99.             // TODO Auto-generated method stub  
  100.             if (result) {//If there is the latest version  
  101.                 doNewVersionUpdate(); //Update the new version  
  102.             }else {  
  103.                 notNewVersionDlgShow(); //Prompt that the current version is the latest.  
  104.             }  
  105.             super.onPostExecute(result);  
  106.         }  
  107.           
  108.         @Override  
  109.         protected void onPreExecute() {  
  110.             // TODO Auto-generated method stub  
  111.             super.onPreExecute();  
  112.         }  
  113.     }  
  114.       
  115.     /** 
  116.      * Get the current latest version number from the server, return TURE if successful, FALSE if unsuccessful 
  117.      * @return 
  118.      */  
  119.     private Boolean postCheckNewestVersionCommand2Server()  
  120.     {  
  121.         StringBuilder builder = new StringBuilder();  
  122.         JSONArray jsonArray = null;  
  123.         try {  
  124.             //Constructing {name:value} parameter pairs of POST methods  
  125.             List<NameValuePair> vps = new ArrayList<NameValuePair>();  
  126.             //Pass parameters into the post method  
  127.             vps.add(new BasicNameValuePair("action""checkNewestVersion"));  
  128.             builder = Common.post_to_server(vps);  
  129.             jsonArray = new JSONArray(builder.toString());  
  130.             if (jsonArray.length()>0) {  
  131.                 if (jsonArray.getJSONObject(0).getInt("id") == 1) {  
  132.                     m_newVerName = jsonArray.getJSONObject(0).getString("verName");  
  133.                     m_newVerCode = jsonArray.getJSONObject(0).getLong("verCode");  
  134.                       
  135.                     return true;  
  136.                 }  
  137.             }  
  138.       
  139.             return false;  
  140.         } catch (Exception e) {  
  141.             Log.e("msg",e.getMessage());  
  142.             m_newVerName="";  
  143.             m_newVerCode=-1;  
  144.             return false;  
  145.         }  
  146.     }  
  147.       
  148.     /** 
  149.      * Tips for updating new versions 
  150.      */  
  151.         private void doNewVersionUpdate() {  
  152.             int verCode = Common.getVerCode(getApplicationContext());    
  153.             String verName = Common.getVerName(getApplicationContext());    
  154.               
  155.             String str= "Current version:"+verName+" Code:"+verCode+" ,Discover the new version:"+m_newVerName+  
  156.                     " Code:"+m_newVerCode+" ,Are they updated?;    
  157.             Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update").setMessage(str)    
  158.                     //Setting up content  
  159.                     .setPositiveButton("Update ",//Set the confirmation button.  
  160.                             new DialogInterface.OnClickListener() {    
  161.                                 @Override    
  162.                                 public void onClick(DialogInterface dialog,    
  163.                                         int which) {   
  164.                                     m_progressDlg.setTitle("Downloading");    
  165.                                     m_progressDlg.setMessage("Just a moment, please.);    
  166.                                     downFile(Common.UPDATESOFTADDRESS);  //Start downloading  
  167.                                 }    
  168.                             })    
  169.                     .setNegativeButton("Not updated for the time being",    
  170.                             new DialogInterface.OnClickListener() {    
  171.                                 public void onClick(DialogInterface dialog,    
  172.                                         int whichButton) {    
  173.                                     //Click the Cancel button to exit the program.  
  174.                                     finish();    
  175.                                 }    
  176.                             }).create();//Create  
  177.             //Display dialog box  
  178.             dialog.show();    
  179.         }  
  180.         /** 
  181.          *  Hint that the current version is the latest. 
  182.          */  
  183.         private void notNewVersionDlgShow()  
  184.         {  
  185.             int verCode = Common.getVerCode(this);    
  186.             String verName = Common.getVerName(this);   
  187.             String str="current version:"+verName+" Code:"+verCode+",/n It's the latest edition,No need to update!";  
  188.             Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update")    
  189.                     .setMessage(str)//Setting up content  
  190.                     .setPositiveButton("Confirm ",//Set the confirmation button.  
  191.                             new DialogInterface.OnClickListener() {    
  192.                                 @Override    
  193.                                 public void onClick(DialogInterface dialog,    
  194.                                         int which) {    
  195.                                     finish();    
  196.                                 }    
  197.                             }).create();//Create  
  198.             //Display dialog box  
  199.             dialog.show();    
  200.         }  
  201.         private void downFile(final String url)  
  202.         {  
  203.             m_progressDlg.show();    
  204.             new Thread() {    
  205.                 public void run() {    
  206.                     HttpClient client = new DefaultHttpClient();    
  207.                     HttpGet get = new HttpGet(url);    
  208.                     HttpResponse response;    
  209.                     try {    
  210.                         response = client.execute(get);    
  211.                         HttpEntity entity = response.getEntity();    
  212.                         long length = entity.getContentLength();    
  213.                           
  214.                         m_progressDlg.setMax((int)length);//Set the maximum of progress bar  
  215.                           
  216.                         InputStream is = entity.getContent();    
  217.                         FileOutputStream fileOutputStream = null;    
  218.                         if (is != null) {    
  219.                             File file = new File(    
  220.                                     Environment.getExternalStorageDirectory(),    
  221.                                     m_appNameStr);    
  222.                             fileOutputStream = new FileOutputStream(file);    
  223.                             byte[] buf = new byte[1024];    
  224.                             int ch = -1;    
  225.                             int count = 0;    
  226.                             while ((ch = is.read(buf)) != -1) {    
  227.                                 fileOutputStream.write(buf, 0, ch);    
  228.                                 count += ch;    
  229.                                 if (length > 0) {    
  230.                                      m_progressDlg.setProgress(count);  
  231.                                 }    
  232.                             }    
  233.                         }    
  234.                         fileOutputStream.flush();    
  235.                         if (fileOutputStream != null) {    
  236.                             fileOutputStream.close();    
  237.                         }    
  238.                         down();    
  239.                     } catch (ClientProtocolException e) {    
  240.                         e.printStackTrace();    
  241.                     } catch (IOException e) {    
  242.                         e.printStackTrace();    
  243.                     }    
  244.                 }    
  245.             }.start();    
  246.         }  
  247.         private void down() {  
  248.             m_mainHandler.post(new Runnable() {  
  249.                 public void run() {  
  250.                     m_progressDlg.cancel();  
  251.                     update();  
  252.                 }  
  253.             });  
  254.     }  
  255.           
  256.         void update() {  
  257.             Intent intent = new Intent(Intent.ACTION_VIEW);  
  258.             intent.setDataAndType(Uri.fromFile(new File(Environment  
  259.                     .getExternalStorageDirectory(), m_appNameStr)),  
  260.                     "application/vnd.android.package-archive");  
  261.             startActivity(intent);  
  262.         }  
  263.   
  264.   
  265. }  
package com.example.try_downloadfile_progress;
/**
 * @author harvic
 * @date 2014-5-7
 * @address http://blog.csdn.net/harvic880925
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    Button m_btnCheckNewestVersion;
    Long m_new VerCode; // the latest version number
    String m_newVerName; // the latest version name
    String m_appNameStr; // Download to the local name to give this APP life

    Handler m_mainHandler;
    ProgressDialog m_progressDlg;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialization of related variables
        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);
         // Whether the progress bar for setting ProgressDialog is ambiguous or false is ambiguous     
        m_progressDlg.setIndeterminate(false);    
        m_appNameStr = "haha.apk";
    }

    OnClickListener btnClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new checkNewestVersionAsyncTask().execute();
        }
    };

    class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean>
    {

        @Override
        protected Boolean doInBackground(Void... params) {
            // TODO Auto-generated method stub
            if(postCheckNewestVersionCommand2Server())
            {
                int vercode = Common.getVerCode(getApplicationContext()); // Use the method described in the first section above  
                 if (m_newVerCode > vercode) {  
                     return true;
                 } else {  
                     return false;
                 }  
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            // TODO Auto-generated method stub
            if (result) {// If there is the latest version
                doNewVersionUpdate();// Update the new version  
            }else {
                Not New Version DlgShow (); // prompt is currently the latest version  
            }
            super.onPostExecute(result);
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
        }
    }

    /**
     * Get the current latest version number from the server, return TURE if successful, FALSE if unsuccessful
     * @return
     */
    private Boolean postCheckNewestVersionCommand2Server()
    {
        StringBuilder builder = new StringBuilder();
        JSONArray jsonArray = null;
        try {
            // Constructing {name:value} parameter pairs of POST methods
            List<NameValuePair> vps = new ArrayList<NameValuePair>();
            // Pass parameters into the post method
            vps.add(new BasicNameValuePair("action", "checkNewestVersion"));
            builder = Common.post_to_server(vps);
            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;
        }
    }

    /**
     * Tips for updating new versions
     */
        private void doNewVersionUpdate() {
            int verCode = Common.getVerCode(getApplicationContext());  
            String verName = Common.getVerName(getApplicationContext());  

            String str= "Current Version:"+verName+ "Code:"+verCode+", Discover New Version:"+m_newVerName+
                    "Code:"+m_newVerCode+", is it updated? ";  
            Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update"). setMessage(str)  
                    // Setting content  
                    setPositiveButton("Update", // Set Definition Button)  
                            new DialogInterface.OnClickListener() {  
                                @Override  
                                public void onClick(DialogInterface dialog,  
                                        int which) { 
                                    m_progressDlg.setTitle("Downloading");  
                                    m_progressDlg.setMessage("Please wait a minute...");  
                                    downFile(Common.UPDATESOFTADDRESS); // Start downloading
                                }  
                            })  
                    SetNegative Button ("Not updated yet")  
                            new DialogInterface.OnClickListener() {  
                                public void onClick(DialogInterface dialog,  
                                        int whichButton) {  
                                    // Click the Cancel button to exit the program  
                                    finish();  
                                }  
                            }) create(); // Create  
            // Display dialog box  
            dialog.show();  
        }
        /**
         * Hint that the current version is the latest  
         */
        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 need to update!"
            Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update")  
                    setMessage(str)// Setting Content  
                    setPositiveButton("OK", // Set the OK button  
                            new DialogInterface.OnClickListener() {  
                                @Override  
                                public void onClick(DialogInterface dialog,  
                                        int which) {  
                                    finish();  
                                }  
                            }) create(); // Create  
            // Display 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 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();  
                    } catch (ClientProtocolException e) {  
                        e.printStackTrace();  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }.start();  
        }
        private void down() {
            m_mainHandler.post(new Runnable() {
                public void run() {
                    m_progressDlg.cancel();
                    update();
                }
            });
    }

        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);
        }


}
Step by step:

1. OnCreate function:

Starting with the main function, OnCreate function has only two parts, one is initVariable() initialization variable, which is not too difficult to say much; the second is to set a listener function for version detection buttons, btnClickListener, which can be clearly seen in the btnClickListener function, and there is only one class checkNewVersion AsyncTask, where asynchronous mode is used. To deal with the problem of renewal. Let's look at the checkNewest Version AsyncTask function

2. checkNewest Version AsyncTask function

  1. class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean>  
  2. {  
  3.   
  4.     @Override  
  5.     protected Boolean doInBackground(Void… params) {  
  6.         // TODO Auto-generated method stub  
  7.         if(postCheckNewestVersionCommand2Server())  
  8.         {  
  9.             int vercode = Common.getVerCode(getApplicationContext()); //Use the method described in the first section above.  
  10.              if (m_newVerCode > vercode) {    
  11.                  return true;  
  12.              } else {    
  13.                  return false;  
  14.              }    
  15.         }  
  16.         return false;  
  17.     }  
  18.       
  19.     @Override  
  20.     protected void onPostExecute(Boolean result) {  
  21.         // TODO Auto-generated method stub  
  22.         if (result) {//If there is the latest version  
  23.             doNewVersionUpdate(); //Update the new version  
  24.         }else {  
  25.             notNewVersionDlgShow(); //Prompt that the current version is the latest.  
  26.         }  
  27.         super.onPostExecute(result);  
  28.     }  
  29.       
  30.     @Override  
  31.     protected void onPreExecute() {  
  32.         // TODO Auto-generated method stub  
  33.         super.onPreExecute();  
  34.     }  
  35. }  
class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean>
{

    @Override
    protected Boolean doInBackground(Void... params) {
        // TODO Auto-generated method stub
        if(postCheckNewestVersionCommand2Server())
        {
            int vercode = Common.getVerCode(getApplicationContext()); // Use the method described in the first section above  
             if (m_newVerCode > vercode) {  
                 return true;
             } else {  
                 return false;
             }  
        }
        return false;
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        if (result) {// If there is the latest version
            doNewVersionUpdate();// Update the new version  
        }else {
            Not New Version DlgShow (); // prompt is currently the latest version  
        }
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }
}

(1) First look at the background operation doInBackground

First, the request is sent to the server using the postCheckNewestVersionCommand2Server() function, which returns TRUE or FALSE successfully according to the request. Then the version code obtained from the server is compared with the local version code. If TRUE is to be updated, FASLE is to be returned if not updated.

Let's look at the code for postCheck Newest Version Command 2 Server ():

  1. private Boolean postCheckNewestVersionCommand2Server()  
  2. {  
  3.     StringBuilder builder = new StringBuilder();  
  4.     JSONArray jsonArray = null;  
  5.     try {  
  6.         //Constructing {name:value} parameter pairs of POST methods  
  7.         List<NameValuePair> vps = new ArrayList<NameValuePair>();  
  8.         //Pass parameters into the post method  
  9.         vps.add(new BasicNameValuePair("action""checkNewestVersion"));  
  10.         builder = Common.post_to_server(vps);  
  11.         jsonArray = new JSONArray(builder.toString());  
  12.         if (jsonArray.length()>0) {  
  13.             if (jsonArray.getJSONObject(0).getInt("id") == 1) {  
  14.                 m_newVerName = jsonArray.getJSONObject(0).getString("verName");  
  15.                 m_newVerCode = jsonArray.getJSONObject(0).getLong("verCode");  
  16.                   
  17.                 return true;  
  18.             }  
  19.         }  
  20.   
  21.         return false;  
  22.     } catch (Exception e) {  
  23.         Log.e("msg",e.getMessage());  
  24.         m_newVerName="";  
  25.         m_newVerCode=-1;  
  26.         return false;  
  27.     }  
  28. }  
private Boolean postCheckNewestVersionCommand2Server()
{
    StringBuilder builder = new StringBuilder();
    JSONArray jsonArray = null;
    try {
        // Constructing {name:value} parameter pairs of POST methods
        List<NameValuePair> vps = new ArrayList<NameValuePair>();
        // Pass parameters into the post method
        vps.add(new BasicNameValuePair("action", "checkNewestVersion"));
        builder = Common.post_to_server(vps);
        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;
    }
}

Here is to build a name-value pair and send it to the server. If it gets the value, it returns to TURE. If it does not, it returns to FALSE. The JSON value returned by the server is:

  1. [{"id":"1","verName":"1.0.1","verCode":"2"}]  
[{"id":"1","verName":"1.0.1","verCode":"2"}]

For server code, because it is written in PHP, it is no longer listed here. It is in the source code.

(2)onPostExecute()
Continue the first part, after the doInBackground operation is completed, if you need to update doInBackground to return TRUE, or FASLE, so in onPost Execute, you call different functions according to the result, using doNewVersionUpdate(); prompt users to update the latest version. Use notNewVersion DlgShow (); / prompt the user that the current version is the latest without updating.

For the notNewVersionDlgShow () function, it just creates a dialog box, without any entity content, so it will not be explained in detail. The following is a detailed description of the process of downloading, updating and installing the doNewVersionUpdate ().

3. doNewVersionUpdate() prompt version update
The code is as follows:

  1. private void doNewVersionUpdate() {  
  2.     int verCode = Common.getVerCode(getApplicationContext());    
  3.     String verName = Common.getVerName(getApplicationContext());    
  4.       
  5.     String str= "Current version:"+verName+" Code:"+verCode+" ,Discover the new version:"+m_newVerName+  
  6.             " Code:"+m_newVerCode+" ,Are they updated?;    
  7.     Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update").setMessage(str)    
  8.             //Setting up content  
  9.             .setPositiveButton("Update ",//Set the confirmation button.  
  10.                     new DialogInterface.OnClickListener() {    
  11.                         @Override    
  12.                         public void onClick(DialogInterface dialog,    
  13.                                 int which) {   
  14.                             m_progressDlg.setTitle("Downloading");    
  15.                             m_progressDlg.setMessage("Just a moment, please.);    
  16.                             downFile(Common.UPDATESOFTADDRESS);  //Start downloading  
  17.                         }    
  18.                     })    
  19.             .setNegativeButton("Not updated for the time being",    
  20.                     new DialogInterface.OnClickListener() {    
  21.                         public void onClick(DialogInterface dialog,    
  22.                                 int whichButton) {    
  23.                             //Click the Cancel button to exit the program.  
  24.                             finish();    
  25.                         }    
  26.                     }).create();//Create  
  27.     //Display dialog box  
  28.     dialog.show();    
  29. }  
private void doNewVersionUpdate() { 
int verCode = Common.getVerCode(getApplicationContext());
String verName = Common.getVerName(getApplicationContext());

String str= "Current version:"+verName+" Code:"+verCode+" ,Discovery of new versions of ___________"+m_newVerName+
        " Code:"+m_newVerCode+" ,Are they updated?";  
Dialog dialog = new AlertDialog.Builder(this).setTitle("Software update").setMessage(str)  
        // Set contents  
        .setPositiveButton("To update",// Set the confirmation button  
                new DialogInterface.OnClickListener() {  
                    @Override  
                    public void onClick(DialogInterface dialog,  
                            int which) { 
                        m_progressDlg.setTitle("Downloading");  
                        m_progressDlg.setMessage("Please wait a moment...");  
                        downFile(Common.UPDATESOFTADDRESS);  //Start downloading
                    }  
                })  
        .setNegativeButton("Not updated",  
                new DialogInterface.OnClickListener() {  
                    public void onClick(DialogInterface dialog,  
                            int whichButton) {  
                        // Click the Cancel button to exit the program  
                        finish();  
                    }  
                }).create();// Establish  
// display a dialog box  
dialog.show();  

}

A dialog box with the functions of confirm button and cancel button is created here. If the user clicks the cancel button, the program will be terminated by finish(); if the confirm button is clicked, the downFile(Common.UPDATESOFTADDRESS) will be used; and the downFile() function starts the download of the program, in which the parameter passed in by the downFile() function is the server address where APP is located. Note that the address here is specific to the download file, such as http://192.168.1.105/server/XXX.apk.

4. downFile(final String url) download and display progress

The code is as follows:

  1. private void downFile(final String url)  
  2. {  
  3.     m_progressDlg.show();    
  4.     new Thread() {    
  5.         public void run() {    
  6.             HttpClient client = new DefaultHttpClient();    
  7.             HttpGet get = new HttpGet(url);    
  8.             HttpResponse response;    
  9.             try {    
  10.                 response = client.execute(get);    
  11.                 HttpEntity entity = response.getEntity();    
  12.                 long length = entity.getContentLength();    
  13.                   
  14.                 m_progressDlg.setMax((int)length);//Set the maximum of progress bar  
  15.                   
  16.                 InputStream is = entity.getContent();    
  17.                 FileOutputStream fileOutputStream = null;    
  18.                 if (is != null) {    
  19.                     File file = new File(    
  20.                             Environment.getExternalStorageDirectory(),    
  21.                             m_appNameStr);    
  22.                     fileOutputStream = new FileOutputStream(file);    
  23.                     byte[] buf = new byte[1024];    
  24.                     int ch = -1;    
  25.                     int count = 0;    
  26.                     while ((ch = is.read(buf)) != -1) {    
  27.                         fileOutputStream.write(buf, 0, ch);    
  28.                         count += ch;    
  29.                         if (length > 0) {    
  30.                              m_progressDlg.setProgress(count);//Setting the current schedule  
  31.                         }    
  32.                     }    
  33.                 }    
  34.                 fileOutputStream.flush();    
  35.                 if (fileOutputStream != null) {    
  36.                     fileOutputStream.close();    
  37.                 }    
  38.                 down();  //Tell HANDER that it's downloaded and ready to install  
  39.             } catch (ClientProtocolException e) {    
  40.                 e.printStackTrace();    
  41.             } catch (IOException e) {    
  42.                 e.printStackTrace();    
  43.             }    
  44.         }    
  45.     }.start();    
  46. }  
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 of 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 &gt; 0) {  
                         m_progressDlg.setProgress(count);//Setting the current schedule
                    }  
                }  
            }  
            fileOutputStream.flush();  
            if (fileOutputStream != null) {  
                fileOutputStream.close();  
            }  
            down();  //Tell HANDER that it's downloaded and ready to install
        } catch (ClientProtocolException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}.start();  

}

By using the get method of httpClient, the content of the specified URL is obtained, and then written to the local SD card. For the progress bar, the maximum value of the progress bar is set by using m_progressDlg.setMax((int)length), and then the current progress is set by using m_progressDlg.setProgress(count) when reading the return result and writing to the local area. After all is written, the down() function is called to notify the HANDER installer.
5. Installation procedures

Installation program mainly uses the following two functions:

  1. / 
  2.   tell HANDER The download is complete and you can install it. 
  3.  /  
  4. private void down() {  
  5.         m_mainHandler.post(new Runnable() {  
  6.             public void run() {  
  7.                 m_progressDlg.cancel();  
  8.                 update();  
  9.             }  
  10.         });  
  11. }  
  12. / 
  13.   Erection sequence 
  14.  /  
  15. void update() {  
  16.     Intent intent = new Intent(Intent.ACTION_VIEW);  
  17.     intent.setDataAndType(Uri.fromFile(new File(Environment  
  18.             .getExternalStorageDirectory(), m_appNameStr)),  
  19.             "application/vnd.android.package-archive");  
  20.     startActivity(intent);  
  21. }  
/** 
* Tell HANDER that it's downloaded and ready to install
*/
private void down() {
m_mainHandler.post(new Runnable() {
public void run() {
m_progressDlg.cancel();
update();
}
});
}
/**
* Installation 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);
}

Because the UI must be operated in a single thread in an android program, it cannot be operated in a non-main thread, otherwise the program will crash.< AsnyncTask and handler(1) - AsyncTask asynchronous processing "And" AsnyncTask and handler(2) - handler message mechanism " So here's how handler is used to update the UI.

Okay, that's all. Here's the source code for client and server. Children who understand PHP have made a lot of money.

 

Source address: http://download.csdn.net/detail/harvic880925/7309013 Don't share, just share.

 

Please respect the author's original copyright, reproduced please indicate the source: http://blog.csdn.net/harvic880925/article/details/25191159 Thank you very much.

Posted by dallasx on Wed, 10 Apr 2019 21:33:31 -0700