Android 原生項(xiàng)目或 Flutter 項(xiàng)目接入 ReactNative 總結(jié)

背景

為了支持容器化多樣性讨便,需要支持 WebView带迟、Flutter爬立、ReactNative 等命锄,我們現(xiàn)需要接入 ReactNative 堰乔,達(dá)到動(dòng)態(tài)下發(fā) react 的 bundle.js 文件來動(dòng)態(tài)更新功能。

ReactNative 接入文檔

ReactNative 項(xiàng)目架構(gòu)

image.png
官方文檔推薦接入方式
  1. 安裝 NPM 依賴脐恩,會(huì)產(chǎn)生node_modules文件夾
  2. 將 React Native 添加到應(yīng)用中镐侯,配置相應(yīng)的依賴
  3. 將現(xiàn)有的 Android 應(yīng)用復(fù)制到 android 的目錄下

Flutter項(xiàng)目架構(gòu)

image.png

現(xiàn)有項(xiàng)目接入問題

問題一

官方未明確給出現(xiàn)有成熟項(xiàng)目如何接入 ReactNative,只給出了將現(xiàn)有項(xiàng)目拷貝到 ReactNative 的文檔驶冒,而不是將 ReactNative 以 第三方庫(kù)接入現(xiàn)有項(xiàng)目苟翻。

問題二

按照官方文檔進(jìn)行項(xiàng)目配置時(shí),在編譯階段會(huì)報(bào)項(xiàng)目的 java toolchain 兼容性使用問題


image.png

問題三

按照網(wǎng)上找到的其他方式接入時(shí)骗污,報(bào)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 文件后崇猫,在跳轉(zhuǎn) ReactNative 類時(shí),進(jìn)行如下報(bào)錯(cuò):


image.png

image.png

接入步驟

步驟一
在項(xiàng)目的根目錄下執(zhí)行如下命令

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. 執(zhí)行 yarn init
  2. 執(zhí)行 yarn add react
    執(zhí)行完上面的命令后需忿,會(huì)生成 node_modules文件夾诅炉,如圖


    image.png

步驟二

在 Android 根目錄下 settings.gradle文件中進(jìn)行配置 react_native加載路徑

//這里設(shè)置react-native加載地址
apply from: file("./node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesSettingsGradle(settings)
 
include ':app'
//下面是 Flutter 插件設(shè)置
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文件中進(jìn)行配置加載 react的遠(yuǎn)程下載規(guī)則


buildscript {
    ext.kotlin_version = '1.8.0'
    repositories {
        //配置過濾規(guī)則
        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" }
//        騰訊地圖相關(guān)
        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" }
//        騰訊地圖相關(guān)
        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 (運(yùn)行應(yīng)用 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
            //這里必須設(shè)置為 false
            shrinkResources false
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            ndk {
                //設(shè)置支持的SO庫(kù)架構(gòu)
                abiFilters 'arm64-v8a'//debug模式flutter運(yùn)行需要這樣設(shè)置
 
            }
        }
        release {
            minifyEnabled false
            zipAlignEnabled true
            shrinkResources false
            signingConfig signingConfigs.debug
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            ndk {
                //設(shè)置支持的SO庫(kù)架構(gòu)
                abiFilters 'arm64-v8a'//debug模式flutter運(yùn)行需要這樣設(shè)置
 
            }
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    packagingOptions {
        doNotStrip "*/armeabi-v7a/*.so"
        doNotStrip "*/arm64-v8a/*.so"
        //排除libc++_shared.so文件沖突蜡歹,選擇第一個(gè)libc++_shared.so文件打包
        pickFirst '**/libc++_shared.so'
        //排除libfbjni.so文件沖突,選擇第一個(gè)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中添加自己要啟動(dòng)的 react-native 類,如圖


image.png

步驟七

創(chuàng)建 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);
    }
 
    /**
     * 獲取上下文對(duì)象
     *
     * @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頁(yè)面中需要繼承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())
                //設(shè)置加載 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項(xiàng)目打包出 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 及以下手機(jī)會(huì)崩潰铛漓,暫時(shí)無(wú)法修復(fù)

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市鲫构,隨后出現(xiàn)的幾起案子浓恶,更是在濱河造成了極大的恐慌,老刑警劉巖结笨,帶你破解...
    沈念sama閱讀 218,204評(píng)論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件包晰,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡炕吸,警方通過查閱死者的電腦和手機(jī)伐憾,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,091評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來赫模,“玉大人树肃,你說我怎么就攤上這事∑俾蓿” “怎么了胸嘴?”我有些...
    開封第一講書人閱讀 164,548評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)斩祭。 經(jīng)常有香客問我劣像,道長(zhǎng),這世上最難降的妖魔是什么摧玫? 我笑而不...
    開封第一講書人閱讀 58,657評(píng)論 1 293
  • 正文 為了忘掉前任耳奕,我火速辦了婚禮,結(jié)果婚禮上诬像,老公的妹妹穿的比我還像新娘屋群。我一直安慰自己,他們只是感情好坏挠,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,689評(píng)論 6 392
  • 文/花漫 我一把揭開白布芍躏。 她就那樣靜靜地躺著,像睡著了一般癞揉。 火紅的嫁衣襯著肌膚如雪纸肉。 梳的紋絲不亂的頭發(fā)上溺欧,一...
    開封第一講書人閱讀 51,554評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音柏肪,去河邊找鬼姐刁。 笑死,一個(gè)胖子當(dāng)著我的面吹牛烦味,可吹牛的內(nèi)容都是我干的聂使。 我是一名探鬼主播,決...
    沈念sama閱讀 40,302評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼谬俄,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼柏靶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起溃论,我...
    開封第一講書人閱讀 39,216評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤屎蜓,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后钥勋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體炬转,經(jīng)...
    沈念sama閱讀 45,661評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,851評(píng)論 3 336
  • 正文 我和宋清朗相戀三年算灸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了扼劈。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,977評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡菲驴,死狀恐怖荐吵,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情赊瞬,我是刑警寧澤先煎,帶...
    沈念sama閱讀 35,697評(píng)論 5 347
  • 正文 年R本政府宣布,位于F島的核電站森逮,受9級(jí)特大地震影響榨婆,放射性物質(zhì)發(fā)生泄漏磁携。R本人自食惡果不足惜褒侧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,306評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望谊迄。 院中可真熱鬧闷供,春花似錦、人聲如沸统诺。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,898評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)粮呢。三九已至婿失,卻和暖如春钞艇,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背豪硅。 一陣腳步聲響...
    開封第一講書人閱讀 33,019評(píng)論 1 270
  • 我被黑心中介騙來泰國(guó)打工哩照, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人懒浮。 一個(gè)月前我還...
    沈念sama閱讀 48,138評(píng)論 3 370
  • 正文 我出身青樓飘弧,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親砚著。 傳聞我的和親對(duì)象是個(gè)殘疾皇子次伶,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,927評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容