提示:當(dāng)前環(huán)境較新為
"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注冊(cè)
安裝appcenter-cli
npm install -g appcenter-cli
登錄AppCenter
appcenter login
然后會(huì)打開(kāi)一個(gè)瀏覽器界面灭翔,如果沒(méi)有賬號(hào)創(chuàng)建一個(gè)賬號(hào)并登錄询张,之后會(huì)出現(xiàn):
復(fù)制上面的token伟葫。
如果沒(méi)有出現(xiàn)可以重新執(zhí)行下上面命令篡石。
之后在終端輸入Access code怖现,然后會(huì)得到一個(gè)登錄用戶名:
獲取部署秘鑰
查看你的AppCenter中有哪些應(yīng)用:
appcenter apps list
如果沒(méi)有,則需要在AppCenter上創(chuàng)建一個(gè)RN應(yīng)用:
注意:安卓的話請(qǐng)?jiān)趏s中選擇Android
為應(yīng)用創(chuàng)建部署秘鑰:
appcenter codepush deployment add -a crazycodeboy/RN2-Android Staging
appcenter codepush deployment add -a crazycodeboy/RN2-iOS Staging
注意:默認(rèn)添加的項(xiàng)目就是Staging 也可以改成其他名稱(chēng)Production(生產(chǎn)環(huán)境)
查看應(yīng)用的部署秘鑰:
appcenter codepush deployment list -a crazycodeboy/RN2-Android -k
至此误续,使用CodePush前的準(zhǔn)備已經(jīng)完成了感局,接下來(lái)讓我們一起在項(xiàng)目中集成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文件添加為下面的附加構(gòu)建任務(wù)定義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中重寫(xiě)getJSBundleFile并返回CodePush.getJSBundleFile():
...
// 1. 導(dǎo)入CodePush.
import com.microsoft.codepush.react.CodePush;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
...
// 2. 重寫(xiě)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標(biāo)簽中的DeploymentKey改為秘鑰,而非string中name的DeploymentKey)
注意如果是打包release版本到Production的話,需要把strings.xml里面的去掉
并且對(duì)于 React Native >= v0.60
1.打開(kāi)項(xiàng)目的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版本號(hào)versionName:'1.0'為versionName:'1.0.0' 因?yàn)槲④浬系腶ppcenter里面的app Version要和我們build.gradle的一致,不然可能出現(xiàn)問(wèn)題
React Native < v0.60版本的,請(qǐng)按照下面參考官方的文檔進(jìn)行相關(guān)配置
參考
Android Setup
安卓生產(chǎn)環(huán)境配置
在JS中使用CodePush
在JS文件中導(dǎo)入CodePush:
安裝
npm i react-native-code-push --save
import CodePush from 'react-native-code-push';
API說(shuō)明
CodePush支持的常見(jiàn)API說(shuō)明:
- sync:允許檢查更新统屈、下載和安裝胚吁,只需一個(gè)電話。除非您需要自定義 UI 和/或行為愁憔,否則我們建議大多數(shù)開(kāi)發(fā)人員在將 CodePush 集成到他們的應(yīng)用程序中時(shí)使用此方法腕扶;
- allowRestart:重新允許因安裝更新而發(fā)生程序化重啟,并且可選地惩淳,如果掛起的更新試圖在不允許重啟時(shí)重啟應(yīng)用程序蕉毯,則立即重啟應(yīng)用程序。這是一個(gè)高級(jí) API思犁,僅當(dāng)您的應(yīng)用程序通過(guò) disallowRestart 方法明確禁止重新啟動(dòng)時(shí)才需要代虾。
- checkForUpdate:詢問(wèn) CodePush 服務(wù)配置的應(yīng)用程序部署是否有可用更新。
- disallowRestart:暫時(shí)禁止因安裝 CodePush 更新而發(fā)生任何程序化重啟激蹲。
這是一個(gè)高級(jí) API棉磨,當(dāng)你的應(yīng)用程序中的某個(gè)組件(例如入門(mén)流程)需要確保在其生命周期內(nèi)不會(huì)發(fā)生最終用戶中斷時(shí)非常有用; - getUpdateMetadata:檢索已安裝更新的元數(shù)據(jù)(如描述学辱、強(qiáng)制)乘瓤。
更多API說(shuō)明可參考下:CodePush js api。
上述API的具體使用策泣,可以參考下面代碼的實(shí)現(xiàn)衙傀。
代碼參考
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: '已經(jīng)是最新版本.', 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: '一個(gè)未知的錯(cuò)誤.',
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)
: '運(yùn)行二進(jìn)制',
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} 接收字節(jié)
</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}>當(dāng)前版本1.0.0</Text>
<TouchableOpacity onPress={this.sync.bind(this)}>
<Text style={styles.syncButton}>檢測(cè)版本</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}>跟新元數(shù)據(jù)</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;
發(fā)布CodePush更新
在RN應(yīng)用的根目錄下通過(guò)下面命令來(lái)發(fā)布CodePush更新:
發(fā)布更新
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代表發(fā)布的環(huán)境,t代表當(dāng)前的app版本
- ownerName:通過(guò)appcenter login登錄后返回的用戶名
- MyApp:在AppCenter中注冊(cè)的APP名字(Android和iOS有區(qū)分是兩個(gè)APP);
查看已發(fā)布的更新
appcenter codepush deployment list -a <ownerName>/<appName>
//如
appcenter codepush deployment list -a crazycodeboy/RN2-iOS
如圖所示