« « Fixing “No rule to make target ‘/usr/lib/liblog4cxx.so’ in ROS |

Communication between native and React Native in Android

Jun 22, 2016 by     1 Comment    Posted under: Android, React Native

React Native is awesome for cross platform development, but I’ve noticed that the documentation for iOS is a lot more complete than the documentation for Android. If you want to pass variables from your native app to React, it’s documented here for iOS, but nowhere for Android. Don’t worry, it’s just as easy to do in Android.

In your Android MainActivity, add this function:

protected @Nullable Bundle getLaunchOptions() {
    Bundle b = new Bundle();
    b.putString("myString", "something");
    return b;
}

That’s all you need. Now in React you can retrieve it from index.android.js like this:

console.log(this.props.myString);

If your variable relies on something loaded from the onCreate() method, you can set it like this. First, define your bundle at the top of the MainActivity class:

Bundle b = new Bundle();

Define your onCreate method, and do whatever you need to generate the variable:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    b.putString("myString", "something");
}

Then return it in our launch option function:

protected @Nullable Bundle getLaunchOptions() {
    return b;
}

1 Comment + Add Comment

  • I want to pass a callback in getLaunchOptions, How can i do?

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>