ReactNative使用codepush

本文详细介绍了如何在React Native应用中实现热更新,包括获取版本信息、手动触发更新、检查更新状态、控制应用重启以及一个完整的使用示例。通过codePush库,开发者可以轻松地在不重新发布应用的情况下推送新版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、获取版本信息

codePush.getUpdateMetadata(codePush.UpdateState.LATEST).then((update) => {
        if (update) {
          this.props.authLoadingMobx.setPackageInfo(update.appVersion+"@"+update.label);
        }else{
          this.props.authLoadingMobx.setPackageInfo('v1');
        }
      });

刚打包没有使用过热更新的时候,update为null,这里需要我们给个默认值

二、热更新

//包装方式
class MyApp extends Component<{}> {}
MyApp = codePush(MyApp);
export default MyApp;

//ES7注解
@codePush
class MyApp extends Component<{}> {}
export default MyApp;

//手动调用
codePush.sync(options: Object, syncStatusChangeCallback: function(syncStatus: Number), downloadProgressCallback: function(progress: DownloadProgress), handleBinaryVersionMismatchCallback: function(update: RemotePackage)): Promise<Number>;

三、检查更新

codePush.checkForUpdate()
.then((update) => {
    if (!update) {
        console.log("The app is up to date!");
    } else {
        console.log("An update is available! Should we download it?");
    }
});

四、允许和禁止app重启

//禁止app重启,更新完成之后将会等待重启命令
codePush.disallowRestart();
//允许app重启,如果之前没有调用禁止,这里什么都不会做
codePush.allowRestart();
//重启app,默认false,不需要更新完成也会重启,如果传true会等待更新完成
codePush.restartApp(false);
//通知app更新完成,如果是allowRestart,应用将会重启
odePush.notifyAppReady();

五、使用示例

/**
 * 热更新界面
 * 预留自动登录模式
 */
import React from "react";
import { ImageBackground, Text, StatusBar } from "react-native";
import { observer, inject } from "mobx-react";
import { createSwitchNavigator, createAppContainer } from "react-navigation";
import { AppRouter } from "./AppRouter";
import { AuthRouter } from "./AuthRouter";
import codePush from "react-native-code-push";
import { Toast } from "teaset";
import ProgressBar from "../components/ProgressBar";

type Props = {
  navigation: any
};

@inject("authLoadingMobx")
@observer
class AuthLoadingScreen extends React.Component<Props> {
  constructor(props) {
    super(props);
    // this.authAsync();
  }

  codePushStatusDidChange = (status) => {
    switch (status) {
      case codePush.SyncStatus.CHECKING_FOR_UPDATE:
        this.props.authLoadingMobx.setMsg("正在检查更新.");
        break;
      case codePush.SyncStatus.DOWNLOADING_PACKAGE:
        this.props.authLoadingMobx.setMsg("正在下载更新包.");
        this.props.authLoadingMobx.setShowProgress(true);
        break;
      case codePush.SyncStatus.INSTALLING_UPDATE:
        this.props.authLoadingMobx.setMsg("正在安装更新包.");
        break;
      case codePush.SyncStatus.UP_TO_DATE:
        this.props.authLoadingMobx.setMsg("正在更新.");
        break;
      case codePush.SyncStatus.UPDATE_INSTALLED:
        this.props.authLoadingMobx.setMsg("更新完成.");
        break;
      case codePush.SyncStatus.UPDATE_IGNORED:
        this.props.authLoadingMobx.setMsg("忽略的更新.");
        break;
      case codePush.SyncStatus.UNKNOWN_ERROR:
        this.props.authLoadingMobx.setMsg("未知错误.");
        break;
      case codePush.SyncStatus.SYNC_IN_PROGRESS:
        this.props.authLoadingMobx.setMsg("正在同步.");
        break;
      case codePush.SyncStatus.AWAITING_USER_ACTION:
        this.props.authLoadingMobx.setMsg("等待用户操作.");
        break;
    }
  };

  codePushDownloadDidProgress = (progress) => {
    this.props.authLoadingMobx.setProgress(progress.receivedBytes * 100 / progress.totalBytes);
  };

  async componentDidMount() {
    try {
      codePush.getUpdateMetadata(codePush.UpdateState.LATEST).then((update) => {
        if (update) {
          this.props.authLoadingMobx.setPackageInfo(update.appVersion+"@"+update.label);
        }else{
          this.props.authLoadingMobx.setPackageInfo('v1');
        }
      });

    } catch (e) {
      Toast.message(e);
    }
    const syncOptions = {
      updateDialog: {
        //是否显示更新描述
        appendReleaseDescription: true,
        //更新描述的前缀。 默认为"Description"
        descriptionPrefix: "更新内容:",
        //强制更新按钮文字,默认为continue
        mandatoryContinueButtonLabel: "立即更新",
        //强制更新时的信息. 默认为"An update is available that must be installed."
        mandatoryUpdateMessage: "必须更新后才能使用",
        //非强制更新时,按钮文字,默认为"ignore"
        optionalIgnoreButtonLabel: "稍后",
        //非强制更新时,确认按钮文字. 默认为"Install"
        optionalInstallButtonLabel: "后台更新",
        //非强制更新时,检查到更新的消息文本
        optionalUpdateMessage: "有新版本了,是否更新?",
        //Alert窗口的标题
        title: "更新提示"
      },
      installMode: codePush.InstallMode.IMMEDIATE
    };
    try {
      await codePush.sync(syncOptions, this.codePushStatusDidChange, this.codePushDownloadDidProgress);
    } catch (e) {
      Toast.sad(e.toString());
    }

    this.props.navigation.navigate("AuthRouter");

  }

  authAsync = async () => {
    // const userToken = await AsyncStorage.getItem('userToken');
    // this.props.navigation.navigate(userToken ? 'AppRouter' : 'AuthRouter');
  };

  render() {
    return (
      <ImageBackground style={{ justifyContent: "flex-end", alignItems: "center", width: "100%", height: "100%" }}
                       source={Images.launch}
      >
        <StatusBar barStyle={"light-content"} backgroundColor={'#fff'}/>
        <Text>{this.props.authLoadingMobx.packageInfo}</Text>
        <Text>{this.props.authLoadingMobx.progressMsg}</Text>
        {this.props.authLoadingMobx.showProgress && <ProgressBar progress={this.props.authLoadingMobx.progress}/>}
      </ImageBackground>
    );
  }
}

export const AuthLoadingRouter = createAppContainer(
  createSwitchNavigator(
    {
      AuthLoading: AuthLoadingScreen,
      AuthRouter: AuthRouter,
      AppRouter: AppRouter
    },
    {
      initialRouteName: "AuthLoading"
    }
  )
);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值