天天看点

Android版本更新 ~ 版本号判断

先贴一个后台返回的一般版本更新接口格式:

Android版本更新 ~ 版本号判断

拿到后台返回的数据后,对比版本号,如果相等,当前已是最新版本,后台返回的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();
    }