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