編輯:關於 Android 程式設計
「App 內提示新版本 → 背景下載 → 通知列顯示進度 → 點擊安裝」是相當常見的升級流程。以下示範以「上海地鐵 Subway」為例,把整個模組拆成可讀的幾個部分。
Android 提供兩個版本屬性:
<manifest package="com.cnblogs.tianxia.subway"
android:versionCode="1" <!-- Integer 類型,不顯示給用戶 -->
android:versionName="1.0" <!-- String 類型,顯示給用戶 -->
>
</manifest>
官方建議用 versionCode 遞增來表示版本升級,不論改動大小;versionName 則單純作為給使用者看的版本字串。因此判斷要不要更新,比的是 versionCode。
public class Global {
// 版本資訊
public static int localVersion = 0;
public static int serverVersion = 0;
public static String downloadDir = "app/download/";
}
初始化時,本地版本從 PackageManager 讀取,伺服器版本在實務上應來自 API(這裡先寫死模擬):
/**
* 初始化全域變數。
* 實際工作中 serverVersion 應從伺服器端取得,
* 最好在啟動畫面的 Activity 中執行。
*/
public void initGlobal() {
try {
Global.localVersion = getPackageManager()
.getPackageInfo(getPackageName(), 0).versionCode;
Global.serverVersion = 2; // 假定伺服器版本為 2
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 檢查更新版本
*/
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) {
// 開啟更新服務;把 Service 需要的參數一併帶過去
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 {
// 已是最新版本,清理舊的下載檔(見文末)
}
}
串起來就是兩步:Application 的 onCreate() 呼叫 initGlobal(),Activity 的 onCreate() 呼叫 checkVersion()。
public void onCreate() {
super.onCreate();
initGlobal();
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkVersion();
}
先宣告下載與通知相關的成員:
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);
}
這裡有個重要觀念:Service 本身跑在主執行緒,網路下載絕對不能同步寫在裡面,否則動不動就 ANR。真正的下載工作交給 updateRunnable。
先用一個 Handler 接收執行緒的消息:
private Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 依 msg.what 判斷下載成功或失敗
}
};
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();
}
// 需要權限: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;
}
// 下載狀態 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:
// 點擊即可安裝
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);
// 注意:此處缺少 break,會繼續往下執行
default:
stopService(updateIntent);
}
}
};
File updateFile = new File(Global.downloadDir,
getResources().getString(R.string.app_name) + ".apk");
if (updateFile.exists()) {
// 不需要時清除之前的下載檔,避免浪費用戶空間
updateFile.delete();
}
INTERNET 與 WRITE_EXTERNAL_STORAGE 權限。setLatestEventInfo() 與 Uri.fromFile() 皆為已被淘汰的 API;新專案請改用 Notification.Builder 搭配 NotificationChannel,並以 FileProvider 產生 content:// URI。break,實際上會落到 default 分支,撰寫時請留意。
GestureDetector 手勢滑動使用完全指南
Gesture 在 ViewGroup 中使用 GestureDetector 類可以讓我們快速處理點擊、滑動等手勢事件。使用它大致分三步: 1. 定義 GestureD
Android 如何獲取 media 文件的 meta data:MediaStore、MediaMetadataRetriever 與 ExifInterface
在 app 開發過程中,經常需要顯示 media 文件的元信息——歌曲的專輯與歌手、視頻的分辨率與時長、照片的拍攝設備與時間。Android 提供了幾套不同層次的 API
Android 打造 iOS 風格的分段選擇控件 UISegmentedControl
在 iOS 7 中出現過一種扁平風格的控件——分段選擇控件 UISegmentedControl。它由幾個被細線分隔的按鈕橫放或豎排而成,每次點擊都能切換不同的按鈕與對應
Android ART 執行環境無縫取代 Dalvik 的機制解析
Android 4.4 引入了 ART(Android Runtime),目標是取代長年飽受效能批評的 Dalvik 虛擬機。它的實作原理是另一個話題,本文關心的是一個更