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

Android 版本檢測與自動更新的完整實現方案

編輯:關於 Android 程式設計

做了一個網站的 Android 客戶端,用戶裝到手機上,一旦你推出了新版本該怎麼辦?答案就是加入版本更新功能。本文分享一套完整的版本檢測與更新方案,涵蓋檢測、下載、安裝替換三個關鍵環節。

設計思路

版本檢測最好能自動進行,但若每次開啟都檢測一輪又是種浪費,畢竟版本更新是小概率事件。作者採取的做法是把檢測功能放到選單上,讓用戶有需要時手動觸發。整體可分為三個關鍵步驟:檢測有無新版本、下載新版本、安裝替換新版本。

版本資訊的存放

在 assets 文件夾新增一個純文字檔 ver.cfg,內容只有一句 Version=1.0,它會隨安裝包裝進用戶手機;而在網站端設置一個 XML 檔 ver_apk.xml,內容也只有最新版本號。檢測時先訪問網站的 XML 取得最新版本,再與手機上的 ver.cfg 比對,不同就提示更新。

 

參考程式碼 如下:

Version=1.0

<?xml version="1.0" encoding="utf-8" ?>
<string>1.0</string>

菜單觸發與封裝

檢測功能做在選單上,點擊「檢測更新」時建立一個 UpdateVer 物件並呼叫 checkVer()。由於檢測邏輯較多,作者把它封裝成一個獨立的類。

參考程式碼 如下:

//==========================================================================
// 菜單
//==========================================================================
private static final String urlApk = "https://3g.***.com/tool/***.apk";
private static final String urlVer = "https://3g.***.com/tool/ver_apk.xml";
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, Menu.FIRST + 1, 5, "檢測更新").setIcon(
android.R.drawable.ic_menu_upload);
menu.add(Menu.NONE,Menu.FIRST+2,4,"退出").setIcon(android.R.drawable.ic_lock_power_off);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case Menu.FIRST + 1:
Toast.makeText(this, "正在檢測版本", Toast.LENGTH_LONG).show();
UpdateVer uv = new UpdateVer(urlApk,urlVer,MainActivity.this);
uv.checkVer();
break;
case Menu.FIRST + 2:
confirmExit();
break;
}
return false;
}

UpdateVer.java 封裝類

這個類負責解析版本資訊、比對、下載 APK 並觸發安裝,重點在於透過 AsyncTask 異步訪問網路取得最新版本,下載完成後用隱含 MIME 類型的 Intent 打開安裝。

參考程式碼 如下:

package android.***;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.URLUtil;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import org.xml.sax.InputSource;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UpdateVer extends Activity{
private static final String TAG = "DOWNLOADAPK";
private String PastVersion;
private String NowVersion;
public ProgressDialog pBar;
private String currentFilePath = "";
private String fileEx="";
private String fileNa="";
private String strURL="";
private String VersionUri ="";
private Context mContext;
private final String fileVer = "ver.cfg";
public UpdateVer(String urlapk,String urlver,final Context context){
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String ver = "?ver=" + df.format(new Date());//主要是避開手機的緩存
strURL = urlapk + ver;
VersionUri = urlver + ver;
mContext = context;
}
public void checkVer() {
// 解析 Version 網頁,獲取版本號
getVersionxml(VersionUri);
}
private void compareVer() {
load();
//當有最新版本的時候
if(PastVersion != null && !PastVersion.equals(NowVersion)){
Dialog dialog = new AlertDialog.Builder(mContext).setTitle("系統更新")
.setMessage(String.format("發現新版本%s,目前版本為%s,請更新!",NowVersion,PastVersion))// 設置內容
.setPositiveButton("確定"
,new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
pBar = new ProgressDialog(mContext);
pBar.setTitle("正在下載");
pBar.setMessage("請稍候...");
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
fileEx = strURL.substring(strURL.lastIndexOf(".") + 1,strURL.length()).toLowerCase();
fileEx = fileEx.substring(0,fileEx.lastIndexOf("?"));
fileNa = strURL.substring(strURL.lastIndexOf("/") + 1,strURL.lastIndexOf("."));
getFile(strURL);
}
}).setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int whichButton) {
// 點擊"取消"按鈕之後退出程序
}
}).create();// 創建
// 顯示對話框
dialog.show();
}
else{
Toast.makeText(mContext, String.format("當前為最新版本%s",PastVersion), Toast.LENGTH_LONG).show();
}
}
private void getFile(final String strPath)
{
pBar.show();
try{
if (strPath.equals(currentFilePath) ){
getDataSource(strPath);
}
currentFilePath = strPath;
Runnable r = new Runnable(){
@Override
public void run()
{
try{
getDataSource(strPath);
}
catch (Exception e){
Log.e(TAG, e.getMessage(), e);
}
}
};
new Thread(r).start();
}
catch(Exception e){
e.printStackTrace();
}
}
/*取得遠程文件*/
private void getDataSource(String strPath) throws Exception {
if (!URLUtil.isNetworkUrl(strPath)) {
Log.d("Tag","error");
}
else {
/*取得 URL*/
URL myURL = new URL(strPath);
/*建立聯機*/
URLConnection conn = myURL.openConnection();
conn.connect();
/*InputStream 下載文件*/
InputStream is = conn.getInputStream();
if (is == null) {
Log.d("tag","error");
throw new RuntimeException("沒有讀取到文件內容");
}
/*建立臨時文件*/
File myTempFile = File.createTempFile(fileNa, "." + fileEx);
myTempFile.getAbsolutePath();
/*將文件寫入臨時盤*/
FileOutputStream fos = new FileOutputStream(myTempFile);
byte buf[] = new byte[128];
do{
int numread = is.read(buf);
if (numread <= 0) {
break;
}
fos.write(buf, 0, numread);
}while (true);
/*打開文件進行安裝*/
openFile(myTempFile);
try {
is.close();
}
catch (Exception ex){
Log.d("Tag","error");
Log.e(TAG, "error: " + ex.getMessage(), ex);
}
}
}
/* 在手機上打開文件 */
private void openFile(File f) {
pBar.cancel();
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(android.content.Intent.ACTION_VIEW);
/* 調用 getMIMEType() 來取得 MimeType */
String type = getMIMEType(f);
/* 設定 intent 的 file 與 MimeType */
intent.setDataAndType(Uri.fromFile(f),type);
mContext.startActivity(intent);
}
/* 判斷文件 MimeType 的 method */
private String getMIMEType(File f) {
String type = "";
String fName = f.getName();
/* 取得擴展名 */
String end = fName.substring(fName.lastIndexOf(".")+1,fName.length()).toLowerCase();
/* 按擴展名的類型決定 MimeType */
if(end.equals("m4a")
|| end.equals("mp3")
|| end.equals("mid")
|| end.equals("xmf")
|| end.equals("ogg")
|| end.equals("wav")){
type = "audio";
}
else if(end.equals("3gp") || end.equals("mp4")){
type = "video";
}
else if(end.equals("jpg")
|| end.equals("gif")
|| end.equals("png")
|| end.equals("jpeg")
|| end.equals("bmp")){
type = "image";
}
else if(end.equals("apk")){
/* android.permission.INSTALL_PACKAGES */
type = "application/vnd.android.package-archive";
}
else{
type = "*";
}
/*如果無法直接打開,就跳出軟件清單給使用者選擇 */
if(!end.equals("apk")){
type += "/*";
}
return type;
}
private void getVersionxml(String resourceUrl){
GetVer gv = new GetVer();
gv.execute(resourceUrl);
}
private boolean load(){
Properties properties = new Properties();
try{
InputStream stream = mContext.getAssets().open(fileVer);
//讀取文件內容
properties.load(stream);
}
catch (FileNotFoundException e){
return false;
}
catch(IOException e){
return false;
}
catch(Exception e){
return false;
}
PastVersion = String.valueOf(properties.get("Version").toString());
return true;
}
//==========================================================================
// GetVer
//==========================================================================
class GetVer extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... urlVer) {
String db = null;
URL url = null;
try {
url = new URL(urlVer[0]);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
InputSource is = null;
try {
is = new InputSource(url.openStream());
is.setEncoding("UTF-8");
db = SAXGetVersionService.readRssXml(is);
}
catch (Exception e) {
e.printStackTrace();
}
return db;
}
@Override
protected void onCancelled() {
super.onCancelled();
}
@Override
protected void onPostExecute(String result) {
NowVersion = result;
compareVer();
}
}
}

權限與重點提醒

要在 AndroidManifest.xml 中加入 INTERNET、INSTALL_PACKAGES、WRITE_EXTERNAL_STORAGE 等權限。特別提醒:安裝替換的關鍵在於簽名——每個版本的簽名必須保持一致,否則新版將無法覆蓋舊版,會出現「安裝未完成」的提示。此外,較新版本的 Android 對直接安裝 APK 有額外的限制,實作時需一併考量。

參考程式碼 如下:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RESTART_PACKAGES" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

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