自從友盟關(guān)閉了版本更新功能后,安卓的版本更新只能自己來擼了颁独,結(jié)合之前友盟的版本更新,其實實現(xiàn)起來也簡單伪冰,這里簡單說說版本更新實現(xiàn)的思路:
第一步誓酒,通過接口獲取更新信息(版本號、更新內(nèi)容贮聂、apk下載地址靠柑、是否強制更新)
第二步,通過接口拿到的版本號和本地的版本號進行比較吓懈,如果拿到的版本號比本地的版本號大歼冰,那就進行版本升級
第三步,版本升級分為三種情況:
1耻警、非wifi情況下隔嫡,彈出版本更新提示框,用戶點擊“立即升級”按鈕開始下載apk甘穿,下載完成后提示安裝腮恩。
2、wifi情況下扒磁,直接后臺下載apk庆揪,下載完后彈出版本更新提示框,用戶點擊“立即安裝”按鈕開始安裝apk妨托。
3缸榛、強制更新為true的時候,無論是否wifi情況下兰伤,都是應(yīng)該彈出更新提示框内颗,用戶點擊“立即升級”按鈕開始下載升級,提示框不能取消敦腔,點擊“關(guān)閉”按鈕直接退出app均澳。
基本思路就是上面那樣,下面來看看最雞凍人心的環(huán)節(jié),如何在自己的app加入版本更新功能找前。
BaseAndroid.checkUpdate(MainActivity.this, 2,
"http://f5.market.mi-img.com/download/AppStore/0f4a347f5ce5a7e01315dda1ec35944fa56431d44/luo.footprint.apk",
"更新了XXX\n修復(fù)OOO", false);
看看效果圖
當然啦,前提是你得依賴了我的base庫:
https://github.com/LuoGuoXin/BaseAndroid
哈哈躺盛,你也可以直接復(fù)制版本更新的部分過去就行啦项戴,再根據(jù)自己需求修改下,有什么好的建議記得評論槽惫,因為那個功能我也還沒去優(yōu)化的周叮。
那下面進行代碼分析哈:首先是主方法
/**
* 版本更新
*
* @param context
* @param versionCode 版本號
* @param url apk下載地址
* @param updateMessage 更新內(nèi)容
* @param isForced 是否強制更新
*/
public static void checkUpdate(Context context, int versionCode, String url, String updateMessage, boolean isForced) {
if (versionCode > UpdateManager.getInstance().getVersionCode(context)) {
int type = 0;//更新方式,0:引導(dǎo)更新界斜,1:安裝更新仿耽,2:強制更新
if (UpdateManager.getInstance().isWifi(context)) {
type = 1;
}
if (isForced) {
type = 2;
}
//檢測是否已下載
String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
File dir = new File(downLoadPath);
if (!dir.exists()) {
dir.mkdir();
}
String fileName = url.substring(url.lastIndexOf("/") + 1, url.length());
if (fileName == null && TextUtils.isEmpty(fileName) && !fileName.contains(".apk")) {
fileName = context.getPackageName() + ".apk";
}
File file = new File(downLoadPath + fileName);
//設(shè)置參數(shù)
UpdateManager.getInstance().setType(type).setUrl(url).setUpdateMessage(updateMessage).setFileName(fileName).setIsDownload(file.exists());
if (type == 1 && !file.exists()) {
UpdateManager.getInstance().downloadFile(context);
} else {
UpdateManager.getInstance().showDialog(context);
}
}
}
然后就是UpdateManager的封裝啦,自己看代碼吧各薇,有什么優(yōu)化點評論下项贺,我去修改哈。
/**
* 版本更新
*/
public class UpdateManager {
private String downLoadPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/downloads/";
private int type = 0;//更新方式得糜,0:引導(dǎo)更新敬扛,1:安裝更新,2:強制更新
private String url = "";//apk下載地址
private String updateMessage = "";//更新內(nèi)容
private String fileName = null;//文件名
private boolean isDownload = false;//是否下載
private NotificationManager mNotifyManager;
private NotificationCompat.Builder mBuilder;
private BaseDialog dialog;
private ProgressDialog progressDialog;
public static UpdateManager updateManager;
public static UpdateManager getInstance() {
if (updateManager == null) {
updateManager = new UpdateManager();
}
return updateManager;
}
private UpdateManager() {
}
/**
* 彈出版本更新提示框
*/
public void showDialog(final Context context) {
String title = "";
String left = "";
boolean cancelable = true;
if (type == 1 | isDownload) {
title = "安裝新版本";
left = "立即安裝";
} else {
title = "發(fā)現(xiàn)新版本";
left = "立即更新";
}
if (type == 2) {
cancelable = false;
}
dialog = new BaseDialog.Builder(context).setTitle(title).setMessage(updateMessage).setCancelable(cancelable)
.setLeftClick(left, new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
if (type == 1 | isDownload) {
installApk(context, new File(downLoadPath, fileName));
} else {
if (url != null && !TextUtils.isEmpty(url)) {
if (type == 2) {
createProgress(context);
} else {
createNotification(context);
}
downloadFile(context);
} else {
Toast.makeText(context, "下載地址錯誤", Toast.LENGTH_SHORT).show();
}
}
}
})
.setRightClick("取消", new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
if (type == 2) {
System.exit(0);
}
}
})
.create();
dialog.show();
}
/**
* 下載apk
*
*/
public void downloadFile(final Context context) {
RequestParams params = new RequestParams(url);
params.setSaveFilePath(downLoadPath + fileName);
x.http().request(HttpMethod.GET, params, new Callback.ProgressCallback<File>() {
@Override
public void onSuccess(File result) {
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
Toast.makeText(context, ex.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onCancelled(CancelledException cex) {
}
@Override
public void onFinished() {
}
@Override
public void onWaiting() {
}
@Override
public void onStarted() {
}
@Override
public void onLoading(long total, long current, boolean isDownloading) {
//實時更新通知欄進度條
if (type == 0) {
notifyNotification(current, total);
} else if (type == 2) {
progressDialog.setProgress((int) (current * 100 / total));
}
if (total == current) {
if (type == 0) {
mBuilder.setContentText("下載完成");
mNotifyManager.notify(10086, mBuilder.build());
} else if (type == 2) {
progressDialog.setMessage("下載完成");
}
if (type == 1) {
showDialog(context);
} else {
installApk(context, new File(downLoadPath, fileName));
}
}
}
});
}
/**
* 強制更新時顯示在屏幕的進度條
*
*/
private void createProgress(Context context) {
progressDialog = new ProgressDialog(context);
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.setMessage("正在下載...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
}
/**
* 創(chuàng)建通知欄進度條
*
*/
private void createNotification(Context context) {
mNotifyManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(context);
mBuilder.setSmallIcon(BaseAndroid.getBaseConfig().getAppLogo());
mBuilder.setContentTitle("版本更新");
mBuilder.setContentText("正在下載...");
mBuilder.setProgress(0, 0, false);
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_AUTO_CANCEL;
mNotifyManager.notify(10086, notification);
}
/**
* 更新通知欄進度條
*
*/
private void notifyNotification(long percent, long length) {
mBuilder.setProgress((int) length, (int) percent, false);
mNotifyManager.notify(10086, mBuilder.build());
}
/**
* 安裝apk
*
* @param context 上下文
* @param file APK文件
*/
private void installApk(Context context, File file) {
Intent intent = new Intent();
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
context.startActivity(intent);
}
/**
* @return 當前應(yīng)用的版本號
*/
public int getVersionCode(Context context) {
try {
PackageManager manager = context.getPackageManager();
PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
int version = info.versionCode;
return version;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 判斷當前網(wǎng)絡(luò)是否wifi
*/
public boolean isWifi(Context mContext) {
ConnectivityManager connectivityManager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
return true;
}
return false;
}
public UpdateManager setUrl(String url) {
this.url = url;
return this;
}
public UpdateManager setType(int type) {
this.type = type;
return this;
}
public UpdateManager setUpdateMessage(String updateMessage) {
this.updateMessage = updateMessage;
return this;
}
public UpdateManager setFileName(String fileName) {
this.fileName = fileName;
return this;
}
public UpdateManager setIsDownload(boolean download) {
isDownload = download;
return this;
}
}