业务逻辑:
系统更新,如果线上有新的安装包了就需要下载新的安装包并且安装更新。

实现逻辑:
如果有新的安装包,则下载新的安装包,但在下载之前需要判断本地文件是否已经存在旧的同名的安装包(如存在然后再下载时,就会在本地出现很多安装包,并且命名也会出错),如果存在则需要先删除点,再下载新的安装包并安装。

涉及理论知识:
获取指定APPID对应的应用信息
在这里插入图片描述

//plus.runtime.version代表的是:manifest.json中设置的apk/ipa版本号。
// plus.runtime.innerVersion;代表的是:客户端运行时基座的版本号

获取指定的目录或文件操作对象
创建成功则返回Download对象
安装应用

代码示例:

//下载之前检测是否已经存在旧的安装包
 checkisexistence(){
            this.loadingtoast = Toast.loading({
                message: '下载中...',
                forbidClick: true,
                duration:0
            });
            if(!window.plus){
                return
            }
            let filename = '防火单位工程端.apk',
            relativePath = "_downloads/" + filename,
            that = this;
            //检查文件是否已存在
            plus.io.resolveLocalFileSystemURL(relativePath, 
                function(entry) {
                    //如果文件存在则删除该文件
                    plus.io.resolveLocalFileSystemURL(relativePath, function(entry2) {
                        entry2.remove(function(entry2) {
                            console.log("文件删除成功==" + relativePath);
                            that.download()
                        }, function(e) {
                            console.log("文件删除失败=" + relativePath);
                        });
                    });
                },
                function(e) {
                    console.log("文件不存在,联网下载=" + relativePath);
                    //如果文件不存在,则去下载
                    that.download()
                }
            )

        },
//下载并安装
 download() {
            let that = this;
            this.apk_name = '防火单位工程端.apk';
            var dtask = plus.downloader.createDownload(this.versionResult.appPath, 
                {
                    filename:"_downloads/"+this.apk_name    //利用保存路径
                }  , function(d, status){
                // 下载完成
                if(status == 200){ 
                    console.log("Download success: " + d.filename);
                    //下载成功,d.filename是文件在保存在本地的相对路径,使用下面的API可转为平台绝对路径
                    var fileSaveUrl = plus.io.convertLocalFileSystemURL(d.filename);
                    console.log("fileSaveUrl",fileSaveUrl)
                    localStorage.clear();
                    that.loadingtoast.clear();
                    plus.runtime.install(fileSaveUrl, {}, 
                        function onSuccess(widgetInfo){
                           console.log('安装成功',widgetInfo)
                        }, function onError(error){
                            console.log('安装error',error)
                        }
                    );
                } else {
                    console.log("Download failed: " + status); 
                    plus.downloader.clear();
                }  
            });
            dtask.start(); 
        }
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐