Android編程實(shí)現(xiàn)應(yīng)用自動更新、下載、安裝的方法
本文實(shí)例講述了Android編程實(shí)現(xiàn)應(yīng)用自動更新、下載、安裝的方法。分享給大家供大家參考,具體如下:
我們看到很多Android應(yīng)用都具有自動更新功能,用戶一鍵就可以完成軟件的升級更新。得益于Android系統(tǒng)的軟件包管理和安裝機(jī)制,這一功能實(shí)現(xiàn)起來相當(dāng)簡單,下面我們就來實(shí)踐一下。
1. 準(zhǔn)備知識
在AndroidManifest.xml里定義了每個Android apk的版本標(biāo)識:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.myapp" android:versionCode="1" android:versionName="1.0.0"> <application></application> </manifest>
其中,android:versionCode和android:versionName兩個字段分別表示版本代碼,版本名稱。versionCode是 整型數(shù)字,versionName是字符串。由于version是給用戶看的,不太容易比較大小,升級檢查時,可以以檢查versionCode為主,方 便比較出版本的前后大小。
那么,在應(yīng)用中如何讀取AndroidManifest.xml中的versionCode和versionName呢?可以使用PackageManager的API,參考以下代碼:
public static int getVerCode(Context context) {
int verCode = -1;
try {
verCode = context.getPackageManager().getPackageInfo(
"com.myapp", 0).versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
return verCode;
}
public static String getVerName(Context context) {
String verName = "";
try {
verName = context.getPackageManager().getPackageInfo(
"com.myapp", 0).versionName;
} catch (NameNotFoundException e) {
Log.e(TAG, e.getMessage());
}
return verName;
}
或者在AndroidManifest中將android:versionName=”1.2.0″寫成 android:versionName=”@string/app_versionName”,然后在values/strings.xml中添加對應(yīng) 字符串,這樣實(shí)現(xiàn)之后,就可以使用如下代碼獲得版本名稱:
public static String getVerName(Context context) {
String verName = context.getResources()
.getText(R.string.app_versionName).toString();
return verName;
}
同理,apk的應(yīng)用名稱可以這樣獲得:
public static String getAppName(Context context) {
String verName = context.getResources()
.getText(R.string.app_name).toString();
return verName;
}
2. 流程框架
比較》下載》安裝。
3. 版本檢查
在服務(wù)端放置最新版本的apk文件,如:http://localhost/myapp/myapp.apk
同時,在服務(wù)端放置對應(yīng)此apk的版本信息調(diào)用接口或者文件,如:http://localhost/myapp/ver.json
ver.json中的內(nèi)容為:
[{"appname":"jtapp12","apkname":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]
然后,在手機(jī)客戶端上進(jìn)行版本讀取和檢查:
private boolean getServerVer () {
try {
String verjson = NetworkTool.getContent(Config.UPDATE_SERVER
+ Config.UPDATE_VERJSON);
JSONArray array = new JSONArray(verjson);
if (array.length() > 0) {
JSONObject obj = array.getJSONObject(0);
try {
newVerCode = Integer.parseInt(obj.getString("verCode"));
newVerName = obj.getString("verName");
} catch (Exception e) {
newVerCode = -1;
newVerName = "";
return false;
}
}
} catch (Exception e) {
Log.e(TAG, e.getMessage());
return false;
}
return true;
}
比較服務(wù)器和客戶端的版本,并進(jìn)行更新操作。
if (getServerVerCode()) {
int vercode = Config.getVerCode(this); // 用到前面第一節(jié)寫的方法
if (newVerCode > vercode) {
doNewVersionUpdate(); // 更新新版本
} else {
notNewVersionShow(); // 提示當(dāng)前為最新版本
}
}
詳細(xì)方法:
private void notNewVersionShow() {
int verCode = Config.getVerCode(this);
String verName = Config.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("當(dāng)前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(",/n已是最新版,無需更新!");
Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("軟件更新")
.setMessage(sb.toString())// 設(shè)置內(nèi)容
.setPositiveButton("確定",// 設(shè)置確定按鈕
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).create();// 創(chuàng)建
// 顯示對話框
dialog.show();
}
private void doNewVersionUpdate() {
int verCode = Config.getVerCode(this);
String verName = Config.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("當(dāng)前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(", 發(fā)現(xiàn)新版本:");
sb.append(newVerName);
sb.append(" Code:");
sb.append(newVerCode);
sb.append(", 是否更新?");
Dialog dialog = new AlertDialog.Builder(Update.this)
.setTitle("軟件更新")
.setMessage(sb.toString())
// 設(shè)置內(nèi)容
.setPositiveButton("更新",// 設(shè)置確定按鈕
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
pBar = new ProgressDialog(Update.this);
pBar.setTitle("正在下載");
pBar.setMessage("請稍候...");
pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
downFile(Config.UPDATE_SERVER + Config.UPDATE_APKNAME);
}
})
.setNegativeButton("暫不更新",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// 點(diǎn)擊"取消"按鈕之后退出程序
finish();
}
}).create();// 創(chuàng)建
// 顯示對話框
dialog.show();
}
4. 下載模塊
void downFile(final String url) {
pBar.show();
new Thread() {
public void run() {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
long length = entity.getContentLength();
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(
Environment.getExternalStorageDirectory(),
Config.UPDATE_SAVENAME);
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) {
}
}
}
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
down();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
下載完成,通過handler通知主ui線程將下載對話框取消。
void down() {
handler.post(new Runnable() {
public void run() {
pBar.cancel();
update();
}
});
}
5. 安裝應(yīng)用
void update() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), Config.UPDATE_SAVENAME)),
"application/vnd.android.package-archive");
startActivity(intent);
}
如果你將apk應(yīng)用發(fā)布到market上,那么,你會發(fā)現(xiàn)market內(nèi)建了類似的模塊,可以自動更新或者提醒你是否更新應(yīng)用。那么,對于你自己的 應(yīng)用需要自動更新的話,自己內(nèi)建一個是不是更加方便了呢?本文提到的代碼大多是在UpdateActivity.java中實(shí)現(xiàn),為了能夠使更新過程更加 友好,可以在最初launcher的Activity中建立一個線程,用來檢查服務(wù)端是否有更新。有更新的時候就啟動UpdateActivity,這樣 的使用體驗(yàn)更加平滑。
更多關(guān)于Android相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Android開發(fā)入門與進(jìn)階教程》、《Android通信方式總結(jié)》、《Android基本組件用法總結(jié)》、《Android視圖View技巧總結(jié)》、《Android布局layout技巧總結(jié)》及《Android控件用法總結(jié)》
希望本文所述對大家Android程序設(shè)計有所幫助。
- Android編程實(shí)現(xiàn)自動檢測版本及自動升級的方法
- android實(shí)現(xiàn)程序自動升級到安裝示例分享(下載android程序安裝包)
- Android App實(shí)現(xiàn)應(yīng)用內(nèi)部自動更新的最基本方法示例
- 安卓(Android)應(yīng)用版本更新方法
- Android應(yīng)用自動更新功能實(shí)現(xiàn)的方法
- Android應(yīng)用APP自動更新功能的代碼實(shí)現(xiàn)
- Android應(yīng)用強(qiáng)制更新APP的示例代碼
- Android應(yīng)用App更新實(shí)例詳解
- 非常實(shí)用的小功能 Android應(yīng)用版本的更新實(shí)例
- Android應(yīng)用更新之自動檢測版本及自動升級
相關(guān)文章
Android實(shí)現(xiàn)搜索保存歷史記錄功能
這篇文章主要介紹了Android實(shí)現(xiàn)搜索保存歷史記錄功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
Android中默認(rèn)系統(tǒng)的聲音/大小修改和配置詳解
這篇文章主要給大家介紹了關(guān)于Android中默認(rèn)系統(tǒng)的聲音/大小修改和配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對各位Android開發(fā)者們具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起看看吧。2017-11-11
flutter實(shí)現(xiàn)appbar下選項(xiàng)卡切換
這篇文章主要為大家詳細(xì)介紹了flutter實(shí)現(xiàn)appbar下選項(xiàng)卡切換,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-07-07
Android開發(fā)筆記之:在ImageView上繪制圓環(huán)的實(shí)現(xiàn)方法
本篇文章是對Android中在ImageView上繪制圓環(huán)的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05

