1.設(shè)計(jì)思路,使用VersionCode定義為版本升級(jí)參數(shù)。
android為我們定義版本提供了2個(gè)屬性:
2.工程目錄
為了對(duì)真實(shí)項(xiàng)目或者企業(yè)運(yùn)用有實(shí)戰(zhàn)指導(dǎo)作用,我模擬一個(gè)獨(dú)立的項(xiàng)目,工程目錄設(shè)置的合理嚴(yán)謹(jǐn)一些,而不是僅僅一個(gè)demo。
假設(shè)我們以上海地鐵為項(xiàng)目,命名為"Subway",工程結(jié)構(gòu)如下,
3.版本初始化和版本號(hào)的對(duì)比。
首先定義在全局文件Global.java中定義變量localVersion和serverVersion分別存放本地版本號(hào)和服務(wù)器版本號(hào)。
if(Global.localVersion < Global.serverVersion){
//發(fā)現(xiàn)新版本,提示用戶更新
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("軟件升級(jí)")
.setMessage("發(fā)現(xiàn)新版本,建議立即更新使用.")
.setPositiveButton("更新", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//開啟更新服務(wù)UpdateService
//這里為了把update更好模塊化,可以傳一些updateService依賴的值
//如布局ID,資源ID,動(dòng)態(tài)獲取的標(biāo)題,這里以app_name為例
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{
//清理工作,略去
//cheanUpdateFile(),文章后面我會(huì)附上代碼
}
}
好,我們現(xiàn)在把這些東西串一下:
第一步在SubwayApplication的onCreate()方法中執(zhí)行initGlobal()初始化版本變量。
現(xiàn)在入口已經(jīng)打開,在checkVersion方法的第18行代碼中看出,當(dāng)用戶點(diǎn)擊更新,我們開啟更新服務(wù),從服務(wù)器上下載最新版本。
4.使用Service在后臺(tái)從服務(wù)器端下載,完成后提示用戶下載完成,并關(guān)閉服務(wù)。
定義一個(gè)服務(wù)UpdateService.java,首先定義與下載和通知相關(guān)的變量:
//文件存儲(chǔ)
private File updateDir = null;
private File updateFile = null;
//通知欄
private NotificationManager updateNotificationManager = null;
private Notification updateNotification = null;
//通知欄跳轉(zhuǎn)Intent
private Intent updateIntent = null;
private PendingIntent updatePendingIntent = null;
在onStartCommand()方法中準(zhǔn)備相關(guān)的下載工作:
this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
this.updateNotification = new Notification();
//設(shè)置下載過程中,點(diǎn)擊通知欄,回到主界面
updateIntent = new Intent(this, SubwayActivity.class);
updatePendingIntent = PendingIntent.getActivity(this,0,updateIntent,0);
//設(shè)置通知欄顯示內(nèi)容
updateNotification.icon = R.drawable.arrow_down_float;
updateNotification.tickerText = "開始下載";
updateNotification.setLatestEventInfo(this,"上海地鐵","0%",updatePendingIntent);
//發(fā)出通知
updateNotificationManager.notify(0,updateNotification);
//開啟一個(gè)新的線程下載,如果使用Service同步下載,會(huì)導(dǎo)致ANR問題,Service本身也會(huì)阻塞
new Thread(new updateRunnable()).start();//這個(gè)是下載的重點(diǎn),是下載的過程
return super.onStartCommand(intent, flags, startId);
}
從代碼中可以看出來,updateRunnable類才是真正下載的類,出于用戶體驗(yàn)的考慮,這個(gè)類是我們單獨(dú)一個(gè)線程后臺(tái)去執(zhí)行的。
下載的過程有兩個(gè)工作:1.從服務(wù)器上下載數(shù)據(jù);2.通知用戶下載的進(jìn)度。
線程通知,我們先定義一個(gè)空的updateHandler。
[/code]
private Handler updateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
}
};
[/code]
再來創(chuàng)建updateRunnable類的真正實(shí)現(xiàn):
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;
//為了防止頻繁的通知導(dǎo)致應(yīng)用吃緊,百分比增加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;
}
下載完成后,我們提示用戶下載完成,并且可以點(diǎn)擊安裝,那么我們來補(bǔ)全前面的Handler吧。
先在UpdateService.java定義2個(gè)常量來表示下載狀態(tài):
updateNotification.defaults = Notification.DEFAULT_SOUND;//鈴聲提醒
updateNotification.setLatestEventInfo(UpdateService.this, "上海地鐵", "下載完成,點(diǎn)擊安裝。", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
//停止服務(wù)
stopService(updateIntent);
case DOWNLOAD_FAIL:
//下載失敗
updateNotification.setLatestEventInfo(UpdateService.this, "上海地鐵", "下載完成,點(diǎn)擊安裝。", updatePendingIntent);
updateNotificationManager.notify(0, updateNotification);
default:
stopService(updateIntent);
}
}
};