提示:当前环境较新为
"react-native": "0.70.1",
"react-native-code-push": "^7.0.5",
"react": "18.1.0",
gradle版本 distributionUrl=https://services.gradle.org/distributions/gradle-7.4.1-all.zip
node v16.15.1
npm 8.11.0
java:
java version "11.0.16" 2022-07-19 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.16+11-LTS-199)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.16+11-LTS-199, mixed mode)
Android Studio:
Android Studio Dolphin | 2021.3.1
Build #AI-213.7172.25.2113.9014738, built on September 1, 2022
Runtime version: 11.0.13+0-b1751.21-8125866 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o.
Windows 10 10.0
GC: G1 Young Generation, G1 Old Generation
Memory: 1280M
Cores: 16
Registry:
external.system.auto.import.disabled=true
ide.text.editor.with.preview.show.floating.toolbar=false
CodePush注册
安装appcenter-cli
npm install -g appcenter-cli
登录AppCenter
appcenter login
然后会打开一个浏览器界面,如果没有账号创建一个账号并登录,之后会出现:
复制上面的token。
如果没有出现可以重新执行下上面命令。
之后在终端输入Access code,然后会得到一个登录用户名:
获取部署秘钥
查看你的AppCenter中有哪些应用:
appcenter apps list
如果没有,则需要在AppCenter上创建一个RN应用:
注意:安卓的话请在os中选择Android
为应用创建部署秘钥:
appcenter codepush deployment add -a crazycodeboy/RN2-Android Staging
appcenter codepush deployment add -a crazycodeboy/RN2-iOS Staging
注意:默认添加的项目就是Staging 也可以改成其他名称Production(生产环境)
查看应用的部署秘钥:
appcenter codepush deployment list -a crazycodeboy/RN2-Android -k
至此,使用CodePush前的准备已经完成了,接下来让我们一起在项目中集成CodePush。
参考
安装react-native-code-push
npm install --save react-native-code-push
配置android/settings.gradle
在android/settings.gradle 中添加:
include ':app', ':react-native-code-push'
project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')
如图所示:
在android/app/build.gradle文件中,将该codepush.gradle文件添加为下面的附加构建任务定义react.gradle:
...
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
...
如图所示更新MainApplication.java
在MainApplication.java中重写getJSBundleFile并返回CodePush.getJSBundleFile():
...
// 1. 导入CodePush.
import com.microsoft.codepush.react.CodePush;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
...
// 2. 重写getJSBundleFile 方法让CodePush决定从哪里加载JS
@Override
protected String getJSBundleFile() {
return CodePush.getJSBundleFile();
}
};
}
在strings.xml中添加部署秘钥
<resources>
<string name="app_name">AppName</string>
<string moduleConfig="true" name="CodePushDeploymentKey">DeploymentKey</string>
</resources>
将DeploymentKey替换为上面获取的部署秘钥(把string标签中的DeploymentKey改为秘钥,而非string中name的DeploymentKey)
注意如果是打包release版本到Production的话,需要把strings.xml里面的去掉
并且对于 React Native >= v0.60
1.打开项目的app目录下的build.gradle文件(例如android/app/build.gradle)
2.找到android { buildTypes {} }定义resValue,它们分别引用不同的部署密钥。debug release Staging Production
android {
...
buildTypes {
debug {
...
// Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.
resValue "string", "CodePushDeploymentKey", '""'
...
}
releaseStaging {
...
resValue "string", "CodePushDeploymentKey", '"<INSERT_STAGING_KEY>"'
// Note: It is a good idea to provide matchingFallbacks for the new buildType you create to prevent build issues
// Add the following line if not already there
matchingFallbacks = ['release']
...
}
release {
...
resValue "string", "CodePushDeploymentKey", '"<INSERT_PRODUCTION_KEY>"'
...
}
}
...
}
如图所示修改app版本号versionName:'1.0'为versionName:'1.0.0' 因为微软上的appcenter里面的app Version要和我们build.gradle的一致,不然可能出现问题
React Native < v0.60版本的,请按照下面参考官方的文档进行相关配置
参考
在JS中使用CodePush
在JS文件中导入CodePush:
安装
npm i react-native-code-push --save
import CodePush from 'react-native-code-push';
API说明
CodePush支持的常见API说明:
- sync:允许检查更新、下载和安装,只需一个电话。除非您需要自定义 UI 和/或行为,否则我们建议大多数开发人员在将 CodePush 集成到他们的应用程序中时使用此方法;
- allowRestart:重新允许因安装更新而发生程序化重启,并且可选地,如果挂起的更新试图在不允许重启时重启应用程序,则立即重启应用程序。这是一个高级 API,仅当您的应用程序通过 disallowRestart 方法明确禁止重新启动时才需要。
- checkForUpdate:询问 CodePush 服务配置的应用程序部署是否有可用更新。
- disallowRestart:暂时禁止因安装 CodePush 更新而发生任何程序化重启。
这是一个高级 API,当你的应用程序中的某个组件(例如入门流程)需要确保在其生命周期内不会发生最终用户中断时非常有用; - getUpdateMetadata:检索已安装更新的元数据(如描述、强制)。
更多API说明可参考下:CodePush js api。
上述API的具体使用,可以参考下面代码的实现。
代码参考
import React, { Component } from 'react';
import { Dimensions, StyleSheet, Text, TouchableOpacity } from 'react-native';
import CodePush from 'react-native-code-push';
import ViewUtils from '../util/ViewUtil';
import NavigationBar from 'react-native-navbar-plus';
import SafeAreaViewPlus from 'react-native-safe-area-plus';
import GlobalStyles from '../res/GlobalStyles';
import NavigationUtil from '../navigator/NavigationUtil';
class App extends Component {
constructor(props) {
super(props);
this.state = { restartAllowed: true };
}
codePushStatusDidChange(syncStatus) {
switch (syncStatus) {
case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
this.setState({ syncMessage: '查询跟新包中......' });
break;
case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
this.setState({ syncMessage: '安装包下载中......' });
break;
case CodePush.SyncStatus.AWAITING_USER_ACTION:
this.setState({ syncMessage: '正在等待用户操作.' });
break;
case CodePush.SyncStatus.INSTALLING_UPDATE:
this.setState({ syncMessage: '安装跟新中......' });
break;
case CodePush.SyncStatus.UP_TO_DATE:
this.setState({ syncMessage: '已经是最新版本.', progress: false });
break;
case CodePush.SyncStatus.UPDATE_IGNORED:
this.setState({
syncMessage: '用户取消跟新.',
progress: false,
});
break;
case CodePush.SyncStatus.UPDATE_INSTALLED:
this.setState({
syncMessage: '跟新完成,正在重启',
progress: false,
});
CodePush.restartApp(true);
break;
case CodePush.SyncStatus.UNKNOWN_ERROR:
this.setState({
syncMessage: '一个未知的错误.',
progress: false,
});
break;
}
}
codePushDownloadDidProgress(progress) {
this.setState({ progress });
}
// toggleAllowRestart() {
// this.state.restartAllowed
// ? CodePush.disallowRestart()
// : CodePush.allowRestart();
// this.setState({ restartAllowed: !this.state.restartAllowed });
// }
getUpdateMetadata() {
CodePush.getUpdateMetadata(CodePush.UpdateState.RUNNING).then(
(metadata) => {
this.setState({
syncMessage: metadata
? JSON.stringify(metadata)
: '运行二进制',
progress: false,
});
},
(error) => {
this.setState({ syncMessage: 'Error: ' + error, progress: false });
},
);
}
/** Update is downloaded silently, and applied on restart (recommended) */
sync() {
CodePush.sync(
{},
this.codePushStatusDidChange.bind(this),
this.codePushDownloadDidProgress.bind(this),
);
}
/** Update pops a confirmation dialog, and then immediately reboots the app */
syncImmediate() {
CodePush.sync(
{ installMode: CodePush.InstallMode.IMMEDIATE, updateDialog: true },
this.codePushStatusDidChange.bind(this),
this.codePushDownloadDidProgress.bind(this),
);
}
// isUpdateApp() {
// CodePush.checkForUpdate()
// .then((update) => {
// if (!update) {
// this.setState({ syncMessage: 'The app is up to date!' });
// // console.log("The app is up to date!");
// } else {
// // console.log("An update is available! Should we download it?");
// this.setState({ syncMessage: 'An update is available! Should we download it?' });
// }
// });
// }
render() {
let progressView;
if (this.state.progress) {
progressView = (
<Text style={styles.messages}>
{this.state.progress.receivedBytes} /{' '}
{this.state.progress.totalBytes} 接收字节
</Text>
);
}
const { theme } = this.props.route.params;
return (
<SafeAreaViewPlus
style={GlobalStyles.root_container}
topColor={theme.themeColor}>
<NavigationBar
style={theme.styles.navBar}
leftButton={ViewUtils.getLeftBackButton(() =>
NavigationUtil.goBack(this.props.navigation),
)}
title={'版本'}
/>
<Text style={styles.welcome}>当前版本1.0.0</Text>
<TouchableOpacity onPress={this.sync.bind(this)}>
<Text style={styles.syncButton}>检测版本</Text>
</TouchableOpacity>
{/* 查询是否有可用跟新 */}
{/* <TouchableOpacity onPress={this.isUpdateApp.bind(this)}>
<Text style={styles.syncButton}>是否有可用跟新</Text>
</TouchableOpacity> */}
{/* <TouchableOpacity onPress={this.syncImmediate.bind(this)}>
<Text style={styles.syncButton}>Press for dialog-driven sync</Text>
</TouchableOpacity> */}
{progressView}
{/* <TouchableOpacity onPress={this.toggleAllowRestart.bind(this)}>
<Text style={styles.restartToggleButton}>
Restart {this.state.restartAllowed ? 'allowed' : 'forbidden'}
</Text>
</TouchableOpacity> */}
<TouchableOpacity onPress={this.getUpdateMetadata.bind(this)}>
<Text style={styles.syncButton}>跟新元数据</Text>
</TouchableOpacity>
<Text style={styles.messages}>{this.state.syncMessage || ''}</Text>
</SafeAreaViewPlus>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
margin: 30,
width: Dimensions.get('window').width - 100,
height: (365 * (Dimensions.get('window').width - 100)) / 651,
},
messages: {
marginTop: 30,
textAlign: 'center',
},
restartToggleButton: {
color: 'blue',
fontSize: 17,
},
syncButton: {
color: 'green',
fontSize: 17,
textAlign:'center'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 20,
},
});
/**
* Configured with a MANUAL check frequency for easy testing. For production apps, it is recommended to configure a
* different check frequency, such as ON_APP_START, for a 'hands-off' approach where CodePush.sync() does not
* need to be explicitly called. All options of CodePush.sync() are also available in this decorator.
*/
let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };
App = CodePush(codePushOptions)(App);
export default App;
发布CodePush更新
在RN应用的根目录下通过下面命令来发布CodePush更新:
发布更新
appcenter codepush release-react -a <ownerName>/MyApp
//如
appcenter codepush release-react -a crazycodeboy/RN2-iOS
如:
appcenter codepush release-react -a williamwook9527-gmail.com/react_native_test -d Production --t '1.0.0'
d代表发布的环境,t代表当前的app版本
- ownerName:通过appcenter login登录后返回的用户名
- MyApp:在AppCenter中注册的APP名字(Android和iOS有区分是两个APP);
查看已发布的更新
appcenter codepush deployment list -a <ownerName>/<appName>
//如
appcenter codepush deployment list -a crazycodeboy/RN2-iOS
如图所示