背景
为了支持容器化多样性,需要支持 WebView、Flutter、ReactNative 等,我们现需要接入 ReactNative ,达到动态下发 react 的 bundle.js 文件来动态更新功能。
ReactNative 项目架构
官方文档推荐接入方式
- 安装 NPM 依赖,会产生node_modules文件夹
- 将 React Native 添加到应用中,配置相应的依赖
- 将现有的 Android 应用复制到 android 的目录下
Flutter项目架构
现有项目接入问题
问题一
官方未明确给出现有成熟项目如何接入 ReactNative,只给出了将现有项目拷贝到 ReactNative 的文档,而不是将 ReactNative 以 第三方库接入现有项目。
问题二
按照官方文档进行项目配置时,在编译阶段会报项目的 java toolchain 兼容性使用问题
问题三
按照网上找到的其他方式接入时,报libc++_shared.so和libfbjni.so文件冲突
接入方式
api "com.facebook.react:react-native:+"
api "org.webkit:android-jsc:+"
引用本地 node_modules中react-native/android文件
问题四
在排除冲突的 so 文件后,在跳转 ReactNative 类时,进行如下报错:
接入步骤
步骤一
在项目的根目录下执行如下命令
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);
- 执行 yarn init
-
执行 yarn add react
执行完上面的命令后,会生成 node_modules文件夹,如图
步骤二
在 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 类,如图:
步骤六
需要在AndroidManifest.xml中添加自己要启动的 react-native 类,如图
步骤七
创建 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";
}
}
步骤九
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 及以下手机会崩溃,暂时无法修复