自動更新--下載apk以及提示對話方塊的實現(3),自動更新apk

來源:互聯網
上載者:User

自動更新--下載apk以及提示對話方塊的實現(3),自動更新apk

下載apk以及提示對話方塊的實現

一、步驟:

1. 確定有可以更新的版本,對話方塊提醒使用者是否進行更新。

2. 選擇更新的話,顯示下載對話方塊並且進行下載,否則關閉提示更新對話方塊。

3. Apk下載完成後,安裝apk。

二、具體細節:

1. 提示使用者更新的時候,實現必須更新的方法如下:顯示的對話方塊只顯示更新按鈕,也就是只能選擇更新。

2. 下載的時候,下載對話方塊的頁面顯示一個進度條來顯示下載進度。

3. 下載的時候,啟動一個子線程來進行下載。

4. 下載的時候需要來源路徑和下載後儲存的路徑。

5. 下載對話方塊有取消下載按鈕,當點擊取消下載的時候,直接結束下載線程中讀取資料的內容即可。

6. 下載對話方塊的進度條是即時更新的,所以需要主線程和子線程之間進行通訊,通訊使用Handler類來實現。

7. 通訊的時候當發送來下載結束的訊號的時候,進行安裝apk操作。

8. 安裝操作使用intent實現。

三、代碼如下:

1. 主要代碼

import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import net.aufo.apps.certclient.R;import android.app.Activity;import android.app.AlertDialog;import android.app.AlertDialog.Builder;import android.app.Dialog;import android.content.Context;import android.content.DialogInterface;import android.content.DialogInterface.OnClickListener;import android.content.Intent;import android.net.Uri;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.view.LayoutInflater;import android.view.View;import android.widget.ProgressBar;public class UpdateManager{/* 下載中 */private static final int DOWNLOAD = 1;/* 下載結束 */private static final int DOWNLOAD_FINISH = 2;private String downloadUrl;/* 下載儲存路徑 */private String localSavePath;/* 記錄進度條數量 */private int progress;/* 是否取消更新 */private boolean cancelUpdate = false;private Context mContext;/* 更新進度條 */private ProgressBar mProgress;private Dialog mDownloadDialog;private Handler mHandler = new Handler(){public void handleMessage(Message msg){switch (msg.what){// 正在下載case DOWNLOAD:// 設定進度條位置mProgress.setProgress(progress);break;case DOWNLOAD_FINISH:// 安裝檔案installApk();break;default:break;}};};public UpdateManager(Context context){this.mContext = context;}/** * 顯示軟體更新對話方塊 */public void showNoticeDialog(boolean forceUpdate, String updatedDetail, String downloadUrl, String localSavePath){this.downloadUrl = downloadUrl;this.localSavePath = localSavePath;// 構造對話方塊AlertDialog.Builder builder = new Builder(mContext);builder.setTitle("軟體更新");builder.setMessage(updatedDetail);// 更新builder.setPositiveButton("更新", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();// 顯示下載對話方塊showDownloadDialog();}});if(forceUpdate == false){// 稍後更新builder.setNegativeButton("稍後更新", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();/*dialog.dismiss();((Activity)mContext).finish();System.exit(0);*/}});}Dialog noticeDialog = builder.create();noticeDialog.show();}/** * 顯示軟體下載對話方塊 */private void showDownloadDialog(){// 構造軟體下載對話方塊AlertDialog.Builder builder = new Builder(mContext);builder.setTitle("正在下載更新");// 給下載對話方塊增加進度條final LayoutInflater inflater = LayoutInflater.from(mContext);View v = inflater.inflate(R.layout.progress, null);mProgress = (ProgressBar) v.findViewById(R.id.progress);builder.setView(v);// 取消更新builder.setNegativeButton("取消", new OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();// 設定取消狀態cancelUpdate = true;}});mDownloadDialog = builder.create();mDownloadDialog.show();// 啟動新線程下載軟體new downloadApkThread().start();}/** * 下載檔案線程 */private class downloadApkThread extends Thread{@Overridepublic void run(){try{// 判斷SD卡是否存在,並且是否具有讀寫權限if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){URL url = new URL(downloadUrl);// 建立串連HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.connect();// 擷取檔案大小int length = conn.getContentLength();// 建立輸入資料流InputStream is = conn.getInputStream();File file = new File(localSavePath);// 判斷檔案目錄是否存在if (!file.exists()){file.mkdirs();}File apkFile = new File(localSavePath, "update.apk");FileOutputStream fos = new FileOutputStream(apkFile);int count = 0;// 緩衝byte buf[] = new byte[1024];// 寫入到檔案中do{int numread = is.read(buf);count += numread;// 計算進度條位置progress = (int) (((float) count / length) * 100);// 更新進度mHandler.sendEmptyMessage(DOWNLOAD);if (numread <= 0){// 下載完成mHandler.sendEmptyMessage(DOWNLOAD_FINISH);break;}// 寫入檔案fos.write(buf, 0, numread);} while (!cancelUpdate);// 點擊取消就停止下載.fos.close();is.close();}} catch (MalformedURLException e){e.printStackTrace();} catch (IOException e){e.printStackTrace();}// 取消下載對話方塊顯示mDownloadDialog.dismiss();}};/** * 安裝APK檔案 */private void installApk(){File apkfile = new File(localSavePath, "update.apk");if (!apkfile.exists()){return;}// 通過Intent安裝APK檔案Intent i = new Intent(Intent.ACTION_VIEW);i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");mContext.startActivity(i);}}


 

2. 下載對話方塊介面代碼progress.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content" >    <ProgressBar        android:id="@+id/progress"        style="?android:attr/progressBarStyleHorizontal"        android:layout_width="fill_parent"        android:layout_height="wrap_content" /></LinearLayout>


 

3. 調用代碼

UpdateManager update = new UpdateManager(this);update.showNoticeDialog(false, "檢測到新版本,立即更新嗎?", "http://saifusuozheng.dbankcloud.com/AppGenXin/CertClient.apk",getFilesDir().getPath());


 

四、參考網站:

1. 更新步驟

http://www.iteye.com/problems/55470

2. xml解析和產生

 http://developer.51cto.com/art/200903/117512.htm

3. 從網路上擷取檔案http://blog.csdn.net/blueman2012/article/details/6450895

4. Android自動更新程式

4.1 http://www.cnblogs.com/wainiwann/archive/2012/03/12/2391810.html

4.2  http://www.cnblogs.com/coolszy/archive/2012/04/27/2474279.html

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.