You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中悬浮窗组件无法访问OverlayModule原生模块的问题

React Native悬浮窗组件中NativeModules.OverlayModule为null的解决方案

在主App组件(App.tsx)中能正常获取NativeModules.OverlayModule,但将LeftSidebar作为悬浮窗通过OverlayService显示时,该组件中NativeModules.OverlayModule返回null。

问题根源

主App的React实例由ReactNativeHost自动初始化,会包含你在MainApplication中注册的所有自定义ReactPackage(包括MyAppPackage)。但悬浮窗的ReactInstanceManager是手动构建的,仅添加了MainReactPackage,没有包含自定义的MyAppPackage,导致OverlayModule未被注册到悬浮窗的React实例中。

解决方案

修改OverlayService.kt,在构建ReactInstanceManager时添加自定义的MyAppPackage,同时确保React上下文正确:

  1. 导入MyAppPackage
    在OverlayService.kt顶部添加导入:
import com.autoclickbot.MyAppPackage
  1. 修改ReactInstanceManager构建代码
    在ReactInstanceManager.builder()链中添加.addPackage(MyAppPackage()),同时将ReactRootView的上下文替换为ReactApplicationContext:

修改后的onStartCommand方法关键代码:

override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
    Log.d("OverlayService", "onStartCommand called")

    val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY 
        else WindowManager.LayoutParams.TYPE_PHONE

    val params = WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            type,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
            PixelFormat.TRANSLUCENT
    )

    params.gravity = Gravity.LEFT or Gravity.CENTER_VERTICAL

    mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager

    // 使用ReactApplicationContext作为ReactRootView的上下文
    val reactContext = ReactApplicationContext(applicationContext)
    mReactRootView = ReactRootView(reactContext)
    
    mReactInstanceManager = ReactInstanceManager.builder()
        .setApplication(application)
        .setBundleAssetName("index.android.bundle")
        .setJSMainModulePath("index")
        .addPackage(MainReactPackage())
        // 添加自定义的MyAppPackage
        .addPackage(MyAppPackage())
        .setUseDeveloperSupport(BuildConfig.DEBUG)
        .setInitialLifecycleState(LifecycleState.BEFORE_CREATE)
        .build()

    mReactRootView?.startReactApplication(mReactInstanceManager, "leftSidebar", null)

    mWindowManager?.addView(mReactRootView, params)

    return START_STICKY
}

额外检查

确保MainApplication.kt中已正确注册MyAppPackage(你提供的代码中已注册,这部分无需修改):

override fun getPackages(): List<ReactPackage> {
    return PackageList(this).packages.apply {
        add(MyAppPackage())
    }
}

完成以上修改后,重新编译运行,悬浮窗组件LeftSidebar就能正常获取NativeModules.OverlayModule实例了。

内容的提问来源于stack exchange,提问作者Lex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:44:52