Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 軟體自動更新功能的完整實作

編輯:關於 Android 程式設計

幾乎所有 App 都有「發現新版本,請更新」的功能。本文將一步步實作這樣一套自動更新機制:檢測更新、提示使用者、下載 APK、並在完成后自動跳轉安裝。

步驟一:建立 UpdateManger 類

這個類封裝了完整的更新流程,透過 Handler 接收下載進度並更新進度條:

public class UpdateManger {
    private Context mContext;
    private String updateMsg = "有最新的軟體包,請下載!";
    private String apkUrl = "https://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk";
    private Dialog noticeDialog;   // 提示更新的對話框
    private Dialog downloadDialog; // 下載對話框
    private static final String savePath = "/sdcard/updatedemo/";
    private static final String saveFileName = savePath + "UpdateDemoRelease.apk";
    private ProgressBar mProgress;
    private static final int DOWN_UPDATE = 1;
    private static final int DOWN_OVER = 2;
    private int progress;              // 當前進度
    private Thread downLoadThread;     // 下載線程
    private boolean interceptFlag = false; // 使用者取消下載

    // 通知處理刷新界面的 handler
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    installApk();
                    break;
            }
            super.handleMessage(msg);
        }
    };
    public UpdateManger(Context context) {
        this.mContext = context;
    }
    // 顯示更新程式對話框,供主程式呼叫
    public void checkUpdateInfo() {
        showNoticeDialog();
    }
    private void showNoticeDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        builder.setTitle("軟體版本更新");
        builder.setMessage(updateMsg);
        builder.setPositiveButton("下載", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                showDownloadDialog();
            }
        });
        builder.setNegativeButton("以後再說", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        noticeDialog = builder.create();
        noticeDialog.show();
    }

下載與安裝流程

按下「下載」後會彈出含進度條的對話框,並在子線程中執行實際的檔案下載。下載過程中透過 Handler 不斷更新進度,完成後觸發安裝:

    protected void showDownloadDialog() {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.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); // 將對話框內容設為一個 View
        builder.setNegativeButton("取消", new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                interceptFlag = true; // 使用者取消下載
            }
        });
        downloadDialog = builder.create();
        downloadDialog.show();
        downloadApk();
    }
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }
    protected void installApk() {
        File apkfile = new File(saveFileName);
        if (!apkfile.exists()) {
            return;
        }
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }
    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.connect();
                int length = conn.getContentLength();
                InputStream ins = conn.getInputStream();
                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                File ApkFile = new File(saveFileName);
                FileOutputStream outStream = new FileOutputStream(ApkFile);
                int count = 0;
                byte buf[] = new byte[1024];
                do {
                    int numread = ins.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100); // 計算下載進度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        mHandler.sendEmptyMessage(DOWN_OVER); // 下載完成,通知安裝
                        break;
                    }
                    outStream.write(buf, 0, numread);
                } while (!interceptFlag); // 點擊取消則停止下載
                outStream.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}

步驟二:建立進度條佈局 progress.xml

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

步驟三:在 MainActivity 中觸發檢測

在 onCreate() 中建立 UpdateManger 並呼叫檢測方法。此處要特別注意:必須傳入 Activity 本身,而非 getApplicationContext(),因為只有 Activity 才能彈出窗體:

mUpdateManger = new UpdateManger(MainActivity.this);
// 注意此處不能傳入 getApplicationContext(),會報錯,因為只有 Activity 才能添加窗體
mUpdateManger.checkUpdateInfo();

同時別忘了在清單檔中加入網路權限:

<uses-permission android:name="android.permission.INTERNET" />

步驟四:運行成果

—點擊下載—>

整套流程串起了對話框提示、子線程下載、進度更新與自動安裝,是一個非常實用的線上更新範本。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved