編輯:Android 開發實例
本文整理自實務經驗,聚焦 App 自動更新的完整流程,不求完美,但求有用。
Android 為版本提供了兩個屬性:
<manifest package="com.cnblogs.tianxia.subway" android:versionCode="1" <!--Integer 類型,系統不顯示給使用者--> android:versionName="1.0"<!--String 類型,顯示給使用者--> ></manifest>
Google 建議以 versionCode 遞增來表示版本升級(無論改動大小),而 versionName 則作為顯示給使用者看的版本號。因此我們選擇 VersionCode 作為判斷升級的依據。
為了貼近真實專案,這裡以「上海地鐵 Subway」為例,建立結構嚴謹的工程而非單純的 demo。
先在全域檔 Global.java 中定義本地與伺服器版本號:
public class Global {
// 版本資訊
public static int localVersion = 0;
public static int serverVersion = 0;
}
為聚焦主題,直接在 SubwayApplication 中定義 initGlobal():
/**
* 初始化全域變量
* 實務中 serverVersion 應從伺服器端取得,最好在啟動畫面的 activity 中執行
*/
public void initGlobal() {
try {
Global.localVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionCode;
Global.serverVersion = 2; // 假定伺服器版本為 2,本地預設為 1
} catch (Exception ex) {
ex.printStackTrace();
}
}
偵測到新版本時,於 SubwayActivity 的 checkVersion() 提示使用者更新:
/** 檢查更新版本 */
public void checkVersion() {
if (Global.localVersion < Global.serverVersion) {
// 發現新版本,提示使用者更新
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("軟件升級")
.setMessage("發現新版本,建議立即更新使用。")
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// 開啟更新服務 UpdateService
// 這裡可傳入 updateService 依賴的值,如佈局 ID、資源 ID、動態標題(以 app_name 為例)
Intent updateIntent = new Intent(SubwayActivity.this, UpdateService.class);
updateIntent.putExtra("titleId", R.string.app_name);
startService(updateIntent);
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert.create().show();
} else {
// 清理工作,略去 cheanUpdateFile()
}
}
接著把流程串起來:第一步,在 SubwayApplication 的 onCreate() 中呼叫 initGlobal() 初始化版本變量:
public void onCreate() {
super.onCreate();
initGlobal();
}
第二步,在 SubwayActivity 的 onCreate() 中呼叫 checkVersion() 檢測更新:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkVersion();
}
當使用者點擊「更新」,即會啟動 UpdateService 從伺服器下載最新版本。
定義 UpdateService.java,先宣告與下載、通知相關的變量:
private int titleId = 0; // 標題 private File updateDir = null; // 檔案儲存 private File updateFile = null; private NotificationManager updateNotificationManager = null; // 通知欄 private Notification updateNotification = null; private Intent updateIntent = null; // 通知欄跳轉 Intent private PendingIntent updatePendingIntent = null;
在 onStartCommand() 中準備下載工作:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
titleId = intent.getIntExtra("titleId", 0);
// 建立檔案
if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
updateDir = new File(Environment.getExternalStorageDirectory(), Global.downloadDir);
updateFile = new File(updateDir.getPath(), getResources().getString(titleId) + ".apk");
}
this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
this.updateNotification = new Notification();
// 下載過程中點擊通知欄回到主介面
updateIntent = new Intent(this, SubwayActivity.class);
updatePendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
// 設定通知欄內容
updateNotification.icon = R.drawable.arrow_down_float;
updateNotification.tickerText = "開始下載";
updateNotification.setLatestEventInfo(this, "上海地鐵", "0%", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
// 開啟新執行緒下載,避免在 Service 中同步下載導致 ANR
new Thread(new updateRunnable()).start();
return super.onStartCommand(intent, flags, startId);
}
真正的下載邏輯在 updateRunnable 中,出於使用者體驗考量,獨立於背景執行緒。先定義一個空的 Handler:
private Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
}
};
updateRunnable 的實作:
class updateRunnable implements Runnable {
Message message = updateHandler.obtainMessage();
public void run() {
message.what = DOWNLOAD_COMPLETE;
try {
// 需增加權限 WRITE_EXTERNAL_STORAGE
if (!updateDir.exists()) {
updateDir.mkdirs();
}
if (!updateFile.exists()) {
updateFile.createNewFile();
}
// 下載函數,以 QQ 為例,需增加權限 INTERNET
long downloadSize = downloadUpdateFile("https://softfile.3g.qq.com:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk", updateFile);
if (downloadSize > 0) {
updateHandler.sendMessage(message); // 下載成功
}
} catch (Exception ex) {
ex.printStackTrace();
message.what = DOWNLOAD_FAIL; // 下載失敗
updateHandler.sendMessage(message);
}
}
}
下載函數同時負責通知下載進度:
public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
int downloadCount = 0;
int currentSize = 0;
long totalSize = 0;
int updateTotalSize = 0;
HttpURLConnection httpConnection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
URL url = new URL(downloadUrl);
httpConnection = (HttpURLConnection)url.openConnection();
httpConnection.setRequestProperty("User-Agent", "PacificHttpClient");
if (currentSize > 0) {
httpConnection.setRequestProperty("RANGE", "bytes=" + currentSize + "-");
}
httpConnection.setConnectTimeout(10000);
httpConnection.setReadTimeout(20000);
updateTotalSize = httpConnection.getContentLength();
if (httpConnection.getResponseCode() == 404) {
throw new Exception("fail!");
}
is = httpConnection.getInputStream();
fos = new FileOutputStream(saveFile, false);
byte buffer[] = new byte[4096];
int readsize = 0;
while ((readsize = is.read(buffer)) > 0) {
fos.write(buffer, 0, readsize);
totalSize += readsize;
// 為避免頻繁通知拖慢應用,每增加 10% 才通知一次
if ((downloadCount == 0) || (int)(totalSize * 100 / updateTotalSize) - 10 > downloadCount) {
downloadCount += 10;
updateNotification.setLatestEventInfo(UpdateService.this, "正在下載", (int)totalSize * 100 / updateTotalSize + "%", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
}
}
} finally {
if (httpConnection != null) {
httpConnection.disconnect();
}
if (is != null) {
is.close();
}
if (fos != null) {
fos.close();
}
}
return totalSize;
}
下載完成後,補全 Handler 來提示使用者並可點擊安裝。先定義兩個狀態常量:
private final static int DOWNLOAD_COMPLETE = 0; private final static int DOWNLOAD_FAIL = 1;
依狀態處理主執行緒:
private Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DOWNLOAD_COMPLETE:
// 點擊安裝 PendingIntent
Uri uri = Uri.fromFile(updateFile);
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0);
updateNotification.defaults = Notification.DEFAULT_SOUND; // 鈴聲提醒
updateNotification.setLatestEventInfo(UpdateService.this, "上海地鐵", "下載完成,點擊安裝。", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
stopService(updateIntent); // 停止服務
break;
case DOWNLOAD_FAIL:
// 下載失敗
updateNotification.setLatestEventInfo(UpdateService.this, "上海地鐵", "下載失敗,請重試。", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
default:
stopService(updateIntent);
}
}
};
至此,檔案下載並在通知欄顯示進度的完整流程就完成了。以下附上先前提到、用於清理舊檔的 cheanUpdateFile():
File updateFile = new File(Global.downloadDir, getResources().getString(R.string.app_name) + ".apk");
if (updateFile.exists()) {
// 不需要時清除之前下載的檔案,避免浪用具使用者的儲存空間
updateFile.delete();
}
以上就是 App 自動更新的完整實作,希望對你有所幫助。
Android 實作 Market 風格的 Loading 效果:自訂版面取代 ProgressDialog
在 Android 裡做載入提示,直覺做法是 ProgressDialog。ApiDemos 中的 ProgressBar3.java 就示範了兩種典型用法:但仔細看 A
Android 應用本地化:讓 App 跟著系統語言自動切換
Android 應用程式可能在各種地區、各種語言環境的裝置上執行。想讓 App 更有親和力,就必須處理好文字、數字、檔案等內容在該語言環境下的呈現方式。 本章要解釋如何依
Android 載入動畫怎麼做?ProgressBar 轉圈指示器完整說明
使用者按下一顆按鈕後若畫面毫無反應,通常會以為 App 當掉了。這時候一個小小的旋轉動畫,就能把「不確定要等多久」的焦慮大幅降低。Android 的 ProgressBa
Android Spinner 載入提示元件:屬性、方法與使用時機
App 在背後做事的時候,使用者需要知道「它還活著」。Android 用 ProgressBar 負責這件事,而它有兩種典型外觀:可以標示百分比的長條進度條,以及不斷旋轉