Android版本更新 ~ 版本号判断
程序员文章站
2022-05-19 22:09:23
...
先贴一个后台返回的一般版本更新接口格式:
拿到后台返回的数据后,对比版本号,如果相等,当前已是最新版本,后台返回的code大于本地应用的code,则允许下载更新。
假设目前已判断到后台code > 本地code
下一步为了节省流量,不用每次都下载,判断下本地是否已经下载了apk,而没有安装,如果已经下载了,那么就直接安装更新,但是有个问题,本地的apk和你现在的apk是否是同一个版本呢?就要再判断一层了。
代码如下:
首先拿到本地的apk的file对象
//通过downLoadId查询下载的apk
public static File queryDownloadedApk(Context context) {
File targetApkFile = null;
DownloadManager downloader = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = PreferencesUtils.getLong(context, UpdateTools.DOWNLOAD_ID);
if (downloadId != -1) {
DownloadManager.Query query = new DownloadManager.Query();
query.setFilterById(downloadId);
query.setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL);
Cursor cur = downloader.query(query);
if (cur != null) {
if (cur.moveToFirst()) {
String uriString = cur.getString(cur.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
if (!TextUtils.isEmpty(uriString)) {
targetApkFile = new File(Uri.parse(uriString).getPath());
}
}
cur.close();
}
}
return targetApkFile;
}
//拿到File
File targetApkFile = UpdataBroadcastReceiver.queryDownloadedApk(mContext);
然后继续根据路径拿到本地apk的版本号后进行比较就OK了
//根据path得到PackageInfo
public static PackageInfo getVersionNameFromApk(Context context, String archiveFilePath) {
PackageManager pm = context.getPackageManager();
PackageInfo packInfo = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
return packInfo;
}
}
// 文件已存在
if (targetApkFile != null && targetApkFile.exists()) {
//还要判断下这个本地的file和当前版本是否一样的,如果一样的,不可更新
PackageInfo packInfo = getVersionNameFromApk(mContext, targetApkFile.getPath());
int versionCode = AppTools.getVersionCode(mContext);
int fileCode = packInfo.versionCode;
if (fileCode <= versionCode) {
initDownNewAPK();
} else {
AppTools.install(targetApkFile, mContext);
}
} else {
initDownNewAPK();
}
上一篇: PHP IPwhois类_PHP教程
下一篇: zend studio9.03 没法调试
推荐阅读
-
[build.gradle配置系列(一)]android studio根据版本号动态生成apk名
-
Android获取手机型号/系统版本号/App版本号等信息实例讲解
-
android中DownloadManager实现版本更新,监听下载进度实例
-
Android版本更新实例详解
-
Android studio版本号查看的三种方法
-
使用Appcan客户端自动更新PHP版本号(全)
-
Win10创造者更新RTM正式版本号可能是15061
-
Windows 10 2019年11月更新官宣:版本号Build 18363.418
-
Win10 21H1版本号确定:系Build 19043小幅更新
-
iOS开发:获取项目名称及版本号(Version/Build)及版本更新提示