目錄
一、前言
二、需要了解的幾個類
三珠叔、JavaModule注冊流程參考資料
一蝎宇、前言
JavaModule是React Native提供給我們封裝原生模塊的能力,它可以讓你復用一些原生的代碼祷安,又或者如果React Native還不支持某個你需要的原生特性姥芥,可以自己實現(xiàn)該特性的封裝。官網(wǎng)文檔介紹了如何封裝JavaModule的過程汇鞭,這里不再啰嗦凉唐,本文將會更深入一層Java層源碼,看下它是如何注冊并提供給JS端調(diào)用的虱咧,以及需要注意的一些問題熊榛。
二锚国、需要了解的幾個類
-
ReactContext
繼承于ContextWrapper腕巡,React Native應用的上下文,通過getContext()獲得血筑,它和Android中的Context是同一個概念
-
ReactRootView
繼承于FragmeLayout绘沉,主要負責native端事件的監(jiān)聽(鍵盤事件、tounch事件)豺总,并將結果傳遞給js端车伞,以及負責頁面元素的繪制
-
ReactInstanceManager
React Native應用的總的管理類,創(chuàng)建ReactContext喻喳、CatalystInstance實體另玖,解析ReactPackage生成映射表,并且配合ReactRootView管理View的創(chuàng)建與生命周期等功能
-
CatalystInstance
通信大管家表伦,負責Java層谦去、C++層、JS層三端通信與協(xié)調(diào)蹦哼,它的實現(xiàn)類是CatalystInstanceImpl
-
NativeModuleRegistry
JavaModule注冊表鳄哭,負責管理和查找JavaModule
-
ReactPackage
定義原生模塊和原生組件必須繼承的一個類,提供NativeModule和ViewManager列表纲熏,其實ViewManager也是NativeModule子類妆丘,但是它們的行為是不一樣的。
三局劲、JavaModule注冊流程
首先我們要明白React Native本質(zhì)上是一個View勺拣,它通過ReactInstanceManager進行一系列的管理,也是我們跟它打交道最多的鱼填,如果我們直接創(chuàng)建一個ReactNative項目宣脉,在它的Android目錄下并不能直接找到ReactInstanceManager這個類剔氏,而是通過ReactNativeHost簡化了很多初始化的事情塑猖,下面先來看下它的代碼:
ReactNativeHost.java
public abstract class ReactNativeHost {
private final Application mApplication;
private @Nullable ReactInstanceManager mReactInstanceManager;
......
protected ReactInstanceManager createReactInstanceManager() {
ReactInstanceManagerBuilder builder = ReactInstanceManager.builder()
.setApplication(mApplication)
.setJSMainModulePath(getJSMainModuleName())
.setUseDeveloperSupport(getUseDeveloperSupport())
.setRedBoxHandler(getRedBoxHandler())
.setJavaScriptExecutorFactory(getJavaScriptExecutorFactory())
.setUIImplementationProvider(getUIImplementationProvider())
.setInitialLifecycleState(LifecycleState.BEFORE_CREATE);
for (ReactPackage reactPackage : getPackages()) {
builder.addPackage(reactPackage);
}
String jsBundleFile = getJSBundleFile();
if (jsBundleFile != null) {
builder.setJSBundleFile(jsBundleFile);
} else {
builder.setBundleAssetName(Assertions.assertNotNull(getBundleAssetName()));
}
return builder.build();
}
/**
* Returns a list of {@link ReactPackage} used by the app.
* You'll most likely want to return at least the {@code MainReactPackage}.
* If your app uses additional views or modules besides the default ones,
* you'll want to include more packages here.
*/
protected abstract List<ReactPackage> getPackages();
......
}
ReactNativeHost主要是負責ReactInstanceManager的實例創(chuàng)建竹祷,從它的createReactInstanceManager()
方法可以看出構建者ReactInstanceManagerBuilder將ReactInstanceManager的構建與表示進行了分離,其中的getPackages()
方法就是我們注冊封裝原生JavaModule的地方羊苟,并在builder中通過for循環(huán)將packagelist逐個add進去塑陵,進一步跟進build()
方法,會發(fā)現(xiàn)它調(diào)用了ReactInstanceManager的構造方法蜡励,參數(shù)有點多令花,但總得來說是把packages放進了ReactInstanceManager的成員變量mPackages
。
那僅僅是把它放進mPackages
成員變量就結束了凉倚?沒有其他操作兼都?別急,我們還要從ReactNative的啟動流程講起稽寒,這里以ReactActivityDelegate這個代理類為例扮碧,在它的onCreate方法中有一段邏輯loadApp邏輯:
protected void loadApp(String appKey) {
if (mReactRootView != null) {
throw new IllegalStateException("Cannot loadApp while app is already running.");
}
mReactRootView = createRootView();
mReactRootView.startReactApplication(
getReactNativeHost().getReactInstanceManager(),
appKey,
getLaunchOptions());
getPlainActivity().setContentView(mReactRootView);
}
- 創(chuàng)建一個ReactRootView
- 獲取ReactInstanceManager實例
- ReactRootView#startReactApplication()
- 給當前Activity設置setContentView()
ReactRootView.java
public class ReactRootView extends SizeMonitoringFrameLayout
implements RootView, MeasureSpecProvider{
......
public void startReactApplication(
ReactInstanceManager reactInstanceManager,
String moduleName,
@Nullable Bundle initialProperties) {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication");
try {
UiThreadUtil.assertOnUiThread();
Assertions.assertCondition(
mReactInstanceManager == null,
"This root view has already been attached to a catalyst instance manager");
mReactInstanceManager = reactInstanceManager;
mJSModuleName = moduleName;
mAppProperties = initialProperties;
if (!mReactInstanceManager.hasStartedCreatingInitialContext()) {
mReactInstanceManager.createReactContextInBackground();
}
attachToReactInstanceManager();
} finally {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
......
}
在startReactApplication()
方法中保存相應的參數(shù)外,還有重要的一點杏糙,如果是第一次啟動慎王,hasStartedCreatingInitialContext()
肯定是false的,那么就會調(diào)用ReactInstanceManager#createReactContextInBackground()方法宏侍,進行一系列ReactContext的初始化赖淤,可以推測我們的mPackage也是在此刻注冊進去的,其內(nèi)部一系列調(diào)用鏈也表明最終會進入ReactInstanceManager#createReactContext()方法:
private ReactApplicationContext createReactContext(
JavaScriptExecutor jsExecutor,
JSBundleLoader jsBundleLoader) {
Log.d(ReactConstants.TAG, "ReactInstanceManager.createReactContext()");
ReactMarker.logMarker(CREATE_REACT_CONTEXT_START);
//創(chuàng)建reactContext谅河,繼承于ContextWrapper
final ReactApplicationContext reactContext = new ReactApplicationContext(mApplicationContext);
if (mUseDeveloperSupport) { //設置本地模塊異常處理
reactContext.setNativeModuleCallExceptionHandler(mDevSupportManager);
}
//解析mPackages咱旱,并創(chuàng)建NativeModuleRegistry進行管理
NativeModuleRegistry nativeModuleRegistry = processPackages(reactContext, mPackages, false);
NativeModuleCallExceptionHandler exceptionHandler = mNativeModuleCallExceptionHandler != null
? mNativeModuleCallExceptionHandler
: mDevSupportManager;
CatalystInstanceImpl.Builder catalystInstanceBuilder = new CatalystInstanceImpl.Builder()
.setReactQueueConfigurationSpec(ReactQueueConfigurationSpec.createDefault())
.setJSExecutor(jsExecutor)
.setRegistry(nativeModuleRegistry)
.setJSBundleLoader(jsBundleLoader)
.setNativeModuleCallExceptionHandler(exceptionHandler);
ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_START);
//創(chuàng)建CatalystInstance實例
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "createCatalystInstance");
final CatalystInstance catalystInstance;
try {
catalystInstance = catalystInstanceBuilder.build();
} finally {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
ReactMarker.logMarker(CREATE_CATALYST_INSTANCE_END);
}
if (mBridgeIdleDebugListener != null) {
catalystInstance.addBridgeIdleDebugListener(mBridgeIdleDebugListener);
}
if (Systrace.isTracing(TRACE_TAG_REACT_APPS | TRACE_TAG_REACT_JS_VM_CALLS)) {
catalystInstance.setGlobalVariable("__RCTProfileIsProfiling", "true");
}
ReactMarker.logMarker(ReactMarkerConstants.PRE_RUN_JS_BUNDLE_START);
catalystInstance.runJSBundle();
// Transitions functions in the minitFunctions list to catalystInstance, to run after the bundle
// TODO T20546472
if (!mInitFunctions.isEmpty()) {
for (CatalystInstanceImpl.PendingJSCall function : mInitFunctions) {
((CatalystInstanceImpl) catalystInstance).callFunction(function);
}
}
reactContext.initializeWithInstance(catalystInstance);
return reactContext;
}
- 通過mApplicationContext來創(chuàng)建ReactApplicationContext
- 創(chuàng)建NativeModuleRegistry,將mPackages中每個ReactPackage返回的List<NativeModule>集合都注冊到NativeModuleRegistry中绷耍,這里不包含List<ViewManager>集合
- 創(chuàng)建CatalystInstance實例吐限,后續(xù)與C++進行交互
在創(chuàng)建CatalystInstance實例的同時也把NativeModuleRegistry引用給了它,這才真正和C++端建立起B(yǎng)ridge橋連接锨天,讓C++端能調(diào)用到JavaModule毯盈,CatalystInstanceImpl的構造函數(shù)內(nèi)部initializeBridge()可以表明這一點。
我們回過頭來看看NativeModuleRegistry的getJavaModules()
方法
/* package */ Collection<JavaModuleWrapper> getJavaModules(
JSInstance jsInstance) {
ArrayList<JavaModuleWrapper> javaModules = new ArrayList<>();
for (Map.Entry<Class<? extends NativeModule>, ModuleHolder> entry : mModules.entrySet()) {
Class<? extends NativeModule> type = entry.getKey();
if (!CxxModuleWrapperBase.class.isAssignableFrom(type)) {
javaModules.add(new JavaModuleWrapper(jsInstance, type, entry.getValue()));
}
}
return javaModules;
}
每一個JavaModule都用JavaModuleWrapper進行了包裹病袄,它是C++中Java層BaseJavaModule特有的包裝類搂赋,通過它可以更方便的閱讀和被JNI調(diào)用。在JavaModuleWrapper中解析了JavaModule的名字益缠、方法脑奠,并通過invoke方式進行調(diào)用。
@DoNotStrip
public class JavaModuleWrapper {
......
@DoNotStrip
public BaseJavaModule getModule() {
return (BaseJavaModule) mModuleHolder.getModule();
}
@DoNotStrip
public String getName() {
return mModuleHolder.getName();
}
@DoNotStrip
private void findMethods() {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "findMethods");
Set<String> methodNames = new HashSet<>();
Class<? extends NativeModule> classForMethods = mModuleClass;
Class<? extends NativeModule> superClass =
(Class<? extends NativeModule>) mModuleClass.getSuperclass();
if (ReactModuleWithSpec.class.isAssignableFrom(superClass)) {
classForMethods = superClass;
}
Method[] targetMethods = classForMethods.getDeclaredMethods();
for (Method targetMethod : targetMethods) {
ReactMethod annotation = targetMethod.getAnnotation(ReactMethod.class);
if (annotation != null) {
String methodName = targetMethod.getName();
if (methodNames.contains(methodName)) {
//js不支持方法重載否則會拋出這個異常
throw new IllegalArgumentException(
"Java Module " + getName() + " method name already registered: " + methodName);
}
MethodDescriptor md = new MethodDescriptor();
JavaMethodWrapper method = new JavaMethodWrapper(this, targetMethod, annotation.isBlockingSynchronousMethod());
md.name = methodName;
md.type = method.getType();
if (md.type == BaseJavaModule.METHOD_TYPE_SYNC) {
md.signature = method.getSignature();
md.method = targetMethod;
}
mMethods.add(method);
mDescs.add(md);
}
}
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
//C++端調(diào)用幅慌,返回這個NativeModule的所有被@ReactMethod注解方法的描述
@DoNotStrip
public List<MethodDescriptor> getMethodDescriptors() {
if (mDescs.isEmpty()) {
findMethods();
}
return mDescs;
}
......
}
這里有一點需要注意宋欺,findMethod()
方法中通過反射的方式,獲取到了所有被@ReactMethod注解標記的方法,
并用集合判斷了是否有方法名重復的方法齿诞,否則拋出IllegalArgumentException酸休,我們都知道在Java中可以很方便的根據(jù)方法名重復參數(shù)不一樣來進行方法重載,但是js是沒有方法重載的祷杈,否則就會出現(xiàn)問題斑司。
我自己寫了一個ToastModule測試類,里面進行了方法重載但汞,發(fā)現(xiàn)ReactNative并沒有把IllegalArgumentException拋回給Java層宿刮,直接就應用內(nèi)部崩潰ANR了,這是一個令人很尷尬的地方私蕾,其實我們可以通過ReactInstanceManagerBuilder#setNativeModuleCallExceptionHandler()進行捕獲處理.
大概就是這樣吧僵缺,可能對于ReactNative內(nèi)部執(zhí)行流程的還不是特別的熟悉,很多跟著源碼一步步點進去看的踩叭,如有不對的地方磕潮,還請各位看官多多包涵了!