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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章