Vue用Cordova打包後的app自升級功能實現
阿新 • • 發佈:2018-12-17
Vue專案
1.在util目錄下新建upgrade.js
關鍵程式碼:
import * as common from '@/api/common'; //檢測新版本升級 export function upgradeForAndroid( releasePath,packageName) { AlertModule.show({title: '已經下載:0%'}) var url = releasePath; //apk所在的伺服器路徑 var targetPath = cordova.file.externalCacheDirectory + "Download/Pass/" + packageName; //要下載的目標路徑及檔名 var trustHosts = true; var options = {}; console.log("url:" + url); console.log("targetPah:" + targetPath); console.log("trustHost:" + trustHosts); downLoadApp(); function downLoadApp() { // 初始化FileTransfer物件 var fileTransfer = new FileTransfer(); fileTransfer.onprogress = function(progressEvent) { if (progressEvent.lengthComputable) { var downloadProgress = (progressEvent.loaded / progressEvent.total) * 100; var result="已經下載:"+ Math.floor(downloadProgress)+ "%"; AlertModule.show({title: result}) } }; // 呼叫download方法 fileTransfer.download( url, //uri網路下載路徑 targetPath, //url本地儲存路徑 function (entry) { console.log("download complete: " + entry.toURL()); cordova.plugins.fileOpener2.open( targetPath, 'application/vnd.android.package-archive', { error: function (e) { console.log('Error status: ' + e.status + ' - Error message: ' + e.message); AlertModule.show({title: "開啟下載檔案失敗"}) }, success: function () { console.log('open successfully'); } }) }, function (error) { AlertModule.show({title: "下載失敗"}) console.log("download error source " + error.source); console.log("download error target " + error.target); console.log("upload error code" + error.code); } ); } } /* * 檢測升級方法 */ export function checkUpgrade(platformType, title) { console.log("裝置型別:" + platformType); var appName = "應用名字"; var appType = platformType; /** * 從伺服器獲取應用的版本資訊,和本地應用版本對比 * @param appName 應用名稱 * @param appType 應用型別 */ common.getAppInfo(appName,appType).then(response =>{ if(response!=null){ var packageName = response.data.packageName; var releasePath = process.env.BASE_API+"/" + response.data.path + "/" + response.data.packageName; var serverVersion = response.data.appVersion; //獲取本地App版本; cordova.getAppVersion.getVersionNumber().then(function (version) { console.log("本地版本:" + version); console.log("伺服器版本:" + serverVersion); if (version < serverVersion) { //$rootScope.$state.isLogin = false; localStorage.setItem("appUpgrade", "0"); localStorage.removeItem("password"); //退出登入 appRouter.$vux.confirm.show({ // 元件除show外的屬性 onCancel () { }, onConfirm () { if (platformType == 'Android') { console.log("---Android升級中,請稍後---"); upgradeForAndroid(releasePath,packageName); } else { console.log("---Ios升級中,請稍後---"); cordova.plugins.externalExtension.openURL(response.data.path.toString()); } }, title:'發現新版本:'+serverVersion +','+'請進行升級' , content: title+response.data.remark, }) } }); } }).catch(error =>{ //請求失敗處理函式 AlertModule.show({title: "請求錯誤!!"}) }) // 監聽網路狀況,無網路時 document.addEventListener('offline', function () { debugger console.log("網路異常,不能連線到伺服器!"); alert({ template: "<span class='c_white text_bold'>網路異常,不能連線到伺服器!</span>" }); setTimeout(function () { console.log("settimeOut方法"); }, 2000); }, false); }
2.來到api目錄下的common.js
關鍵程式碼:
//從伺服器獲取應用的版本資訊,和本地應用版本對比
export function getAppInfo(appName,appType) {
return fetch({
headers: {"Content-Type": "application/json"},
url: '/mobile/common/getAppInfo',
method: 'post',
data:{
appName:appName,
appType: appType
}
})
}
3.來到config目錄下的dev.env.js,配置開發環境的伺服器url(本地伺服器)
關鍵程式碼:
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
isWeChat: false,
NODE_ENV: '"development"',
BASE_API: 'http://127.0.0.1:8080/你自己的專案url'
})
4.然後找到config目錄下的pro.env.js,配置正式環境下的伺服器url(雲端伺服器)
關鍵程式碼:
'use strict' module.exports = { isWeChat: false, NODE_ENV: '"production"', BASE_API: '"雲端伺服器域名"' }
配置後臺SSM程式碼
1.根據前端common.js配置的路徑,找到後臺@RequestMapping對應路徑下的Action
這裡是:mobile/action/CommonAction.java
對應於:@RequestMapping("mobile/common")下的@RequestMapping(value = "getAppInfo")
關鍵程式碼:
@ResponseBody
@RequestMapping(value = "getAppInfo")
public Json<SysApp> getAppInfo(@RequestBody Map<String, Object> map) {
SysApp app=null;
try {
Map<String,Object> param= new HashMap<String,Object>();
param.put("stauts","0");
param.put("appName",map.get("appName"));
param.put("appType",map.get("appType"));
List<SysApp> list = appService.getByParam(param);
if(list.size()>0) {
app=list.get(0);
}
return new Json<SysApp>().success(app);
} catch (Exception e) {
e.printStackTrace();
LogService.getInstance().error("APP-> CommonAction -> 'getAppInfo'->getAppInfo is exception",e);
return new Json<SysApp>().fail();
}
}
2.然後一層層來到seviceImpl、dao、mapper層,就是簡單的單表查詢。
資料庫內容:
CREATE TABLE `sys_app` (
`Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主鍵',
`AppName` varchar(100) DEFAULT NULL COMMENT 'App名稱',
`AppType` varchar(20) DEFAULT NULL COMMENT 'App型別',
`AppVersion` varchar(20) DEFAULT NULL COMMENT 'App版本',
`PackageName` varchar(100) DEFAULT NULL COMMENT '打包名稱',
`Path` varchar(100) DEFAULT NULL COMMENT '路徑',
`PublishDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '釋出日期',
`ProductId` int(11) DEFAULT NULL COMMENT '所屬產品Id',
`ProductName` varchar(50) DEFAULT NULL COMMENT '所屬產品名稱',
`Remark` varchar(4000) DEFAULT NULL COMMENT '備註',
PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT charset=utf8 ROW_FORMAT=DYNAMIC COMMENT='APP管理 - APP版本控制表';
更新版本設定
將資料庫中,AppVersion改為與上次版本不一致的版本號,要大於上次的版本號。
將PackageName設定為伺服器上的apk的名字
將Path設定為為Tomcat上配置的虛擬路徑。
Remark設定為更新的提示內容
伺服器設定
1.將已經打包好的apk檔案放置在伺服器上的某個目錄,這裡是:
C:\release\sites\upload\apk
然後開啟伺服器上的Tomcat下的conf目錄下的server.xml配置虛擬路徑的對映
<Host name="" debug="0" appBase="webapps" unpackWARs="true" autoDeploy="true">
<Context docBase="C:\release\sites\upload" path="upload" reloadable="true"/>
</Host>
2.這樣就就將伺服器上的物理路徑與虛擬路徑對映完成,此時資料庫中的upload/apk目錄就能定位到伺服器上具體磁碟的路徑。