How to call a React Native method from Android native activity which does not have React Context

361 Views Asked by At

I am building a React Native plugin for an Android SDK that is already built, I am using Native Modules to call methods from React native to Android native as shown below

import { NativeModules, Platform } from 'react-native';

const CoreSDKPlugin = NativeModules.CoreSDKPlugin
  ? NativeModules.CoreSDKPlugin
  : new Proxy(
      {},
      {
        get() {
          throw new Error(LINKING_ERROR);
        },
      }
    );

And I have a different AppCompatActivity in Android native which needs to provide a callback to React Native that a Call has been ended. I know we can do that using React Context like below

val message = "Call Ended"

val reactNativeContext = //get React Native Context here

reactNativeContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
    ?.emit("call_ended", message)

But as I am inside AppCompatActivity the context in the here is not React Context its Android context, please help how do I get React Native Context inside this activity. I do have React Context inside another activity which extends ReactContextBaseJavaModule

class SDKPluginModule(reactContext: ReactApplicationContext) :
  ReactContextBaseJavaModule(reactContext) {

  override fun getName(): String {
    return NAME
  }

  @ReactMethod
  fun launchMeeting() {
    context = reactApplicationContext // context is available in here
    val intent = Intent(reactApplicationContext, PermissionActivity::class.java)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    reactApplicationContext.startActivity(intent)
  }

  companion object {
    const val NAME = "CoreSDKPlugin"
  }
}

I've tried casting Application context inside AppCompatActivity to ReactContext but it didn't work, I also tried using a method called getReactContext() but it requires a View that is binded with the SDK. And as I am using an already built SDK I do not have a View available.

1

There are 1 best solutions below

0
Yash Ashra On

As I did not have React Context in App Compat Activity and casting of AppContext to ReactContext was not working I used Companion Object inside ReactContextBaseJavaModule activity to save React Context and then use it in AppCompatActivity based activity

companion object {
    const val NAME = "SDKPlugin"
    lateinit var context: ReactApplicationContext
  }

I initialized the context when calling the first function of react native is called. And then I used it in another activity which does not have a React Context

@ReactMethod
  fun launchMeeting() {
    context = reactApplicationContext
    ...
  }
val message = "Call Ended"

SDKPluginModule.context.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter::class.java)
    ?.emit("call_ended", message)