如何集成
以下內容基於RN 0.61.5版本(最新版本已經不存在本文所說的so衝突問題,官方在build.gradle中已經加上pickFirst)
在新建一個RN項目並安裝完node模塊依賴後,在根目錄執行
npm run android
即可啓動編譯並安裝到目標設備
android工程依賴的本地maven庫配置
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url("$rootDir/../node_modules/react-native/android")
}
工程依賴配置
implementation "com.facebook.react:react-native:+" // From node_modules
如果我們想開發學習ReactAndroid的源碼,希望在工程中直接配置ReactAndroid module,首先需要在Settings.gradle中配置ReactAndroid工程:
include ':ReactAndroid'
project(':ReactAndroid').projectDir = new File(
rootProject.projectDir, '../node_modules/react-native/ReactAndroid')
然後在app build.gradle中引入
//implementation "com.facebook.react:react-native:+" // From node_modules
implementation project(":ReactAndroid")
集成結束,可以開始愉快的編譯了
so衝突解決
編譯會出現如下錯誤:
* What went wrong:
Execution failed for task ':app:transformNativeLibsWithMergeJniLibsForDebug'.
> More than one file was found with OS independent path 'lib/arm64-v8a/libc++_shared.so'
說明存在so衝突了,都告訴是哪個task了,接着看下詳細的衝突信息,在app build.gradle添加如下代碼
android.applicationVariants.all{ variant ->
def targetName = variant.name.capitalize()
if (targetName == "Debug"){
tasks.findByName("transformNativeLibsWithMergeJniLibsFor${targetName}").doFirst {
inputs.files.files.each {File file ->
def match = file.path =~ "^.*/armeabi-v7a/libc\\+\\+_shared\\.so\$"
if (match.size() > 0){
println "dulpicate file path ${file.path}"
}
}
}
}
}
接着重新編譯,查看輸出信息
dulpicate file path /Users/**/.gradle/caches/transforms-2/files-2.1/594e854423337ea0f46904d533b98b3f/jni/armeabi-v7a/libc++_shared.so
dulpicate file path /Users/**/mywork/rn/AwesomeProject/node_modules/react-native/ReactAndroid/build/intermediates/intermediate-jars/debug/jni/armeabi-v7a/libc++_shared.so
可以看出,ReactAndroid和594e854423337ea0f46904d533b98b3f這個maven庫都包含該so,導致衝突了
接着cd到594e854423337ea0f46904d533b98b3f對應的目錄,查看AndroidManifest文件信息,可以看到包名爲
com.facebook.flipper
這個庫是在ReactAndroid引入的,flipper主要是用於開發調試用的,所以只在debug階段引入
debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.yoga'
exclude group:'com.facebook.flipper', module: 'fbjni'
exclude group:'com.facebook.litho', module: 'litho-annotations'
}
解決的方式有兩個
packagingOptions {
pickFirst '**/libc++_shared.so'
}
//或者
android.applicationVariants.all{ variant ->
def targetName = variant.name.capitalize()
if (targetName == "Debug"){
tasks.findByName("transformNativeLibsWithMergeJniLibsFor${targetName}").doFirst {
inputs.files.files.each {File file ->
def match = file.path =~ "^.*\\.gradle/caches.*libc\\+\\+_shared\\.so\$"
if (match.size() > 0){
file.delete()
}
}
}
}
}
疑問
爲什麼都通過maven庫方式引入的時候,不會有衝突,但是改成工程子project引入後,就會有衝突了呢?我覺得這說明gradle編譯時,對於maven庫之間的衝突和子project與maven庫之間的衝突,在merge時,校驗的嚴格程度是不一樣的