reactNative更新App,自定进度条

reactNative更新App,自定进度条

实现原理:获取当前App的版本号与后台存储的版本号进行比较,不相同时则需要更新App

一、下载插件

yarn add rn-app-upgrade

二、安卓配置,react-native版本0.6以上的不需要更多配置

// 低于0.6+版本
react-native link rn-app-upgrade

找到node_modules/rn-app-upgrade/android/src/main/java/com/songlcy/rnupgrade/DownloadService.java文件修改:

备注1:修改源码是因为官方没有处理网络下载慢的时候android通知栏不会通知,只有下载进度变化时通知栏才会显示

1、修改因网络慢通知栏不能及时显示

 @Override
    protected void onHandleIntent(Intent intent) {

        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mBuilder = new Builder(this, "downLoadChannelId");
            NotificationChannel channel = new NotificationChannel("downLoadChannelId", "downLoadChannel", NotificationManager.IMPORTANCE_LOW);
            mNotifyManager.createNotificationChannel(channel);
        } else {
            mBuilder = new Builder(this);
        }

        String appName = getString(getApplicationInfo().labelRes);
        int icon = getApplicationInfo().icon;

        mBuilder.setContentTitle(appName).setSmallIcon(icon);
        String urlStr = intent.getStringExtra(Constants.APK_DOWNLOAD_URL);
        InputStream in = null;
        FileOutputStream out = null;

        updateProgress(0);    /////////////////////////**源代码中增加这一句**
        try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		........

备注2:官网没有处理因网络慢下载失败的时候

2、还是在此文件中方法名为onHandleIntent的代码,修改catch中的代码

try {
            URL url = new URL(urlStr);
            HttpURLConnection urlConnection = (HttpURLConnection) 	
            .......
        } catch (Exception e) {    //下载失败的时候
            Log.e(TAG, "download apk file error");
            /////////////////////////////////////////源代码中加入下面的代码
            mBuilder.setContentText("下载失败");
            //setContentInent如果不设置在4.0+上没有问题,在4.0以下会报异常
            PendingIntent pendingintent = PendingIntent.getActivity(this, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
            mBuilder.setContentIntent(pendingintent);
            mNotifyManager.notify(NOTIFICATION_ID, mBuilder.build());
        } finally {
           .........
        }

三、IOS配置

1、将node_modules/ios_upgrade里面的文件拷贝到项目的IOS目录下,打开Xcode将这两个文件导入项目工程----->点击右键 Add filfe…
在这里插入图片描述

四、使用

1、安卓使用

import React, {Component} from 'react';
import {PermissionsAndroid,Text, View,NativeModules,DeviceEventEmitter,TouchableOpacity} from 'react-native';

///////////可通过NativeModules.upgrade获取versionName和versionCode

export default class Index extends React.Component {
    constructor(props){
        super(props);
        this.state = {
           
        }
    }
    goUserpage(){
       NativeModules.upgrade.upgrade("https://qd.myapp.com/myapp/qqteam/QQ_JS/qqlite_4.0.0.1025_537062065.apk");
        DeviceEventEmitter.addListener('LOAD_PROGRESS',(pro)=>{       //监听进度
            console.log(pro)
        })
    }
    componentDidMount(){
       this.crequestMultiplePermission()      //添加权限   安卓低版本需要手动授权
    }
    crequestMultiplePermission = async () => {     
        try {
          const permissions = [
            PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
          ];
          const granteds = await PermissionsAndroid.requestMultiple(permissions);
          if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
            this.storage = true;
          } else {
            this.storage = false;
          }
          if (this.storage) return;
        } catch (err) {
          console.log(err);
        }
      };
    render() {
        return <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
            <TouchableOpacity activeOpacity={0.5} onPress={this.goUserpage.bind(this)}>
            <Text>更新App</Text>
            </TouchableOpacity>
        </View>;
    }
}

2、ios使用

//AppId为上架后的应用的AppId可以到开发者中心中查看
 if(iOS) {
       NativeModules.upgrade.upgrade('AppId',(msg) =>{  
           if('YES' == msg) {                     
              Alert.alert('发现新版本','是否下载',
              [
                  {text:"确定", onPress:() => {
                      //跳转到APP Stroe
                       NativeModules.upgrade.openAPPStore('AppId');  
                  }},      
                  {text:"取消"}    
              ]
              );                   
           } else {  
           //    this.toast('当前为最新版本');  
           }  
       })             
   }

3、判断安卓还是ios

import {Platform} from "react-native"
if(Platform.OS === 'ios'){
	//IOS代码
}else{
	//安卓代码
}

-------大功告成啦-------

如果不想下载包或者包已发生变化,可以使用下面的代码,以下代码是包的代码,代码已经更改

一、android
将文件中android下面的rnupgrade文件拷贝到项目/android/app/src/main/java/com/包名,文件夹下面。
修改rnupgrade文件夹里面所有java文件:

package com.这里改为你的包名.rnupgrade;

2、修改项目/android/app/src/main/java/com/包名/MainApplication.java文件

import com.包名.rnupgrade.UpgradePackage;			//////增加此处
	....
   @Override
  protected List<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> packages = new PackageList(this).getPackages();
      packages.add(new UpgradePackage());           //////增加此处
      return packages;
    }
    ....

二、IOS:将ios_upgrade里面的文件拷贝到项目的IOS目录下,打开Xcode将这两个文件导入项目工程----->点击右键 Add filfe…
在这里插入图片描述

资源文件下载:点击下载

提取码:ncqj

发布了16 篇原创文章 · 获赞 14 · 访问量 1773

猜你喜欢

转载自blog.csdn.net/TanHao8/article/details/104611747