Android 軟件自動更新功能的實現

大家好,發現半年沒有更新博客了,最近一直都比較忙,決定在凌晨 英超 阿森納VS富勒姆 中場休息的時候,給大家分享Android裏應用版本更新功能這一塊的實現。

一個好的應用軟件都是需要好的維護,從初出版本到最後精品,這個過程需要版本不停的更新,那麼如何讓用戶第一時間獲取最新的應用安裝包呢?那麼就要求我們從第一個版本就要實現升級模塊這一功能。

自動更新功能的實現原理,就是我們事先和後臺協商好一個接口,我們在應用的主Activity裏,去訪問這個接口,如果需要更新,後臺會返回一些數據(比如,提示語;最新版本的url等)。然後我們給出提示框,用戶點擊開始下載,下載完成開始覆蓋安裝程序,這樣用戶的應用就保持最新的拉。

爲了讓大家容易理解,我像往常一樣準備一個小例子,這裏爲了方便我就省去了和後臺交互部分了。步驟分別如下:

第一步:新建一個Android工程命名爲:UpdateDemo.代碼結構如下圖所示:

第二步:新建一個UpdateManager.java類,負責軟件更新功能模塊,代碼如下:

  1. package com.tutor.update;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.MalformedURLException;  
  9. import java.net.URL;  
  10.   
  11.   
  12. import android.app.AlertDialog;  
  13. import android.app.Dialog;  
  14. import android.app.AlertDialog.Builder;  
  15. import android.content.Context;  
  16. import android.content.DialogInterface;  
  17. import android.content.Intent;  
  18. import android.content.DialogInterface.OnClickListener;  
  19. import android.net.Uri;  
  20. import android.os.Handler;  
  21. import android.os.Message;  
  22. import android.view.LayoutInflater;  
  23. import android.view.View;  
  24. import android.widget.ProgressBar;  
  25.   
  26. public class UpdateManager {  
  27.   
  28.     private Context mContext;  
  29.       
  30.     //提示語  
  31.     private String updateMsg = "有最新的軟件包哦,親快下載吧~";  
  32.       
  33.     //返回的安裝包url  
  34.     private String apkUrl = "http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk";  
  35.       
  36.       
  37.     private Dialog noticeDialog;  
  38.       
  39.     private Dialog downloadDialog;  
  40.      /* 下載包安裝路徑 */  
  41.     private static final String savePath = "/sdcard/updatedemo/";  
  42.       
  43.     private static final String saveFileName = savePath + "UpdateDemoRelease.apk";  
  44.   
  45.     /* 進度條與通知ui刷新的handler和msg常量 */  
  46.     private ProgressBar mProgress;  
  47.   
  48.       
  49.     private static final int DOWN_UPDATE = 1;  
  50.       
  51.     private static final int DOWN_OVER = 2;  
  52.       
  53.     private int progress;  
  54.       
  55.     private Thread downLoadThread;  
  56.       
  57.     private boolean interceptFlag = false;  
  58.       
  59.     private Handler mHandler = new Handler(){  
  60.         public void handleMessage(Message msg) {  
  61.             switch (msg.what) {  
  62.             case DOWN_UPDATE:  
  63.                 mProgress.setProgress(progress);  
  64.                 break;  
  65.             case DOWN_OVER:  
  66.                   
  67.                 installApk();  
  68.                 break;  
  69.             default:  
  70.                 break;  
  71.             }  
  72.         };  
  73.     };  
  74.       
  75.     public UpdateManager(Context context) {  
  76.         this.mContext = context;  
  77.     }  
  78.       
  79.     //外部接口讓主Activity調用  
  80.     public void checkUpdateInfo(){  
  81.         showNoticeDialog();  
  82.     }  
  83.       
  84.       
  85.     private void showNoticeDialog(){  
  86.         AlertDialog.Builder builder = new Builder(mContext);  
  87.         builder.setTitle("軟件版本更新");  
  88.         builder.setMessage(updateMsg);  
  89.         builder.setPositiveButton("下載"new OnClickListener() {           
  90.             @Override  
  91.             public void onClick(DialogInterface dialog, int which) {  
  92.                 dialog.dismiss();  
  93.                 showDownloadDialog();             
  94.             }  
  95.         });  
  96.         builder.setNegativeButton("以後再說"new OnClickListener() {             
  97.             @Override  
  98.             public void onClick(DialogInterface dialog, int which) {  
  99.                 dialog.dismiss();                 
  100.             }  
  101.         });  
  102.         noticeDialog = builder.create();  
  103.         noticeDialog.show();  
  104.     }  
  105.       
  106.     private void showDownloadDialog(){  
  107.         AlertDialog.Builder builder = new Builder(mContext);  
  108.         builder.setTitle("軟件版本更新");  
  109.           
  110.         final LayoutInflater inflater = LayoutInflater.from(mContext);  
  111.         View v = inflater.inflate(R.layout.progress, null);  
  112.         mProgress = (ProgressBar)v.findViewById(R.id.progress);  
  113.           
  114.         builder.setView(v);  
  115.         builder.setNegativeButton("取消"new OnClickListener() {   
  116.             @Override  
  117.             public void onClick(DialogInterface dialog, int which) {  
  118.                 dialog.dismiss();  
  119.                 interceptFlag = true;  
  120.             }  
  121.         });  
  122.         downloadDialog = builder.create();  
  123.         downloadDialog.show();  
  124.           
  125.         downloadApk();  
  126.     }  
  127.       
  128.     private Runnable mdownApkRunnable = new Runnable() {      
  129.         @Override  
  130.         public void run() {  
  131.             try {  
  132.                 URL url = new URL(apkUrl);  
  133.               
  134.                 HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
  135.                 conn.connect();  
  136.                 int length = conn.getContentLength();  
  137.                 InputStream is = conn.getInputStream();  
  138.                   
  139.                 File file = new File(savePath);  
  140.                 if(!file.exists()){  
  141.                     file.mkdir();  
  142.                 }  
  143.                 String apkFile = saveFileName;  
  144.                 File ApkFile = new File(apkFile);  
  145.                 FileOutputStream fos = new FileOutputStream(ApkFile);  
  146.                   
  147.                 int count = 0;  
  148.                 byte buf[] = new byte[1024];  
  149.                   
  150.                 do{                   
  151.                     int numread = is.read(buf);  
  152.                     count += numread;  
  153.                     progress =(int)(((float)count / length) * 100);  
  154.                     //更新進度  
  155.                     mHandler.sendEmptyMessage(DOWN_UPDATE);  
  156.                     if(numread <= 0){      
  157.                         //下載完成通知安裝  
  158.                         mHandler.sendEmptyMessage(DOWN_OVER);  
  159.                         break;  
  160.                     }  
  161.                     fos.write(buf,0,numread);  
  162.                 }while(!interceptFlag);//點擊取消就停止下載.  
  163.                   
  164.                 fos.close();  
  165.                 is.close();  
  166.             } catch (MalformedURLException e) {  
  167.                 e.printStackTrace();  
  168.             } catch(IOException e){  
  169.                 e.printStackTrace();  
  170.             }  
  171.               
  172.         }  
  173.     };  
  174.       
  175.      /** 
  176.      * 下載apk 
  177.      * @param url 
  178.      */  
  179.       
  180.     private void downloadApk(){  
  181.         downLoadThread = new Thread(mdownApkRunnable);  
  182.         downLoadThread.start();  
  183.     }  
  184.      /** 
  185.      * 安裝apk 
  186.      * @param url 
  187.      */  
  188.     private void installApk(){  
  189.         File apkfile = new File(saveFileName);  
  190.         if (!apkfile.exists()) {  
  191.             return;  
  192.         }      
  193.         Intent i = new Intent(Intent.ACTION_VIEW);  
  194.         i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");   
  195.         mContext.startActivity(i);  
  196.       
  197.     }  
  198. }  

第三步:在MainActivity.java也就是主Activity調用,代碼如下:
  1. package com.tutor.update;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5.   
  6. public class MainAcitivity extends Activity {  
  7.       
  8.   
  9.     private UpdateManager mUpdateManager;  
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.main);  
  14.           
  15.         //這裏來檢測版本是否需要更新  
  16.         mUpdateManager = new UpdateManager(this);  
  17.         mUpdateManager.checkUpdateInfo();  
  18.     }       
  19. }  

第四步:添加程序所用的資源與權限:

下載的時候用到了ProgressBar,所以事先寫了一個progress.xml佈局文件,代碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:layout_width="fill_parent"  
  5.   android:layout_height="wrap_content">  
  6.     
  7.   <ProgressBar  
  8.     android:id="@+id/progress"  
  9.     android:layout_width="fill_parent"  
  10.     android:layout_height="wrap_content"  
  11.     style="?android:attr/progressBarStyleHorizontal"  
  12.   />  
  13. </LinearLayout>  
下載的時候用到了網絡部分,所以要在AndroidManifest.xml中添加網絡權限,代碼如下:
  1. <uses-permission android:name="android.permission.INTERNET" />  

第五步:運行查看效果如下:

    

 圖一:提示有最新包                                                                                   圖二:點擊開始下載

圖三:下載完開始安裝,我這裏模擬器空間不足了。

OK~大功告成了,繼續看球,阿森納已經0:1了,希望範大將軍救駕!大家晚安~稍後將會爲大家分享更多內容,盡請期待!

源代碼點擊進入==>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章