reactnative实现app应用内更新

最近用reactnative写app,需要有app升级功能。查看资料,很多都是热更新,需要在CodePush等框架注册账号,然后传包到他们系统,下载次数有限制。并不符合要求。
于是使用rn-fetch-blob下载安装包在运行替换。

安装 rn-fetch-blob

npm install rn-fetch-blob

or

yarn add rn-fetch-blob

安装 react-native-device-info

安装react-native-device-info获取当前版本号

npm install react-native-device-info

or

yarn add react-native-device-info

使用

import RNFetchBlob from 'rn-fetch-blob';
import DeviceInfo from 'react-native-device-info';

const Update = () => {
if(DeviceInfo.getVersion !== newVersion){
  const android = RNFetchBlob.android;
  //配置手机系统通知栏下载文件通知,下载成功后点击通知可运行apk文件
  RNFetchBlob.config({
    addAndroidDownloads: {
      useDownloadManager: true,
      title: '更新app',
      description: 'An APK that will be installed',
      mime: 'application/vnd.android.package-archive',
      path: `${RNFetchBlob.fs.dirs.DownloadDir}/update.apk`,
      mediaScannable: true,
      notification: true
    }
  }).fetch(
    'GET',
     url, //apk下载地址
  ).progress({ interval: 250 }, (received, total) => {
    setpercent(received / total)// 下载进度
}).then(res => {
  setpercent(100)
    //下载成功后自动打开安装已下载apk文件
    console.log('要运行咯。。。。。');
    android.actionViewIntent(
      res.path(),
      'application/vnd.android.package-archive'
    );
  }).catch((err) => {
    console.log('err',err);
    
  })
}
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐