前面這部分轉載:http://blog.csdn.net/xjanker2/archive/2011/04/06/6303937.aspxhtml
咱們看到不少Android應用都具備自動更新功能,用戶一鍵就能夠完成軟件的升級更新。得益於Android系統的軟件包管理和安裝機制,這一功能實現起來至關簡單,下面咱們就來實踐一下。首先給出界面效果:java
1. 準備知識
在AndroidManifest.xml裏定義了每一個Android apk的版本標識:
android
view plaincopy to clipboardweb
<manifest xmlns:android="http://schemas.android.com/apk/res/android" apache
package="com.myapp" json
android:versionCode="1" tomcat
android:versionName="1.0.0"> 服務器
<application></application> app
</manifest> 框架
[xhtml] view plaincopy
<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是整型數字,versionName是字符串。因爲version是給用戶看的,不太容易比較大小,升級檢查時,能夠以檢查versionCode爲主,方便比較出版本的先後大小。
那麼,在應用中如何讀取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;
}
[java] view plaincopy
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中添加對應字符串,這樣實現以後,就能夠使用以下代碼得到版本名稱:
public static String getVerName(Context context) {
String verName = context.getResources()
.getText(R.string.app_versionName).toString();
return verName;
}
[java] view plaincopy
public static String getVerName(Context context) {
String verName = context.getResources()
.getText(R.string.app_versionName).toString();
return verName;
}
同理,apk的應用名稱能夠這樣得到:
public static String getAppName(Context context) {
String verName = context.getResources()
.getText(R.string.app_name).toString();
return verName;
}
[java] view plaincopy
public static String getAppName(Context context) {
String verName = context.getResources()
.getText(R.string.app_name).toString();
return verName;
}
2. 流程框架
3. 版本檢查
在服務端放置最新版本的apk文件,如:http://localhost/myapp/myapp.apk
同時,在服務端放置對應此apk的版本信息調用接口或者文件,如:http://localhost/myapp/ver.json
ver.json中的內容爲:
[{"appname":"jtapp12","apkname":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]
[xhtml] view plaincopy
[{"appname":"jtapp12","apkname":"jtapp-12-updateapksamples.apk","verName":1.0.1,"verCode":2}]
而後,在手機客戶端上進行版本讀取和檢查:
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;
}
[java] view plaincopy
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;
}
比較服務器和客戶端的版本,並進行更新操做。
if (getServerVerCode()) {
int vercode = Config.getVerCode(this); // 用到前面第一節寫的方法
if (newVerCode > vercode) {
doNewVersionUpdate(); // 更新新版本
} else {
notNewVersionShow(); // 提示當前爲最新版本
}
}
[java] view plaincopy
if (getServerVerCode()) {
int vercode = Config.getVerCode(this); // 用到前面第一節寫的方法
if (newVerCode > vercode) {
doNewVersionUpdate(); // 更新新版本
} else {
notNewVersionShow(); // 提示當前爲最新版本
}
}
詳細方法:
private void notNewVersionShow() {
int verCode = Config.getVerCode(this);
String verName = Config.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("當前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(",/n已經是最新版,無需更新!");
Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("軟件更新")
.setMessage(sb.toString())// 設置內容
.setPositiveButton("肯定",// 設置肯定按鈕
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).create();// 建立
// 顯示對話框
dialog.show();
}
private void doNewVersionUpdate() {
int verCode = Config.getVerCode(this);
String verName = Config.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("當前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(", 發現新版本:");
sb.append(newVerName);
sb.append(" Code:");
sb.append(newVerCode);
sb.append(", 是否更新?");
Dialog dialog = new AlertDialog.Builder(Update.this)
.setTitle("軟件更新")
.setMessage(sb.toString())
// 設置內容
.setPositiveButton("更新",// 設置肯定按鈕
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) {
// 點擊"取消"按鈕以後退出程序
finish();
}
}).create();// 建立
// 顯示對話框
dialog.show();
}
[java] view plaincopy
private void notNewVersionShow() {
int verCode = Config.getVerCode(this);
String verName = Config.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("當前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(",/n已經是最新版,無需更新!");
Dialog dialog = new AlertDialog.Builder(Update.this).setTitle("軟件更新")
.setMessage(sb.toString())// 設置內容
.setPositiveButton("肯定",// 設置肯定按鈕
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).create();// 建立
// 顯示對話框
dialog.show();
}
private void doNewVersionUpdate() {
int verCode = Config.getVerCode(this);
String verName = Config.getVerName(this);
StringBuffer sb = new StringBuffer();
sb.append("當前版本:");
sb.append(verName);
sb.append(" Code:");
sb.append(verCode);
sb.append(", 發現新版本:");
sb.append(newVerName);
sb.append(" Code:");
sb.append(newVerCode);
sb.append(", 是否更新?");
Dialog dialog = new AlertDialog.Builder(Update.this)
.setTitle("軟件更新")
.setMessage(sb.toString())
// 設置內容
.setPositiveButton("更新",// 設置肯定按鈕
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) {
// 點擊"取消"按鈕以後退出程序
finish();
}
}).create();// 建立
// 顯示對話框
dialog.show();
}
4. 下載模塊
注,本部分參考了前人的相關實現,見 http://apps.hi.baidu.com/share/detail/24172508
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();
}
[java] view plaincopy
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();
}
});
}
[java] view plaincopy
void down() {
handler.post(new Runnable() {
public void run() {
pBar.cancel();
update();
}
});
}
5. 安裝應用
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);
}
[java] view plaincopy
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應用發佈到market上,那麼,你會發現market內建了相似的模塊,能夠自動更新或者提醒你是否更新應用。那麼,對於你本身的應用須要自動更新的話,本身內建一個是否是更加方便了呢?本文提到的代碼大可能是在UpdateActivity.java中實現,爲了可以使更新過程更加友好,能夠在最初launcher的Activity中創建一個線程,用來檢查服務端是否有更新。有更新的時候就啓動UpdateActivity,這樣的使用體驗更加平滑。
關於Tomcat這部分我本身整理以下:
1)在Apache 官網http://tomcat.apache.org/下載安裝就能夠了,我本身裝的是Tomcat 7.0版本。
2)在Tomcat安裝默認路徑下找到webapps文件夾並在該文件夾下新建一個myapp文件夾(你能夠命名成你本身喜歡的文件夾名)
3)把上面提到的ver.json 文件保存放到myapp文件夾下
4)把你要升級安裝的apk文件也放到myapp文件夾下就能夠了
注意事項:訪問android模擬器的端口是http://10.0.2.2:8080
源代碼出處:http://code.google.com/p/androidex/source/browse/trunk/jtapp-12-updateapksamples