一般服务器会返回最新的apk版本,格式为1.x.x,前端拿到后跟自己的版本号对比,如果我们的版本号小于最新的,就会弹出更新弹窗。
1、将版本号转为数字进行对比
function handlerVersionString(version) {
let versions = version.split('.');
let number = 0;
if (versions.length === 3) {
number = parseInt(versions[0]) * 10000 + parseInt(versions[1]) * 100 + parseInt(versions[2])
} else {
number = parseInt(versions[0]) * 10000 + parseInt(versions[1]) * 100
}
return number;
}
2、进行对比,用到DeviceInfo库,安卓APP升级用到的是rn-app-upgrade库。
import DeviceInfo from 'react-native-device-info';
import {upgrade} from 'rn-app-upgrade';
//安卓检查更新
state={
showModal:false,
}
componentDidMount() {
store.get('lastVST').then((lastTime)=>{
if(lastTime){
//对比上次显示时间 如果超过24小时就显示
let now = new Date()
let diff = now.getTime() - parseInt(lastTime)
console.log('上次提示时间',lastTime)
console.log('距离上次提示时间间隔',diff)
if( diff > 3600 * 24 * 1000 ){
this.checkAppVersion()
}
}else{
this.checkAppVersion()
}
})
}
checkAppVersion(){
const version = handlerVersionString( DeviceInfo.getVersion() )
//服务器返回的版本号 remoteAppVersion 比如1.2.0
if(handlerVersionString(remoteAppVersion) > version){
this.versionDialog.current.show(data,()=>{
if(Platform.OS === 'android'){
upgrade(data.download_url)
}else{
//如果是iOS则跳转到Apple store应用商店,代码忽略
}
})
}
}
render(){
<>
....
//更新弹窗
<NewVersion
show={showModal}
data={versionData}
onCancel={()=>{
//记录一下当前时间lastVersionShowTime 防止每次都提示
let date = new Date()
store.save('lastVST',date.getTime())
this.setState({
showModal:false
})
}}
onConfirm={()=>{
//记录一下当前时间lastVersionShowTime 防止每次都提示
let date = new Date()
store.save('lastVST',date.getTime())
upgrade(versionData.download_url)
}}
/>
<>
}
网友评论