Android 原生项目或 Flutter 项目接入 ReactNative 总结

背景

为了支持容器化多样性,需要支持 WebView、Flutter、ReactNative 等,我们现需要接入 ReactNative ,达到动态下发 react 的 bundle.js 文件来动态更新功能。

ReactNative 接入文档

ReactNative 项目架构

image.png
官方文档推荐接入方式
  1. 安装 NPM 依赖,会产生node_modules文件夹
  2. 将 React Native 添加到应用中,配置相应的依赖
  3. 将现有的 Android 应用复制到 android 的目录下

Flutter项目架构

image.png

现有项目接入问题

问题一

官方未明确给出现有成熟项目如何接入 ReactNative,只给出了将现有项目拷贝到 ReactNative 的文档,而不是将 ReactNative 以 第三方库接入现有项目。

问题二

按照官方文档进行项目配置时,在编译阶段会报项目的 java toolchain 兼容性使用问题


image.png

问题三

按照网上找到的其他方式接入时,报libc++_shared.so和libfbjni.so文件冲突

接入方式
api  "com.facebook.react:react-native:+"

api "org.webkit:android-jsc:+"

引用本地 node_modules中react-native/android文件


image.png

image.png

问题四

在排除冲突的 so 文件后,在跳转 ReactNative 类时,进行如下报错:


image.png

image.png

接入步骤

步骤一
在项目的根目录下执行如下命令

curl -O https://raw.githubusercontent.com/react-native-community/template/refs/heads/0.75-stable/template/package.json

或者拷贝如下文件到根目录
react-native.config.js

module.exports = {
  project: {
    android: {
      sourceDir: './',
    },
  },
};

package.json

{
  "name": "HYTestDemo",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "lint": "eslint .",
    "start": "react-native start",
    "test": "jest"
  },
  "dependencies": {
    "react": "^18.3.1",
    "react-native": "0.76.3"
  },
  "devDependencies": {
    "@babel/core": "^7.25.2",
    "@babel/preset-env": "^7.25.3",
    "@babel/runtime": "^7.25.0",
    "@react-native-community/cli": "15.0.1",
    "@react-native-community/cli-platform-android": "15.0.1",
    "@react-native-community/cli-platform-ios": "15.0.1",
    "@react-native/babel-preset": "0.76.3",
    "@react-native/eslint-config": "0.76.3",
    "@react-native/metro-config": "0.76.3",
    "@react-native/typescript-config": "0.76.3",
    "@types/react": "^18.2.6",
    "@types/react-test-renderer": "^18.0.0",
    "babel-jest": "^29.6.3",
    "eslint": "^8.19.0",
    "jest": "^29.6.3",
    "prettier": "2.8.8",
    "react-test-renderer": "18.3.1",
    "typescript": "5.0.4"
  },
  "engines": {
    "node": ">=18"
  },
  "main": "index.js",
  "license": "MIT"
}

metro.config.js

const {getDefaultConfig, mergeConfig} = require('@react-native/metro-config');

/**
 * Metro configuration
 * https://reactnative.dev/docs/metro
 *
 * @type {import('metro-config').MetroConfig}
 */
const config = {};

module.exports = mergeConfig(getDefaultConfig(__dirname), config);

  1. 执行 yarn init
  2. 执行 yarn add react
    执行完上面的命令后,会生成 node_modules文件夹,如图


    image.png

步骤二

在 Android 根目录下 settings.gradle文件中进行配置 react_native加载路径

//这里设置react-native加载地址
apply from: file("./node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesSettingsGradle(settings)
 
include ':app'
//下面是 Flutter 插件设置
def flutterProjectRoot = rootProject.projectDir.parentFile.toPath()
 
def plugins = new Properties()
def pluginsFile = new File(flutterProjectRoot.toFile(), '.flutter-plugins')
if (pluginsFile.exists()) {
    pluginsFile.withReader('UTF-8') { reader -> plugins.load(reader) }
}
 
plugins.each { name, path ->
    def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile()
    include ":$name"
    project(":$name").projectDir = pluginDirectory
}

步骤三

在 Android 根目录下的build.gradle文件中进行配置加载 react的远程下载规则


buildscript {
    ext.kotlin_version = '1.8.0'
    repositories {
        //配置过滤规则
        def filterReactGroup = { repo, isInclude ->
            def reactGroups = ["com\\.getui\\..*", "com\\.huawei\\..*","com\\.assist-v3\\.*","com\\.hihonor\\..*","com\\.tencent\\..*"]
            repo.content {
                reactGroups.each {
                    if (isInclude) includeGroupByRegex it
                    else excludeGroupByRegex it
                }
            }
        }
        def includeJdGroup = { filterReactGroup(it, true) }
        def excludeJdGroup = { filterReactGroup(it, false) }
        //下载 react 依赖地址
        maven {
            url "$rootDir/node_modules/react-native/android"
            filterReactGroup(it)
        }
        //下载 react 依赖地址
        maven {
            url("$rootDir/node_modules/jsc-android/dist")
            filterReactGroup(it)
        }
 
        maven {
            url 'https://maven.aliyun.com/nexus/content/groups/public/'
        }
        maven {
            url "https://mvn.getui.com/nexus/content/repositories/releases/"
        }
        maven {
            url 'https://maven.aliyun.com/repository/google'
        }
        maven {
            setUrl("https://maven.aliyun.com/repository/public")
        }
        maven {
            url 'https://maven.aliyun.com/repository/jcenter'
        }
        maven { url 'https://developer.huawei.com/repo/' }
        maven { url 'https://developer.hihonor.com/repo/' }
        maven { url "https://jitpack.io" }
//        腾讯地图相关
        maven {
            url "https://mirrors.tencent.com/repository/maven/tencent_public/"
        }
        maven {
            url "https://mirrors.tencent.com/repository/maven/tencent_public_snapshots"
        }
        maven {
            url "https://oss.sonatype.org/content/groups/public"
        }
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
        maven {
            url "https://oss.sonatype.org/content/repositories/staging/"
        }
        google()
        mavenCentral()
    }
 
    dependencies {
        classpath 'com.android.tools.build:gradle:7.2.2'
        classpath 'com.huawei.agconnect:agcp:1.7.2.300'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
    }
}
 
allprojects {
    def filterReactGroup = { repo, isInclude ->
        def reactGroups = ["com\\.getui\\..*", "com\\.huawei\\..*","com\\.assist-v3\\.*","com\\.hihonor\\..*","com\\.tencent\\..*"]
        repo.content {
            reactGroups.each {
                if (isInclude) includeGroupByRegex it
                else excludeGroupByRegex it
            }
        }
    }
    def includeJdGroup = { filterReactGroup(it, true) }
    def excludeJdGroup = { filterReactGroup(it, false) }
    repositories {
        maven {
            url "$rootDir/node_modules/react-native/android"
            filterReactGroup(it)
        }
        maven {
            url("$rootDir/node_modules/jsc-android/dist")
            filterReactGroup(it)
        }
 
        maven {
            url 'https://maven.aliyun.com/nexus/content/groups/public/'
        }
        maven {
            url "https://mvn.getui.com/nexus/content/repositories/releases/"
        }
        maven {
            url 'https://maven.aliyun.com/repository/google'
        }
        maven {
            setUrl("https://maven.aliyun.com/repository/public")
        }
        maven {
            url 'https://maven.aliyun.com/repository/jcenter'
        }
        maven { url 'https://developer.huawei.com/repo/' }
        maven { url 'https://developer.hihonor.com/repo/' }
        maven { url "https://jitpack.io" }
//        腾讯地图相关
        maven {
            url "https://mirrors.tencent.com/repository/maven/tencent_public/"
        }
        maven {
            url "https://mirrors.tencent.com/repository/maven/tencent_public_snapshots"
        }
        maven {
            url "https://oss.sonatype.org/content/groups/public"
        }
        maven {
            url "https://oss.sonatype.org/content/repositories/snapshots/"
        }
        maven {
            url "https://oss.sonatype.org/content/repositories/staging/"
        }
        google()
        mavenCentral()
    }
}
 
rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}
 
tasks.register("clean", Delete) {
    delete rootProject.buildDir
}

步骤四

在 app (运行应用 module )目录下的build.gradle文件中配置依赖

plugins {
    id "com.android.application"
    id "kotlin-android"
}
 
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new FileNotFoundException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}
 
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
//配置 react 插件加载路径
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesAppBuildGradle(project)
android {
    namespace "com.example.flutter_test_rn_project"
    compileSdkVersion flutter.compileSdkVersion
    ndkVersion flutter.ndkVersion
 
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
 
    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.flutter_test_rn_project"
        // You can update the following values to match your application needs.
        // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-gradle-build-configuration.
        minSdkVersion flutter.minSdkVersion
        targetSdkVersion flutter.targetSdkVersion
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        //这里一定要配置
        multiDexEnabled true
    }
 
    buildTypes {
        debug {
            minifyEnabled false
            zipAlignEnabled true
            //这里必须设置为 false
            shrinkResources false
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            ndk {
                //设置支持的SO库架构
                abiFilters 'arm64-v8a'//debug模式flutter运行需要这样设置
 
            }
        }
        release {
            minifyEnabled false
            zipAlignEnabled true
            shrinkResources false
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            ndk {
                //设置支持的SO库架构
                abiFilters 'arm64-v8a'//debug模式flutter运行需要这样设置
 
            }
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    packagingOptions {
        doNotStrip "*/armeabi-v7a/*.so"
        doNotStrip "*/arm64-v8a/*.so"
        //排除libc++_shared.so文件冲突,选择第一个libc++_shared.so文件打包
        pickFirst '**/libc++_shared.so'
        //排除libfbjni.so文件冲突,选择第一个libfbjni.so文件打包
        pickFirst '**/libfbjni.so'
        exclude 'META-INF/com.android.tools/proguard/coroutines.pro'
    }
}
dependencies {
    implementation 'androidx.multidex:multidex:2.0.1'
    api "com.facebook.react:react-native:+"
    api "org.webkit:android-jsc:+"
    //hermes 解决lib so 缺失
    api 'com.facebook.react:hermes-android:0.76.3'
}
flutter {
    source '../..'
}

步骤五

在配置完成后,需要在AndroidManifest.xml中配置 application 类,如图:


image.png

步骤六

需要在AndroidManifest.xml中添加自己要启动的 react-native 类,如图


image.png

步骤七

创建 MyApplication 类,代码如下:

package com.example.flutter_test_rn_project;
 
import android.app.Application;
import android.content.Context;
 
import androidx.annotation.NonNull;
import androidx.multidex.MultiDex;
 
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.defaults.DefaultReactNativeHost;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
 
import java.util.ArrayList;
import java.util.List;
 
public class MyApplication extends Application implements ReactApplication {
 
    private static Context context;
    static private MyApplication myApplication;
 
    public static Application getInstance() {
        return myApplication;
    }
 
    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();
        myApplication = this;
    }
 
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
        //初始化 SoLoader
        SoLoader.init(this, false);
    }
 
    /**
     * 获取上下文对象
     *
     * @return context
     */
    public static Context getContext() {
        return context;
    }
 
    private final ReactNativeHost mReactNativeHost = new DefaultReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return false;
        }
 
        @Override
        protected List<ReactPackage> getPackages() {
            //配置要加载的 react 的 package
//            List<ReactPackage> packages = new PackageList(this).getPackages();
            List<ReactPackage> packages = new ArrayList<>();
            packages.add(new MainReactPackage());
            // Packages that cannot be autolinked yet can be added manually here
            return packages;
        }
    };
 
    @NonNull
    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }
}

步骤八

在 MyReactActivity页面中需要继承ReactActivity,代码如下:

import android.os.Bundle;
 
import androidx.annotation.Nullable;
 
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.shell.MainReactPackage;
 
/**
 * Description:
 * Author: chengfengli
 * Date: 2024/11/27 14:30
 */
public class MyReactActivity extends ReactActivity {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        SoLoader.init(this, false);
        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                //设置加载 react 包的名称,在 assets 文件中
                .setBundleAssetName("index.android.bundle")
                .addPackage(new MainReactPackage())
                .setJSMainModulePath("index.android")
                .setUseDeveloperSupport(false)
                .setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "HYTestDemo", null);
        setContentView(mReactRootView);
    }
 
    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }
     
    //要加载的组件名,与 React 的工程名保持一致
    @Nullable
    @Override
    protected String getMainComponentName() {
        return "HYTestDemo";
    }
}
image.png

image.png

image.png

步骤九

ReactNative项目打包出 bundle 包的命令如下:

npx react-native bundle --platform android --dev false --entry-file index.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res/

目前在 Android10 及以下手机会崩溃,暂时无法修复

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

推荐阅读更多精彩内容