AndroidAPP更新升級完整實現Demo


市場上的Android應用都能夠自動提示升級更新,這里就完整的來實現一下AndroidAPP,實現自動升級的功能。

Demo地址:http://download.csdn.net/detail/ericfantastic/9250609

效果圖:

具體如何實現,其實不難,先看看流程:

 

本地AndroidApp必須要先有一個版本號用於標識當前版本,再從服務器獲取服務器最新版本,進行相比較。

 

實現流程:

1、Manifest.xml添加聯網權限,讀寫SD卡權限,版本號versionCode和版本名versionName,其中versionCode用來比較版本使用的變量,versionName為用於顯示在界面上的版本字符串。

 

[html]  view plain  copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.eric.androidupdatedemo"  
  4.     android:versionCode="1"  
  5.     android:versionName="01.00.01" >  
  6.     <uses-permission android:name='android.permission.INTERNET'/> <!-- 聯網權限 -->  
  7.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  <!-- 寫入SD卡權限 -->  
  8.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    <!-- 在SD卡中創建和刪除文件的權限 -->  
  9.     <uses-sdk  
  10.         android:minSdkVersion="14"  
  11.         android:targetSdkVersion="14" />  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name=".MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  
[html]  view plain  copy
 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.eric.androidupdatedemo"  
  4.     android:versionCode="1"  
  5.     android:versionName="01.00.01" >  
  6.     <uses-permission android:name='android.permission.INTERNET'/> <!-- 聯網權限 -->  
  7.     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  <!-- 寫入SD卡權限 -->  
  8.     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>    <!-- 在SD卡中創建和刪除文件的權限 -->  
  9.     <uses-sdk  
  10.         android:minSdkVersion="14"  
  11.         android:targetSdkVersion="14" />  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name=".MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.     </application>  
  28.   
  29. </manifest>  


2、activity_main.xml布局文件,簡單的幾個控件。

 

 

[html]  view plain  copy
 
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context="com.eric.androidupdatedemo.MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:id="@+id/textview_id"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="@string/hello_world" />  
  16.       
  17.     <Button   
  18.         android:id="@+id/button_id"  
  19.         android:layout_width="fill_parent"  
  20.         android:layout_height="40dp"  
  21.         android:layout_below="@id/textview_id"  
  22.         android:textColor="#FFF"  
  23.         android:text="檢查更新"  
  24.         android:background="@drawable/buttonbg"  
  25.         />  
  26.     <ProgressBar   
  27.         android:id="@+id/progressBar_id"  
  28.         style="@android:style/Widget.ProgressBar.Horizontal"    
  29.         android:layout_width="match_parent"  
  30.         android:layout_height="40dp"  
  31.         android:layout_below="@id/button_id"  
  32.         android:layout_marginTop="10dp"  
  33.         android:visibility="gone"/>  
  34. </RelativeLayout>  
[html]  view plain  copy
 
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     tools:context="com.eric.androidupdatedemo.MainActivity" >  
  10.   
  11.     <TextView  
  12.         android:id="@+id/textview_id"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="@string/hello_world" />  
  16.       
  17.     <Button   
  18.         android:id="@+id/button_id"  
  19.         android:layout_width="fill_parent"  
  20.         android:layout_height="40dp"  
  21.         android:layout_below="@id/textview_id"  
  22.         android:textColor="#FFF"  
  23.         android:text="檢查更新"  
  24.         android:background="@drawable/buttonbg"  
  25.         />  
  26.     <ProgressBar   
  27.         android:id="@+id/progressBar_id"  
  28.         style="@android:style/Widget.ProgressBar.Horizontal"    
  29.         android:layout_width="match_parent"  
  30.         android:layout_height="40dp"  
  31.         android:layout_below="@id/button_id"  
  32.         android:layout_marginTop="10dp"  
  33.         android:visibility="gone"/>  
  34. </RelativeLayout>  

 

 

3、MainActivity.java界面初始化,調用更新類的方法,刷新頁面數據。

 

 

[java]  view plain  copy
 
  1. package com.eric.androidupdatedemo;  
  2.   
  3. import java.io.File;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.AlertDialog;  
  7. import android.app.AlertDialog.Builder;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.net.Uri;  
  11. import android.os.Bundle;  
  12. import android.os.Environment;  
  13. import android.os.Handler;  
  14. import android.os.Message;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.view.Window;  
  18. import android.widget.Button;  
  19. import android.widget.ProgressBar;  
  20. import android.widget.TextView;  
  21.   
  22. public class MainActivity extends Activity {  
  23.     private TextView textView;  
  24.     public static int version,serverVersion;  
  25.     public static String versionName,serverVersionName,downloadResult;  
  26.     private Button btn;  
  27.     private ProgressBar proBar;  
  28.     public static receiveVersionHandler handler;  
  29.     private UpdateManager manager = UpdateManager.getInstance();  
  30.       
  31.     @Override  
  32.     protected void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.activity_main);  
  35.           
  36.         textView = (TextView) findViewById(R.id.textview_id);  
  37.         btn = (Button) findViewById(R.id.button_id);  
  38.         proBar=(ProgressBar)findViewById(R.id.progressBar_id);  
  39.           
  40.         Context c = this;  
  41.         version = manager.getVersion(c);  
  42.         versionName = manager.getVersionName(c);  
  43.           
  44.         textView.setText("當前版本號:"+version+"\n"+"當前版本名:"+versionName);  
  45.           
  46.         handler = new receiveVersionHandler();  
  47.           
  48.         //檢查更新按鈕點擊事件   
  49.         btn.setOnClickListener(new OnClickListener() {  
  50.             @Override  
  51.             public void onClick(View v) {  
  52.                 manager.compareVersion(MainActivity.this);  
  53.             }  
  54.         });  
  55.     }  
  56.       
  57.       
  58.     public class receiveVersionHandler extends Handler{  
  59.         @Override  
  60.         public void handleMessage(Message msg) {  
  61.            proBar.setProgress(msg.arg1);  
  62.            proBar.setVisibility(R.id.button_id);  
  63.            textView.setText("下載進度:"+msg.arg1);  
  64.            if(msg.arg1 == 100){  
  65.                Intent intent = new Intent(Intent.ACTION_VIEW);   
  66.                String path = Environment.getExternalStorageDirectory()+"/AndroidUpdateDemo.apk";  
  67.                intent.setDataAndType(Uri.fromFile(new File(path)),   
  68.                        "application/vnd.android.package-archive");     
  69.                startActivity(intent);  
  70.            }  
  71.            proBar.setVisibility(R.id.button_id);  
  72.         }  
  73.   
  74.     }  
  75. }  
[java]  view plain  copy
 
  1. package com.eric.androidupdatedemo;  
  2.   
  3. import java.io.File;  
  4.   
  5. import android.app.Activity;  
  6. import android.app.AlertDialog;  
  7. import android.app.AlertDialog.Builder;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.net.Uri;  
  11. import android.os.Bundle;  
  12. import android.os.Environment;  
  13. import android.os.Handler;  
  14. import android.os.Message;  
  15. import android.view.View;  
  16. import android.view.View.OnClickListener;  
  17. import android.view.Window;  
  18. import android.widget.Button;  
  19. import android.widget.ProgressBar;  
  20. import android.widget.TextView;  
  21.   
  22. public class MainActivity extends Activity {  
  23.     private TextView textView;  
  24.     public static int version,serverVersion;  
  25.     public static String versionName,serverVersionName,downloadResult;  
  26.     private Button btn;  
  27.     private ProgressBar proBar;  
  28.     public static receiveVersionHandler handler;  
  29.     private UpdateManager manager = UpdateManager.getInstance();  
  30.       
  31.     @Override  
  32.     protected void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.activity_main);  
  35.           
  36.         textView = (TextView) findViewById(R.id.textview_id);  
  37.         btn = (Button) findViewById(R.id.button_id);  
  38.         proBar=(ProgressBar)findViewById(R.id.progressBar_id);  
  39.           
  40.         Context c = this;  
  41.         version = manager.getVersion(c);  
  42.         versionName = manager.getVersionName(c);  
  43.           
  44.         textView.setText("當前版本號:"+version+"\n"+"當前版本名:"+versionName);  
  45.           
  46.         handler = new receiveVersionHandler();  
  47.           
  48.         //檢查更新按鈕點擊事件  
  49.         btn.setOnClickListener(new OnClickListener() {  
  50.             @Override  
  51.             public void onClick(View v) {  
  52.                 manager.compareVersion(MainActivity.this);  
  53.             }  
  54.         });  
  55.     }  
  56.       
  57.       
  58.     public class receiveVersionHandler extends Handler{  
  59.         @Override  
  60.         public void handleMessage(Message msg) {  
  61.            proBar.setProgress(msg.arg1);  
  62.            proBar.setVisibility(R.id.button_id);  
  63.            textView.setText("下載進度:"+msg.arg1);  
  64.            if(msg.arg1 == 100){  
  65.                Intent intent = new Intent(Intent.ACTION_VIEW);   
  66.                String path = Environment.getExternalStorageDirectory()+"/AndroidUpdateDemo.apk";  
  67.                intent.setDataAndType(Uri.fromFile(new File(path)),   
  68.                        "application/vnd.android.package-archive");     
  69.                startActivity(intent);  
  70.            }  
  71.            proBar.setVisibility(R.id.button_id);  
  72.         }  
  73.   
  74.     }  
  75. }  

 

 

4、UpdateManager.java更新工具類,包含獲取本地版本信息,服務器版本信息,下載apk文件等方法。

[java]  view plain  copy
 
  1. package com.eric.androidupdatedemo;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9.   
  10. import org.json.JSONArray;  
  11. import org.json.JSONException;  
  12. import org.json.JSONObject;  
  13.   
  14. import android.R.integer;  
  15. import android.app.AlertDialog;  
  16. import android.app.AlertDialog.Builder;  
  17. import android.content.Context;  
  18. import android.content.DialogInterface;  
  19. import android.os.Bundle;  
  20. import android.os.Environment;  
  21. import android.os.Handler;  
  22. import android.os.Looper;  
  23. import android.os.Message;  
  24.   
  25. /* 
  26.  *@author Eric  
  27.  *@2015-11-7上午8:03:31 
  28.  */  
  29. public class UpdateManager {  
  30.     private static UpdateManager manager = null;  
  31.     private UpdateManager(){}  
  32.     public static UpdateManager getInstance(){  
  33.         manager = new UpdateManager();  
  34.         return manager;  
  35.     }  
  36.       
  37.     //獲取版本號   
  38.     public int getVersion(Context context){  
  39.         int version = 0;  
  40.         try {    
  41.             version = context.getPackageManager().getPackageInfo(    
  42.                     "com.eric.androidupdatedemo", 0).versionCode;    
  43.         } catch (Exception e) {    
  44.              System.out.println("獲取版本號異常!");  
  45.         }    
  46.         return version;  
  47.     }  
  48.       
  49.     //獲取版本名   
  50.     public String getVersionName(Context context){  
  51.         String versionName = null;  
  52.         try {  
  53.             versionName = context.getPackageManager().getPackageInfo(  
  54.                     "com.eric.androidupdatedemo", 0).versionName;  
  55.         } catch (Exception e) {  
  56.              System.out.println("獲取版本名異常!");  
  57.         }  
  58.         return versionName;  
  59.     }  
  60.       
  61.     //獲取服務器版本號   
  62.     public String getServerVersion(){  
  63.         String serverJson = null;  
  64.         byte[] buffer = new byte[128];  
  65.           
  66.         try {  
  67.             URL serverURL = new URL("http://192.168.226.106/ver.aspx");  
  68.             HttpURLConnection connect = (HttpURLConnection) serverURL.openConnection();  
  69.             BufferedInputStream bis = new BufferedInputStream(connect.getInputStream());  
  70.             int n = 0;  
  71.             while((n = bis.read(buffer))!= -1){  
  72.                 serverJson = new String(buffer);  
  73.             }  
  74.         } catch (Exception e) {  
  75.             System.out.println("獲取服務器版本號異常!"+e);  
  76.         }  
  77.           
  78.         return serverJson;  
  79.     }     
  80.       
  81.     //比較服務器版本與本地版本彈出對話框   
  82.     public boolean compareVersion(Context context){  
  83.           
  84.         final Context contextTemp = context;  
  85.           
  86.         new Thread(){  
  87.             public void run() {  
  88.                 Looper.prepare();  
  89.                 String serverJson = manager.getServerVersion();  
  90.                   
  91.                 //解析Json數據   
  92.                 try {  
  93.                     JSONArray array = new JSONArray(serverJson);  
  94.                     JSONObject object = array.getJSONObject(0);  
  95.                     String getServerVersion = object.getString("version");  
  96.                     String getServerVersionName = object.getString("versionName");  
  97.                       
  98.                     MainActivity.serverVersion = Integer.parseInt(getServerVersion);  
  99.                     MainActivity.serverVersionName = getServerVersionName;  
  100.                       
  101.                     if(MainActivity.version < MainActivity.serverVersion){  
  102.                         //彈出一個對話框   
  103.                         AlertDialog.Builder builder  = new Builder(contextTemp);    
  104.                         builder.setTitle("版本更新" ) ;    
  105.                         builder.setMessage("當前版本:"+MainActivity.versionName  
  106.                                 +"\n"+"服務器版本:"+MainActivity.serverVersionName ) ;    
  107.                         builder.setPositiveButton("立即更新",new DialogInterface.OnClickListener() {    
  108.                                @Override    
  109.                                public void onClick(DialogInterface dialog, int arg1) {   
  110.                                    //開啟線程下載apk   
  111.                                    new Thread(){  
  112.                                        public void run() {  
  113.                                            Looper.prepare();  
  114.                                            downloadApkFile(contextTemp);  
  115.                                            Looper.loop();  
  116.                                        };  
  117.                                    }.start();  
  118.                                }    
  119.                            });    
  120.                         builder.setNegativeButton("下次再說", null);    
  121.                         builder.show();  
  122.                     }else{  
  123.                         AlertDialog.Builder builder  = new Builder(contextTemp);    
  124.                         builder.setTitle("版本信息" ) ;    
  125.                         builder.setMessage("當前已經是最新版本" ) ;    
  126.                         builder.setPositiveButton("確定",null);    
  127.                         builder.show();  
  128.                     }  
  129.                 } catch (JSONException e) {  
  130.                     e.printStackTrace();  
  131.                     System.out.println("獲取服務器版本線程異常!"+e);  
  132.                 }  
  133.                   
  134.                 Looper.loop();  
  135.             };  
  136.               
  137.         }.start();  
  138.           
  139.           
  140.           
  141.           
  142.           
  143.         return false;  
  144.     }  
  145.       
  146.       
  147.     //下載apk文件   
  148.     public void downloadApkFile(Context context){  
  149.         String savePath = Environment.getExternalStorageDirectory()+"/AndroidUpdateDemo.apk";  
  150.         String serverFilePath = "http://192.168.226.106/AndroidUpdateDemo.png";  
  151.         try {  
  152.             if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){    
  153.                 URL serverURL = new URL(serverFilePath);  
  154.                 HttpURLConnection connect = (HttpURLConnection) serverURL.openConnection();  
  155.                 BufferedInputStream bis = new BufferedInputStream(connect.getInputStream());  
  156.                 File apkfile = new File(savePath);  
  157.                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(apkfile));  
  158.                   
  159.                 int fileLength = connect.getContentLength();  
  160.                 int downLength = 0;  
  161.                 int progress = 0;  
  162.                 int n;  
  163.                 byte[] buffer = new byte[1024];  
  164.                 while((n=bis.read(buffer, 0, buffer.length))!=-1){  
  165.                     bos.write(buffer, 0, n);  
  166.                     downLength +=n;  
  167.                     progress = (int) (((float) downLength / fileLength) * 100);  
  168.                     Message msg = new Message();  
  169.                     msg.arg1 = progress;  
  170.                     MainActivity.handler.sendMessage(msg);  
  171.                     //System.out.println("發送"+progress);   
  172.                 }  
  173.                 bis.close();  
  174.                 bos.close();  
  175.                 connect.disconnect();  
  176.             }   
  177.               
  178.         } catch (Exception e) {  
  179.             System.out.println("下載出錯!"+e);  
  180.         }  
  181.           
  182.   
  183.         /*AlertDialog.Builder builder  = new Builder(context);   
  184.         builder.setTitle("下載apk" ) ;   
  185.         builder.setMessage("正在下載" ) ;   
  186.         builder.setPositiveButton("確定",null);   
  187.         builder.show();*/  
  188.           
  189.           
  190.           
  191.     }  
  192. }  
[java]  view plain  copy
 
  1. package com.eric.androidupdatedemo;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9.   
  10. import org.json.JSONArray;  
  11. import org.json.JSONException;  
  12. import org.json.JSONObject;  
  13.   
  14. import android.R.integer;  
  15. import android.app.AlertDialog;  
  16. import android.app.AlertDialog.Builder;  
  17. import android.content.Context;  
  18. import android.content.DialogInterface;  
  19. import android.os.Bundle;  
  20. import android.os.Environment;  
  21. import android.os.Handler;  
  22. import android.os.Looper;  
  23. import android.os.Message;  
  24.   
  25. /* 
  26.  *@author Eric  
  27.  *@2015-11-7上午8:03:31 
  28.  */  
  29. public class UpdateManager {  
  30.     private static UpdateManager manager = null;  
  31.     private UpdateManager(){}  
  32.     public static UpdateManager getInstance(){  
  33.         manager = new UpdateManager();  
  34.         return manager;  
  35.     }  
  36.       
  37.     //獲取版本號  
  38.     public int getVersion(Context context){  
  39.         int version = 0;  
  40.         try {    
  41.             version = context.getPackageManager().getPackageInfo(    
  42.                     "com.eric.androidupdatedemo", 0).versionCode;    
  43.         } catch (Exception e) {    
  44.              System.out.println("獲取版本號異常!");  
  45.         }    
  46.         return version;  
  47.     }  
  48.       
  49.     //獲取版本名  
  50.     public String getVersionName(Context context){  
  51.         String versionName = null;  
  52.         try {  
  53.             versionName = context.getPackageManager().getPackageInfo(  
  54.                     "com.eric.androidupdatedemo", 0).versionName;  
  55.         } catch (Exception e) {  
  56.              System.out.println("獲取版本名異常!");  
  57.         }  
  58.         return versionName;  
  59.     }  
  60.       
  61.     //獲取服務器版本號  
  62.     public String getServerVersion(){  
  63.         String serverJson = null;  
  64.         byte[] buffer = new byte[128];  
  65.           
  66.         try {  
  67.             URL serverURL = new URL("http://192.168.226.106/ver.aspx");  
  68.             HttpURLConnection connect = (HttpURLConnection) serverURL.openConnection();  
  69.             BufferedInputStream bis = new BufferedInputStream(connect.getInputStream());  
  70.             int n = 0;  
  71.             while((n = bis.read(buffer))!= -1){  
  72.                 serverJson = new String(buffer);  
  73.             }  
  74.         } catch (Exception e) {  
  75.             System.out.println("獲取服務器版本號異常!"+e);  
  76.         }  
  77.           
  78.         return serverJson;  
  79.     }     
  80.       
  81.     //比較服務器版本與本地版本彈出對話框  
  82.     public boolean compareVersion(Context context){  
  83.           
  84.         final Context contextTemp = context;  
  85.           
  86.         new Thread(){  
  87.             public void run() {  
  88.                 Looper.prepare();  
  89.                 String serverJson = manager.getServerVersion();  
  90.                   
  91.                 //解析Json數據  
  92.                 try {  
  93.                     JSONArray array = new JSONArray(serverJson);  
  94.                     JSONObject object = array.getJSONObject(0);  
  95.                     String getServerVersion = object.getString("version");  
  96.                     String getServerVersionName = object.getString("versionName");  
  97.                       
  98.                     MainActivity.serverVersion = Integer.parseInt(getServerVersion);  
  99.                     MainActivity.serverVersionName = getServerVersionName;  
  100.                       
  101.                     if(MainActivity.version < MainActivity.serverVersion){  
  102.                         //彈出一個對話框  
  103.                         AlertDialog.Builder builder  = new Builder(contextTemp);    
  104.                         builder.setTitle("版本更新" ) ;    
  105.                         builder.setMessage("當前版本:"+MainActivity.versionName  
  106.                                 +"\n"+"服務器版本:"+MainActivity.serverVersionName ) ;    
  107.                         builder.setPositiveButton("立即更新",new DialogInterface.OnClickListener() {    
  108.                                @Override    
  109.                                public void onClick(DialogInterface dialog, int arg1) {   
  110.                                    //開啟線程下載apk  
  111.                                    new Thread(){  
  112.                                        public void run() {  
  113.                                            Looper.prepare();  
  114.                                            downloadApkFile(contextTemp);  
  115.                                            Looper.loop();  
  116.                                        };  
  117.                                    }.start();  
  118.                                }    
  119.                            });    
  120.                         builder.setNegativeButton("下次再說", null);    
  121.                         builder.show();  
  122.                     }else{  
  123.                         AlertDialog.Builder builder  = new Builder(contextTemp);    
  124.                         builder.setTitle("版本信息" ) ;    
  125.                         builder.setMessage("當前已經是最新版本" ) ;    
  126.                         builder.setPositiveButton("確定",null);    
  127.                         builder.show();  
  128.                     }  
  129.                 } catch (JSONException e) {  
  130.                     e.printStackTrace();  
  131.                     System.out.println("獲取服務器版本線程異常!"+e);  
  132.                 }  
  133.                   
  134.                 Looper.loop();  
  135.             };  
  136.               
  137.         }.start();  
  138.           
  139.           
  140.           
  141.           
  142.           
  143.         return false;  
  144.     }  
  145.       
  146.       
  147.     //下載apk文件  
  148.     public void downloadApkFile(Context context){  
  149.         String savePath = Environment.getExternalStorageDirectory()+"/AndroidUpdateDemo.apk";  
  150.         String serverFilePath = "http://192.168.226.106/AndroidUpdateDemo.png";  
  151.         try {  
  152.             if(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){    
  153.                 URL serverURL = new URL(serverFilePath);  
  154.                 HttpURLConnection connect = (HttpURLConnection) serverURL.openConnection();  
  155.                 BufferedInputStream bis = new BufferedInputStream(connect.getInputStream());  
  156.                 File apkfile = new File(savePath);  
  157.                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(apkfile));  
  158.                   
  159.                 int fileLength = connect.getContentLength();  
  160.                 int downLength = 0;  
  161.                 int progress = 0;  
  162.                 int n;  
  163.                 byte[] buffer = new byte[1024];  
  164.                 while((n=bis.read(buffer, 0, buffer.length))!=-1){  
  165.                     bos.write(buffer, 0, n);  
  166.                     downLength +=n;  
  167.                     progress = (int) (((float) downLength / fileLength) * 100);  
  168.                     Message msg = new Message();  
  169.                     msg.arg1 = progress;  
  170.                     MainActivity.handler.sendMessage(msg);  
  171.                     //System.out.println("發送"+progress);  
  172.                 }  
  173.                 bis.close();  
  174.                 bos.close();  
  175.                 connect.disconnect();  
  176.             }   
  177.               
  178.         } catch (Exception e) {  
  179.             System.out.println("下載出錯!"+e);  
  180.         }  
  181.           
  182.   
  183.         /*AlertDialog.Builder builder  = new Builder(context);   
  184.         builder.setTitle("下載apk" ) ;   
  185.         builder.setMessage("正在下載" ) ;   
  186.         builder.setPositiveButton("確定",null);   
  187.         builder.show();*/  
  188.           
  189.           
  190.           
  191.     }  
  192. }  

具體實現都在UpdateManager類中,詳細說明一下,其中,

getVersion(Context context)、getVersionName(Context context)本地版本的獲取很簡單一看就懂;

getServerVersion()服務器版本的獲取:讀取服務器目錄下的ver.aspx文件,返回json字符串;

compareVersion(Context context)比較版本:啟動線程,讀取json字符串,並解析服務器版本賦值到serverVersion中,並且比較本地版本和服務器版本,如果低於服務器版本,就啟動新線程下載apk文件;

downloadApkFile(Context context)下載apk文件:設置文件保存路徑,服務器訪問路徑,通過HTTP協議下載文件,這里測試的時候,apk文件無法下載,故將服務器的apk修改擴展名為png格式,下載完成后保存為apk文件。




 




 

 

搭建本地Web服務器:

1、開啟功能:控制面板-> 程序-> 程序和功能 -> 打開或關閉Windows功能,將“Internet信息服務”下的所有功能都打開。

2、設置防火牆:控制面板-> 系統安全 -> Windows防火牆 -> 允許程序通過Windows防火牆,勾選“萬維網服務(HTTP)”。

3、以上步驟完成后,web服務器就搭好了,可以win+R,運行cmd,鍵入ipconfig /all ,查看本機IP地址,打開瀏覽器輸入地址ip地址測試一下,如果打開的是IIS7網頁,說明成功了。

然后就是將新版本的apk放到服務器目錄下,一般是系統盤目錄下C:\inetpub\wwwroot文件夾中。

放置兩個文件,一個是2.0版本的apk文件,一個是ver.aspx文件用於獲取服務器版本的json字符串,里面的內容為:[{"appname":"AndroidUpdateDemo","apkname":"AndroidUpdateDemo.apk","versionName":"02.00.01","version":"2"}] 。

由於測試時候apk文件無法直接下載,想了個辦法將apk文件擴展名改為png,在Android端下載完成后把它在保存為apk文件。

 

上述操作結束后,服務器端就完全搭好了,可以開始測試升級流程。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM