編輯:關於 Android 程式設計
幾乎每個 Android App 都會有版本更新的功能。本文示範一套完整的更新流程,主要用到 AsyncTask 非同步載入、HTTP 協議、JSON 解析與版本號取得等技術。整體步驟是:點擊檢查 → 向伺服器查詢最新版本 → 比對版本號 → 若有新版則下載並安裝,否則提示已是最新。
介面只需一個用來觸發檢查的按鈕:
點擊按鈕後啟動 AsyncTask,在背景執行緒向伺服器查詢最新版本號;若新版本號大於當前版本,則執行下載,否則提示已是最新:
public class MainActivity extends Activity {
Button m_btnCheckNewestVersion;
long m_newVerCode; // 最新版的版本號
String m_newVerName; // 最新版的版本名
String m_appNameStr; // 下載到本地的檔名
Handler m_mainHandler;
ProgressDialog m_progressDlg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initVariable();
m_btnCheckNewestVersion.setOnClickListener(btnClickListener);
}
private void initVariable() {
m_btnCheckNewestVersion = (Button) findViewById(R.id.chek_newest_version);
m_mainHandler = new Handler();
m_progressDlg = new ProgressDialog(this);
m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
m_progressDlg.setIndeterminate(false);
m_appNameStr = "haha.apk";
}
OnClickListener btnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
new checkNewestVersionAsyncTask().execute();
}
};
class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
if (postCheckNewestVersionCommand2Server()) {
int vercode = Common.getVerCode(getApplicationContext());
return m_newVerCode > vercode;
}
return false;
}
@Override
protected void onPostExecute(Boolean result) {
if (result) {
doNewVersionUpdate();
} else {
notNewVersionDlgShow();
}
super.onPostExecute(result);
}
}
/** 從伺服器取得最新版本號,成功回傳 true */
private Boolean postCheckNewestVersionCommand2Server() {
StringBuilder builder = new StringBuilder();
try {
List<NameValuePair> vps = new ArrayList<NameValuePair>();
vps.add(new BasicNameValuePair("action", "checkNewestVersion"));
builder = Common.post_to_server(vps);
JSONArray jsonArray = new JSONArray(builder.toString());
if (jsonArray.length() > 0) {
if (jsonArray.getJSONObject(0).getInt("id") == 1) {
m_newVerName = jsonArray.getJSONObject(0).getString("verName");
m_newVerCode = jsonArray.getJSONObject(0).getLong("verCode");
return true;
}
}
return false;
} catch (Exception e) {
m_newVerName = "";
m_newVerCode = -1;
return false;
}
}
/** 提示更新新版本 */
private void doNewVersionUpdate() {
int verCode = Common.getVerCode(getApplicationContext());
String verName = Common.getVerName(getApplicationContext());
String str = "當前版本:" + verName + " Code:" + verCode + " ,發現新版本:" + m_newVerName + " Code:" + m_newVerCode + " ,是否更新?";
Dialog dialog = new AlertDialog.Builder(this).setTitle("軟件更新").setMessage(str)
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
m_progressDlg.setTitle("正在下載");
m_progressDlg.setMessage("請稍候...");
downFile(Common.UPDATESOFTADDRESS);
}
})
.setNegativeButton("暫不更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
}).create();
dialog.show();
}
/** 提示當前為最新版本 */
private void notNewVersionDlgShow() {
int verCode = Common.getVerCode(this);
String verName = Common.getVerName(this);
String str = "當前版本:" + verName + " Code:" + verCode + ",已是最新版,無需更新!";
Dialog dialog = new AlertDialog.Builder(this).setTitle("軟件更新").setMessage(str)
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { finish(); }
}).create();
dialog.show();
}
private void downFile(final String url) {
m_progressDlg.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
m_progressDlg.setMax((int) length);
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(Environment.getExternalStorageDirectory(), m_appNameStr);
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
int count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
if (length > 0) m_progressDlg.setProgress(count);
}
}
if (fileOutputStream != null) fileOutputStream.close();
down();
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
/** 下載完成,通知更新 UI 並安裝 */
private void down() {
m_mainHandler.post(new Runnable() {
public void run() {
m_progressDlg.cancel();
update();
}
});
}
/** 安裝程式 */
void update() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory(), m_appNameStr)),
"application/vnd.android.package-archive");
startActivity(intent);
}
}
類似一個工具類,封裝了向伺服器 POST 請求、取得版本號與版本名等方法。下載完成後即呼叫安裝:
public class Common {
public static final String SERVER_IP = "https://192.168.1.105/";
public static final String SERVER_ADDRESS = SERVER_IP + "try_downloadFile_progress_server/index.php";
public static final String UPDATESOFTADDRESS = SERVER_IP + "try_downloadFile_progress_server/update_pakage/baidu.apk";
/** 向伺服器發送查詢請求,回傳 StringBuilder */
public static StringBuilder post_to_server(List<NameValuePair> vps) {
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httpost = new HttpPost(SERVER_ADDRESS);
StringBuilder builder = new StringBuilder();
httpost.setEntity(new UrlEncodedFormEntity(vps, HTTP.UTF_8));
HttpResponse response = httpclient.execute(httpost);
if (response.getEntity() != null) {
BufferedReader reader = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String s = reader.readLine();
for (; s != null; s = reader.readLine()) {
builder.append(s);
}
}
return builder;
} catch (Exception e) {
return null;
} finally {
try { httpclient.getConnectionManager().shutdown(); } catch (Exception e) { }
}
}
/** 取得軟件版本號 */
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo(
"com.example.try_downloadfile_progress", 0).versionCode;
} catch (NameNotFoundException e) { }
return verCode;
}
/** 取得版本名稱 */
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo(
"com.example.try_downloadfile_progress", 0).versionName;
} catch (NameNotFoundException e) { }
return verName;
}
}
Android 實戰:以 Bmob 後端雲打造免安裝的 H5 應用收藏集(五)
2016 年 Google I/O 大會提出了 Instant Apps 的概念——使用者無須下載安裝,點擊即可運行應用。如果你聯想到 H5 App、Web App,那方
華為榮耀V8手機怎麼支付?榮耀V8怎麼刷手機消費
華為榮耀V8支付與刷卡消費 榮耀V8支援NFC與指紋支付,可通過Huawei Pay在支援銀聯閃付的POS機上使用。 使用時,可在支付頁面選擇公交卡或銀行卡,靠近感應區
安卓自定義 View 入門(一):用組合 View 寫一個 TopBar
先搞清楚自定義 View 有哪幾條路 自定義 View 大致可以分成三類: 1. 組合 View——把若干現成控件拼成一個新控件。 2. 繼承重寫 View——繼承現有
深入解析 Android Service 的概念、生命週期與通訊
Service 是 Android 四大元件之一,是一種在後台執行、不與使用者直接互動的服務。它沒有介面,卻能在應用退出後依然存活,因而廣泛應用於音樂播放、資料定時更新等