1.設(shè)計(jì)思路,使用VersionCode定義為版本升級(jí)參數(shù)。
android為我們定義版本提供了2個(gè)屬性:
<manifest package="com.cnblogs.tianxia.subway"
android:versionCode="1" <!--Integer類型,系統(tǒng)不顯示給用戶-->
android:versionName="1.0"<!--String類型,系統(tǒng)顯示用戶-->
></manifest>
谷歌建議我們使用versionCode自增來(lái)表明版本升級(jí),無(wú)論是大的改動(dòng)還是小的改動(dòng),而versionName是顯示用戶看的軟件版本,作為顯示使用。所以我們選擇了VersionCode作為我們定義版本升級(jí)的參數(shù)。
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)。
public class Global {
//版本信息
public static int localVersion = 0;
public static int serverVersion = 0;
public static String downloadDir = "app/download/";
}
因?yàn)楸疚闹皇侵攸c(diǎn)說(shuō)明升級(jí)更新,為了防止其他太多無(wú)關(guān)代碼冗余其中,我直接在SubwayApplication中定義方法initGlobal()方法。
/**
* 初始化全局變量
* 實(shí)際工作中這個(gè)方法中serverVersion從服務(wù)器端獲取,最好在啟動(dòng)畫(huà)面的activity中執(zhí)行
*/
public void initGlobal(){
try{
Global.localVersion = getPackageManager().getPackageInfo(getPackageName(),0).versionCode; //設(shè)置本地版本號(hào)
Global.serverVersion = 1;//假定服務(wù)器版本為2,本地版本默認(rèn)是1
}catch (Exception ex){
ex.printStackTrace();
}
}
如果檢測(cè)到新版本發(fā)布,提示用戶是否更新,我在SubwayActivity中定義了checkVersion()方法:
/**
* 檢查更新版本
*/
public void checkVersion(){
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) {
//開(kāi)啟更新服務(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()初始化版本變量。
public void onCreate() {
super.onCreate();
initGlobal();
}
第二步在SubwayActivity的onCreate()方法中檢測(cè)版本更新checkVersion()。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkVersion();
現(xiàn)在入口已經(jīng)打開(kāi),在checkVersion方法的第18行代碼中看出,當(dāng)用戶點(diǎn)擊更新,我們開(kāi)啟更新服務(wù),從服務(wù)器上下載最新版本。
4.使用Service在后臺(tái)從服務(wù)器端下載,完成后提示用戶下載完成,并關(guān)閉服務(wù)。
定義一個(gè)服務(wù)UpdateService.java,首先定義與下載和通知相關(guān)的變量:
//標(biāo)題
private int titleId = 0;
//文件存儲(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)的下載工作:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//獲取傳值
titleId = intent.getIntExtra("titleId",0);
//創(chuàng)建文件
if(android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())){
updateDir = new File(Environment.getExternalStorageDirectory(),Global.downloadDir);
updateFile = new File(updateDir.getPath(),getResources().getString(titleId)+".apk");
}
this.updateNotificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
this.updateNotification = new Notification();
//設(shè)置下載過(guò)程中,點(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 = "開(kāi)始下載";
updateNotification.setLatestEventInfo(this,"上海地鐵","0%",updatePendingIntent);
//發(fā)出通知
updateNotificationManager.notify(0,updateNotification);
//開(kāi)啟一個(gè)新的線程下載,如果使用Service同步下載,會(huì)導(dǎo)致ANR問(wèn)題,Service本身也會(huì)阻塞
new Thread(new updateRunnable()).start();//這個(gè)是下載的重點(diǎn),是下載的過(guò)程
return super.onStartCommand(intent, flags, startId);
}
上面都是準(zhǔn)備工作
從代碼中可以看出來(lái),updateRunnable類才是真正下載的類,出于用戶體驗(yàn)的考慮,這個(gè)類是我們單獨(dú)一個(gè)線程后臺(tái)去執(zhí)行的。
下載的過(guò)程有兩個(gè)工作:1.從服務(wù)器上下載數(shù)據(jù);2.通知用戶下載的進(jìn)度。
線程通知,我們先定義一個(gè)空的updateHandler。
[/code]
private Handler updateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
}
};
[/code]
再來(lái)創(chuàng)建updateRunnable類的真正實(shí)現(xiàn):
class updateRunnable implements Runnable {
Message message = updateHandler.obtainMessage();
public void run() {
message.what = DOWNLOAD_COMPLETE;
try{
//增加權(quán)限<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">;
if(!updateDir.exists()){
updateDir.mkdirs();
}
if(!updateFile.exists()){
updateFile.createNewFile();
}
//下載函數(shù),以QQ為例子
//增加權(quán)限<uses-permission android:name="android.permission.INTERNET">;
long downloadSize = downloadUpdateFile("http://softfile.3g.qq.com:8080/msoft/179/1105/10753/MobileQQ1.0(Android)_Build0198.apk",updateFile);
if(downloadSize>0){
//下載成功
updateHandler.sendMessage(message);
}
}catch(Exception ex){
ex.printStackTrace();
message.what = DOWNLOAD_FAIL;
//下載失敗
updateHandler.sendMessage(message);
}
}
}
</uses-permission></uses-permission>
下載函數(shù)的實(shí)現(xiàn)有很多,我這里把代碼貼出來(lái),而且我們要在下載的時(shí)候通知用戶下載進(jìn)度:
public long downloadUpdateFile(String downloadUrl, File saveFile) throws Exception {
//這樣的下載代碼很多,我就不做過(guò)多的說(shuō)明
int downloadCount = 0;
int currentSize = 0;
long totalSize = 0;
int updateTotalSize = 0;
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)擊安裝,那么我們來(lái)補(bǔ)全前面的Handler吧。
先在UpdateService.java定義2個(gè)常量來(lái)表示下載狀態(tài):
//下載狀態(tài)
private final static int DOWNLOAD_COMPLETE = 0;
private final static int DOWNLOAD_FAIL = 1;
根據(jù)下載狀態(tài)處理主線程:
private Handler updateHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
switch(msg.what){
case DOWNLOAD_COMPLETE:
//點(diǎn)擊安裝PendingIntent
Uri uri = Uri.fromFile(updateFile);
Intent installIntent = new Intent(Intent.ACTION_VIEW);
installIntent.setDataAndType(uri, "application/vnd.android.package-archive");
updatePendingIntent = PendingIntent.getActivity(UpdateService.this, 0, installIntent, 0);
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);
}
}
};
至此,文件下載并且在通知欄通知進(jìn)度。
發(fā)現(xiàn)本人廢話很多,其實(shí)幾句話的事情,來(lái)來(lái)回回寫(xiě)了這么多,啰嗦了,后面博文我會(huì)朝著精簡(jiǎn)方面努力。
PS:前面說(shuō)要附上cheanUpdateFile()的代碼
File updateFile = new File(Global.downloadDir,getResources().getString(R.string.app_name)+".apk");
if(updateFile.exists()){
//當(dāng)不需要的時(shí)候,清除之前的下載文件,避免浪費(fèi)用戶空間
updateFile.delete();
}