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:
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.example.try_downloadfile_progress"
- android:versionCode="1"
- 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:
- /**
- * Get the software version number
- * @param context
- * @return
- */
- public static int getVerCode(Context context) {
- int verCode = -1;
- try {
- //Note: "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;
- }
/** * 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:
- <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>
<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:
- 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_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 and return the StringBuilder type data found
- *
- * @param ArrayList
- * <NameValuePair> vps POST Incoming pairs of parameters
- * @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 web site
- 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 correctly written, 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: "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;
- }
- }
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:
- <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>
<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:
- 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_newVerCode; //The latest version number
- String m_newVerName; //The name of the latest edition
- 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 setting ProgressDialog is ambiguous or not 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 {
- notNewVersionDlgShow(); //Prompt that the current version is the latest.
- }
- 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 the new version:"+m_newVerName+
- " Code:"+m_newVerCode+" ,Are they updated?;
- Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update").setMessage(str)
- //Setting up content
- .setPositiveButton("Update ",//Set the confirmation button.
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog,
- int which) {
- m_progressDlg.setTitle("Downloading");
- m_progressDlg.setMessage("Just a moment, please.);
- downFile(Common.UPDATESOFTADDRESS); //Start downloading
- }
- })
- .setNegativeButton("Not updated for the time being",
- 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 It's the latest edition,No need to update!";
- Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update")
- .setMessage(str)//Setting up content
- .setPositiveButton("Confirm ",//Set the confirmation 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 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);
- }
- }
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
- 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 {
- notNewVersionDlgShow(); //Prompt that the current version is the latest.
- }
- super.onPostExecute(result);
- }
- @Override
- protected void onPreExecute() {
- // TODO Auto-generated method stub
- super.onPreExecute();
- }
- }
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 ():
- 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;
- }
- }
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:
- [{"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:
- private void doNewVersionUpdate() {
- int verCode = Common.getVerCode(getApplicationContext());
- String verName = Common.getVerName(getApplicationContext());
- String str= "Current version:"+verName+" Code:"+verCode+" ,Discover the new version:"+m_newVerName+
- " Code:"+m_newVerCode+" ,Are they updated?;
- Dialog dialog = new AlertDialog.Builder(this).setTitle("Software Update").setMessage(str)
- //Setting up content
- .setPositiveButton("Update ",//Set the confirmation button.
- new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog,
- int which) {
- m_progressDlg.setTitle("Downloading");
- m_progressDlg.setMessage("Just a moment, please.);
- downFile(Common.UPDATESOFTADDRESS); //Start downloading
- }
- })
- .setNegativeButton("Not updated for the time being",
- 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();
- }
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:
- 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 > 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();
- }
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 > 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:
- /
- tell HANDER The download is complete and you can install it.
- /
- private void down() {
- m_mainHandler.post(new Runnable() {
- public void run() {
- m_progressDlg.cancel();
- update();
- }
- });
- }
- /
- Erection sequence
- /
- 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);
- }
/**
* 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.