編輯:關於 Android 程式設計
我們大概都遇過這樣的體驗:開啟某個 App 時跳出提示,說有新版本可以下載。這個功能拆開來其實只有三個步驟:
/** 取得目前 App 的版本名稱 */
private String getVersionName() throws Exception {
PackageManager packageManager = getPackageManager();
// getPackageName() 取得目前應用程式的套件名,第二個參數 0 表示要版本資訊
PackageInfo packInfo = packageManager.getPackageInfo(getPackageName(), 0);
return packInfo.versionName;
}
這裡假設伺服器回傳一份 XML,內含版本號、下載網址與更新說明。用 XmlPullParser 解析並封裝成實體物件:
public static UpdataInfo getUpdataInfo(InputStream is) throws Exception {
XmlPullParser parser = Xml.newPullParser();
parser.setInput(is, "utf-8");
int type = parser.getEventType();
UpdataInfo info = new UpdataInfo();
while (type != XmlPullParser.END_DOCUMENT) {
switch (type) {
case XmlPullParser.START_TAG:
if ("version".equals(parser.getName())) {
info.setVersion(parser.nextText());
} else if ("url".equals(parser.getName())) {
info.setUrl(parser.nextText());
} else if ("description".equals(parser.getName())) {
info.setDescription(parser.nextText());
}
break;
}
type = parser.next();
}
return info;
}
對應的實體類別:
public class UpdataInfo {
private String version;
private String url;
private String description;
public String getVersion() { return version; }
public void setVersion(String version) { this.version = version; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
public static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
// 先確認外部儲存空間已掛載且可寫
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return null;
}
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
pd.setMax(conn.getContentLength()); // 進度條上限 = 檔案大小
InputStream is = conn.getInputStream();
File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
FileOutputStream fos = new FileOutputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
byte[] buffer = new byte[1024];
int len, total = 0;
while ((len = bis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
total += len;
pd.setProgress(total);
}
fos.close();
bis.close();
is.close();
return file;
}
把網路請求放到子執行緒,透過 Handler 回主執行緒處理 UI:
public class CheckVersionTask implements Runnable {
public void run() {
try {
String path = getResources().getString(R.string.serverurl);
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
InputStream is = conn.getInputStream();
info = UpdataInfoParser.getUpdataInfo(is);
if (info.getVersion().equals(versionname)) {
Message msg = new Message();
msg.what = UPDATA_CLIENT_NONE;
handler.sendMessage(msg);
} else {
Message msg = new Message();
msg.what = UPDATA_CLIENT;
handler.sendMessage(msg);
}
} catch (Exception e) {
Message msg = new Message();
msg.what = GET_UNDATAINFO_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case UPDATA_CLIENT:
showUpdataDialog();
break;
case GET_UNDATAINFO_ERROR:
Toast.makeText(getApplicationContext(), "獲取伺服器更新資訊失敗", 1).show();
LoginMain();
break;
case DOWN_ERROR:
Toast.makeText(getApplicationContext(), "下載新版本失敗", 1).show();
LoginMain();
break;
}
}
};
protected void showUpdataDialog() {
AlertDialog.Builder builer = new Builder(this);
builer.setTitle("版本升級");
builer.setMessage(info.getDescription());
builer.setPositiveButton("確定", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
downLoadApk();
}
});
builer.setNegativeButton("取消", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
LoginMain();
}
});
builer.create().show();
}
protected void downLoadApk() {
final ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("正在下載更新");
pd.show();
new Thread() {
@Override
public void run() {
try {
File file = DownLoadManager.getFileFromServer(info.getUrl(), pd);
sleep(3000);
installApk(file);
pd.dismiss();
} catch (Exception e) {
Message msg = new Message();
msg.what = DOWN_ERROR;
handler.sendMessage(msg);
e.printStackTrace();
}
}
}.start();
}
protected void installApk(File file) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(intent);
}
private void LoginMain() {
startActivity(new Intent(this, MainActivity.class));
finish();
}
上面這套寫法是早期 Android 的標準做法,邏輯沒問題,但放到今天有幾個地方必須調整:
file:// Uri 直接傳給其他應用會觸發 FileUriExposedException。必須改用 FileProvider.getUriForFile() 產生 content:// Uri,並在 manifest 中宣告 provider 與 FLAG_GRANT_READ_URI_PERMISSION。REQUEST_INSTALL_PACKAGES。Environment.getExternalStorageDirectory() 已不建議,應改用 App 專用目錄 getExternalFilesDir() 或 getFilesDir(),可免去寫入權限申請。equals() 有陷阱,1.10 與 1.9 的字串比較結果會不如預期,應拆成數值逐段比較。HttpURLConnection 搭配自建 Thread 的方式建議替換為 OkHttp 或 Retrofit,並用 ViewModel + Coroutine 取代 Handler。ProgressDialog 是不安全的,UI 更新必須回到主執行緒。如果你只是要快速做出一個可用的升級流程,上面的程式碼足夠理解原理;但要在正式產品中使用,務必把這幾個平台差異補齊。
Fragment 切換後如何保留狀態?hide/show 與 replace 的生命週期差異
第一篇 Fragment 實例裡,我用的是 FragmentTransaction.replace(),這大概也是多數人剛入門時的寫法。但很快會碰到一個惱人的問題。 r
Android Camera API2.0:全新 Camera FW/HAL 架構解析
前言 先前的文章大多在總結 Camera HAL1 到 HAL3 的系統架構,但這些架構對 Camera App 開發而言,仍停留在 Camera API1.0 的標準。
Android 觸摸事件分發機制透視:View 篇
其實我一直想寫一篇關於 Android 事件分發機制的文章。從第一篇博客開始,我就在很多地方零散地用到了事件分發的知識,也有許多朋友問過我各種各樣的問題,比如:onTou
小米手機助手怎麼刷機?用電腦端完成系統升級的步驟
手機賣得好,順手做一個手機助手,說是工具不如說是給使用者的福利。vivo 有 vivo 手機助手,小米則有小助手。它能做的事不少,其中最多人問的就是:能不能用它刷機?答案