将数据从Android活动发送到React Native [英] Send data from Android activity to React Native

查看:260
本文介绍了将数据从Android活动发送到React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理本机android活动中的意图,并希望将在该意图内获得的数据发送到react本机部分.请原谅我拙劣的术语/解释-关于Android开发,我是一个完整的初学者.

I am handling an intent in a native android activity and would like to send the data obtained within the intent to the react native part. Please excuse my poor terminology/explanations - I am a complete beginner when it comes to Android development.

我已尝试遵循此指南:

I have tried following this guide: https://facebook.github.io/react-native/docs/native-modules-android.html#sending-events-to-javascript, but I get stuck on getting the main react context. So, the intent is coming outside of the app, and I would like to get the intent data and start the app. E.g. the main view should only display the text from intent.

这是我发送活动的方式:

This is how I send the event:

public class CustomActivity extends ReactActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    WritableMap map = Arguments.createMap();
    map.putString("messageString", "CustomMessage");

    try {
      getReactInstanceManager().getCurrentReactContext()
        .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
        .emit("customEvent", map);
    } catch (Exception e){
      Log.e("ReactNative", "Caught Exception: " + e.getMessage());
    }
}

这会引发异常

捕获的异常:尝试调用虚拟方法 'com.facebook.react.bridge.JavaScriptModule com.facebook.react.bridge.ReactContext.getJSModule(java.lang.Class)' 在空对象引用上

Caught Exception: Attempt to invoke virtual method 'com.facebook.react.bridge.JavaScriptModule com.facebook.react.bridge.ReactContext.getJSModule(java.lang.Class)' on a null object reference

我没有为活动定义自定义布局,而是想使用主应用程序的上下文.

I am not defining a custom layout for the activity and would like to use the main app's context.

推荐答案

所以这似乎失败了,因为没有及时创建上下文.为了解决这个问题,我添加了一个忙于等待上下文创建的过程.

So it seems like this fails because the context does not get created in time. To solve this I added a busy wait for the context to be created.

while (getReactInstanceManager().getCurrentReactContext() == null);  // Busy wait.
getReactInstanceManager().getCurrentReactContext()
    .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
    .emit("defineIntent", map);

如果有人知道更好的方式来处理等待,请在此处进行更新.谢谢!

If someone knows a better way to deal with the wait, please update it here. Thank you!

这篇关于将数据从Android活动发送到React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆