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

Android APK 版本更新完整實作

編輯:關於 Android 程式設計

讓 App 具備自動檢查與下載更新的能力,是許多應用的必備功能。本文從取得當前版本號開始,一路實作到異步下載 APK 並觸發安裝。

取得版本名稱

透過 PackageManager 取得當前應用的版本資訊:

/**
 * 獲取版本名稱
 */
private String getVersionName() {
    String version = "";
    try {
        PackageManager packageManager = getPackageManager();
        // getPackageName() 為當前類的套件名,0 表示取得版本資訊
        PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
        version = packInfo.versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    return version;
}

在 Activity 中呼叫

// 檢測版本是否需要更新
UpdateManager mUpdateManager = new UpdateManager(SettingActivity.this);
mUpdateManager.checkUpdateInfo();

UpdateManager 完整實作

public class UpdateManager {

    private Context mContext;
    /* 下載包安裝路徑 */
    private static final String savePath = "//sdcard//updatedemo//";
    private static final String saveFileName = savePath + "licaike.apk";

    private int progress;
    private ProgressDialogUtil pdu;
    private boolean interceptFlag = true;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x123:
                    pdu.setProgress(progress);
                    break;
                case 0x124: // 安裝 apk
                    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);
                    pdu.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    public UpdateManager(Context context) {
        this.mContext = context;
    }

    // 外部接口,讓主 Activity 調用
    public void checkUpdateInfo() {
        final AlertDialogUtil dialogUtil = new AlertDialogUtil(mContext, false, null);
        dialogUtil.setMessage("請更新新版本");
        dialogUtil.setBtnPositiveValue("更新");
        dialogUtil.setPositiveClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                showDownloadDialog();
                dialogUtil.dismiss();
            }
        });
        dialogUtil.setBtnNegativeValue("取消");
        dialogUtil.setNegativeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                dialogUtil.dismiss();
            }
        });
        dialogUtil.show();
    }

    private void showDownloadDialog() {
        downLoadThread();
        pdu = new ProgressDialogUtil(mContext, false, null);
        pdu.setMessage("軟件正在更新中...");
        pdu.setBtnNegativeValue("取消");
        pdu.setNegativeClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                interceptFlag = false;
                pdu.dismiss();
            }
        });
        pdu.show();
    }

    private void downLoadThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                InputStream is = null;
                FileOutputStream fos = null;
                try {
                    String apkUrl = "https://d.m.hexun.com/app/licaike.apk";
                    URL url = new URL(apkUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    int length = conn.getContentLength();
                    is = conn.getInputStream();

                    File file = new File(savePath);
                    if (!file.exists()) file.mkdir();
                    File ApkFile = new File(saveFileName);
                    fos = new FileOutputStream(ApkFile);

                    int count = 0;
                    byte buf[] = new byte[1024];
                    while (interceptFlag) { // 點擊取消即停止下載
                        int numread = is.read(buf);
                        count += numread;
                        progress = (int) (((float) count / length) * 100);
                        mHandler.sendEmptyMessage(0x123); // 更新進度
                        if (numread <= 0) {
                            mHandler.sendEmptyMessage(0x124); // 下載完成,通知安裝
                            break;
                        }
                        fos.write(buf, 0, numread);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (fos != null) fos.close();
                        if (is != null) is.close();
                    } catch (Exception e) { }
                }
            }
        }).start();
    }
}

整體流程為:先彈出更新提示對話框,按下更新後開啟下載進度框並啟動子線程下載,下載過程中透過 Handler 更新進度,完成後發送安裝意圖。實務上要留意:新版 Android 對寫入外部儲存與安裝未知來源應用有更嚴格的限制,需動態申請相應權限,並建議改用 FileProvider 來分享安裝檔。

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