UpdateManager
UpdateManager 对象,用来管理更新,可通过 wx.getUpdateManager 接口获取实例。
方法
UpdateManager.applyUpdate()
强制小程序重启并使用新版本。在小程序新版本下载完成后(即收到 onUpdateReady
回调)调用。
UpdateManager.onCheckForUpdate(function callback)
监听向微信后台请求检查更新结果事件。微信在小程序冷启动时自动检查更新,不需由开发者主动触发。
UpdateManager.onUpdateReady(function callback)
监听小程序有版本更新事件。客户端主动触发下载(无需开发者触发),下载成功后回调。
UpdateManager.onUpdateFailed(function callback)
监听小程序更新失败事件。小程序有新版本,客户端主动触发下载(无需开发者触发),下载失败(可能是网络原因等)后回调。
示例代码
一般是在全局配置app.js的onLaunch函数进行判断。
onLaunch: function () {
const that = this;
//region 如果有更新小程序的版本,就清除缓存
if (wx.canIUse('getUpdateManager')) {
const updateManager = wx.getUpdateManager();
updateManager.onCheckForUpdate(function (res) {
console.debug('onCheckForUpdate====', res);
// 请求完新版本信息的回调
if (res.hasUpdate) {
console.debug('res.hasUpdate====');
updateManager.onUpdateReady(function () {
wx.showModal({
title: '更新提示',
content: '新版本已经准备好,是否重启应用?',
success: function (res) {
console.debug('success====', res);
// res: {errMsg: "showModal: ok", cancel: false, confirm: true}
if (res.confirm) {
// 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
updateManager.applyUpdate();
}
}
})
});
updateManager.onUpdateFailed(function () {
// 新的版本下载失败
wx.showModal({
title: '已经有新版本了哟~',
content: '新版本已经上线啦~,请您删除当前小程序,重新搜索打开哟~'
})
});
}
})
}
//endregion 如果有更新版本,就清除缓存
},