插件 "rn-app-upgrade": "^2.1.8"
组件代码:
import React, { PureComponent } from "react";
import {
View,
Image,
Text,
InteractionManager,
ProgressViewIOS,
ProgressBarAndroid,
Platform,
Modal,
StyleSheet,
Dimensions,
ScrollView,
NativeModules,
TouchableOpacity,
Linking,
} from "react-native";
import CodePush from "react-native-code-push";
import { Router, Scene } from "react-native-router-flux";
import {
downloadApk,
versionName,
versionCode,
openAPPStore,
checkIOSUpdate,
addDownLoadListener,
} from "rn-app-upgrade";
// import Loading from './view/screen/home/Loading';
import { Colors, Metrics } from "../../theme/Index";
import { Version, CodePushKey, CodePushKeyIos } from "../../config/Index";
import { Send } from "../../utils/Http";
import Toast from "../../components/Toast";
import { connect } from "react-redux";
class Update extends PureComponent {
constructor(props) {
super(props);
this.state = {
updateingText: "",
updateModalVisible: false,
updateInfo: {},
updateProgressBarVisible: false,
noticeModalVisible: true,
};
}
componentDidMount() {
InteractionManager.runAfterInteractions(() => {
// CodePush.notifyAppReady();
this.fetchVersion();
});
}
/**
* 获取线上版本
*/
fetchVersion() {
if (this.props.hiddenUpdateModal == true) {
console.log("用户启动时点击了不更新跳过更新检查");
return;
}
let systemName = Platform.OS.toLowerCase();
Send(`api/v1/version`, "get")
.then((res) => {
console.log("检查版本返回:");
console.log(res);
if (res.status == "Success") {
this.checkUpdateApp(res.data); //{ currentVersion: '1.0.0', downloadUrl: 'http://app-1251750492.file.myqcloud.com/prod/x7game2.0.7.apk', updateContent: '118创富助手 喜普大奔 今日上线公测! 1.0.1' }
}
})
.catch((res) => {
Toast.tip("检查版本失败");
console.log("检查版本失败");
});
// this.checkUpdateApp(testData); //
}
parseVersion(version) {
if (version == null || version == "") return 0;
var arr = version.split(".");
if (arr == null || arr.length != 3) return 0;
return parseInt(arr[0]) * 100 + parseInt(arr[1]) * 10 + parseInt(arr[2]);
}
/**
* 线上版本获取
*/
checkUpdateApp(updateInfo) {
// 后端自己做了判断
if (updateInfo.upgrade == false) {
console.log("后端返回不需要更新");
return;
}
let currentVersion = this.parseVersion(updateInfo.data.version);
if (currentVersion == 0) {
Toast.tip("服务器无版本信息");
return;
}
// this.props.updateVersion(currentVersion, true);
if (this.parseVersion(Version) >= currentVersion) {
console.log("不需要更新");
return;
}
console.log("准备更新");
this.setState({ updateInfo }, () => {
this.setState({ updateModalVisible: true });
/*
if (isHotReload) {
// 热更新强制弹框
if (isSilent) {
// 静默更新
this.hotReload(CodePush.InstallMode.IMMEDIATE);
} else {
this.setState({ updateModalVisible: true });
}
} else {
if (Platform.OS === "ios") {
// IOS升级ipa
this.setState({ updateModalVisible: true });
} else {
this.setState({ updateModalVisible: true });
}
}*/
});
}
/**
* 热更新更新流程
* @param {*} mode
*/
hotReload(mode) {
if (!this.state.updateProgressBarVisible) this.setState({ updateProgressBarVisible: true });
CodePush.sync(
{
installMode: CodePush.InstallMode.IMMEDIATE,
mandatoryInstallMode: mode,
deploymentKey: Platform.OS === "ios" ? CodePushKeyIos : CodePushKey,
updateDialog: false,
},
(status) => {
console.log("code-push status" + status);
if ([0, 2, 3, 8].indexOf(status) !== -1) this.setState({ updateModalVisible: false });
},
(process) => {
let { totalBytes, receivedBytes } = process;
console.log("code-push process-->" + totalBytes + " / " + receivedBytes);
},
(update) => {
console.log("code-push update" + update);
}
);
}
/**
* 应用商店更新流程
*/
downloadApp() {
let updateInfo = this.state.updateInfo;
this.setState({ updateingText: "" });
let that = this;
console.log("开始更新:" + updateInfo.data.path);
if (Platform.OS === "ios") {
// var IPAInstall = NativeModules.IPAInstall2;
// IPAInstall.itms_install(updateInfo['data.path']);
Linking.openURL(updateInfo.data.path);
} else {
// upgrade(updateInfo.data.path);
// Linking.openURL(updateInfo.data.path);
downloadApk({
interval: 666, // listen to upload progress event, emit every 666ms
apkUrl: updateInfo.data.path,
downloadInstall: true,
callback: {
onProgress: (received, total, percent) => {
let txt = percent + "% (" + received + "/" + total + ")";
//console.log(txt);
this.setState({ updateingText: txt });
},
onFailure: (errorMessage, statusCode) => {
console.log("更新失败");
this.setState({ updateingText: "更新失败" });
},
onComplete: () => {
console.log("完成");
this.setState({ updateingText: "下载完成" });
},
},
});
}
if (!this.state.updateProgressBarVisible) this.setState({ updateProgressBarVisible: true });
}
/**
* 渲染更新Bar
*/
renderAppUpdateBar() {
return (
onPress={() => { this.setState({ updateModalVisible: false }); this.props.sethiddenUpdateModal(); }}>
//
);
}
/**
* 热更新进度条
*/
renderAppUpdateProgress = () => {
let progressValue = 0;
return (
style={{ width: Metrics.screenWidth * 0.55, paddingTop: 10, paddingBottom: Platform.OS === "ios" ? 35 : 20, }}> {Platform.OS === "ios" ? ( progressTintColor={Colors.C6} trackTintColor={Colors.C6} progress={progressValue} /> ) : ( animating styleAttr="Horizontal" color={Colors.C6} progress={progressValue} /> )}
);
};
/**
* 系统更新提示框
*/
renderUpdateModal() {
return (
style={[ styles.updateContainer, { position: "absolute", left: 0, right: 0, top: 0, bottom: 0, backgroundColor: "black", opacity: 0.5, }, ]} /> source={require("../../image/login/log.png")} resizeMode="contain" style={{ width: Metrics.screenWidth * 0.45, height: Metrics.screenWidth * 0.45 * 0.454, marginTop: 15, }} /> {this.state.updateProgressBarVisible ? ( 正在更新:{this.state.updateingText} ) : ( {this.state.updateInfo == null || this.state.updateInfo.data == null ? "" : `发现新版本${this.state.updateInfo.data.version}`} )} {/* {this.state.updateProgressBarVisible ? this.renderAppUpdateProgress() : this.renderAppUpdateBar()}
);
}
render() {
return this.renderUpdateModal();
}
}
const styles = StyleSheet.create({
container: { flex: 1, backgroundColor: "#FFFFFF" },
updateContainer: { flex: 1, justifyContent: "center", alignItems: "center" },
updateHeader: {
width: Metrics.screenWidth * 0.75,
backgroundColor: "#FFFFFF",
borderRadius: 10,
alignItems: "center",
},
updateVersion: { fontSize: 17, textAlign: "center", marginTop: 20 },
updateContent: { fontSize: 14, paddingTop: 15 },
updateFooter: {
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
alignSelf: "center",
},
updateFooterBtn: {
marginTop: 15,
marginBottom: 15,
flexDirection: "row",
justifyContent: "center",
alignItems: "center",
alignSelf: "center",
height: 38,
width: Metrics.screenWidth * 0.28,
backgroundColor: "#0E96A4",
borderRadius: 17,
marginHorizontal: 5,
},
updateText: { fontSize: 14, color: "#FFFFFF" },
});
// export default Update;
const mapStateToProps = (state) => ({
hiddenUpdateModal: state.Home.hiddenUpdateModal,
});
const mapDispatchToProps = (dispatch) => ({
sethiddenUpdateModal: () =>
dispatch({
type: "Home/setFormData",
payload: { name: "hiddenUpdateModal", value: true },
}),
});
export default connect(mapStateToProps, mapDispatchToProps)(Update);