react-native使用react-native-code-push到安卓Production中

提示:当前环境较新为
"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

然后会打开一个浏览器界面,如果没有账号创建一个账号并登录,之后会出现:

Authentication-succeeded.png

复制上面的token。

如果没有出现可以重新执行下上面命令。

之后在终端输入Access code,然后会得到一个登录用户名:

appcenter-login.png

参照: Use CodePush to update your app live

获取部署秘钥

查看你的AppCenter中有哪些应用:

appcenter apps list

如果没有,则需要在AppCenter上创建一个RN应用:

appcenter-create-app.png

注意:安卓的话请在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')

如图所示:

微信图片_20230204101615.png

在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"
...

如图所示
QQ截图20230204103147.png

更新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里面的去掉


QQ截图20230204102501.png

并且对于 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>"'
            ...
        }
    }
    ...
}

如图所示
微信图片_20230204110413.png

修改app版本号versionName:'1.0'为versionName:'1.0.0' 因为微软上的appcenter里面的app Version要和我们build.gradle的一致,不然可能出现问题


QQ截图20230204120804.png

React Native < v0.60版本的,请按照下面参考官方的文档进行相关配置

参考

Android Setup
安卓生产环境配置

在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
如图所示


QQ截图20230204120000.png

参考

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,302评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,563评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,433评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,628评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,467评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,354评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,777评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,419评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,725评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,768评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,543评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,387评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,794评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,032评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,305评论 1 252
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,741评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,946评论 2 336

推荐阅读更多精彩内容