React-native: can android communication between native and React Native just like iOS?

Created on 10 Dec 2015  Â·  30Comments  Â·  Source: facebook/react-native

hi react-native,
can android communication between native and React Native just like iOS?
see https://facebook.github.io/react-native/docs/communication-ios.html

I found that iOS can use properties and bridge to transmit some args from native to react-native,
so I want to know how android run like that,
thx for reading.

Locked

Most helpful comment

@Ge-yuan-jun see the demo code below:

Java code (Android)

// Create reactRootView and reactInstanceManager as described in the demo app
Bundle initialProps = new Bundle();
initialProps.putString("message", "Hello World");

reactRootView.startReactApplication(reactInstanceManager, "AwesomeProject", initialProps);

JS code (React bundle)

AppRegistry.registerComponent("AwesomeProject", () =>
    React.createClass({
        render() {
            return (
                <View>
                    <Text>{this.props.message}</Text>
                </View>
            );
        }
    })
);

This will render a text view with the text "Hello World"

All 30 comments

Hey coderlin, thanks for reporting this issue!

React Native, as you've probably heard, is getting really popular and truth is we're getting a bit overwhelmed by the activity surrounding it. There are just too many issues for us to manage properly.

  • If this is a feature request or a bug that you would like to be fixed by the team, please report it on Product Pains. It has a ranking feature that lets us focus on the most important issues the community is experiencing.
  • If you don't know how to do something or not sure whether some behavior is expected or a bug, please ask on StackOverflow with the tag react-native or for more real time interactions, ask on Discord in the #react-native channel.
  • We welcome clear issues and PRs that are ready for in-depth discussion; thank you for your contributions!

@coderlin yes, we can communicate b/w android and react-native. Here is the official documentation for Android module development https://facebook.github.io/react-native/docs/native-modules-android.html#content

@rnagella thx for answer, but actually I want to know how to Passing properties from native to React Native, is that only support iOS now?

I already find out, thx guys.

@coderlin can you post your findings?

@coderlin can you post your findings?

@mkonicek I don't see how this is similar to initialProperties in RCTRootView constructor like described in the doc mentioned by @john1jan , is there any way to just pass props once to our root component in android without the complexity of two-ways asynchroneous communication of Modules ?

@mkonicek check out my blog which explains the communication to and from native to react native

@john1jan thanks but this is not what the doc explains only for iOS : how to pass initial params to your react-native code from you android native code

The answer lies in ReactActivity or ReactActivityDelegate (react-native > 0.34)

@Override
    protected @Nullable Bundle getLaunchOptions() {

@Thibaut-Fatus @john1jan can you share an example on how to use getLaunchOptions() with the new ReactActivityDelegate in RN 0.34? (I think 0.33 as well)

I've done this, works but I'm not sure this is the best way of doing things

// XXXReactActivityDelegate.java
package com.xxx;

import com.facebook.react.ReactActivityDelegate;
import android.os.Bundle;
import android.app.Activity;
import android.support.v4.app.FragmentActivity;
import javax.annotation.Nullable;

// subclass ReactActivityDelegate
public class XXXReactActivityDelegate extends ReactActivityDelegate {

  public XXXReactActivityDelegate(Activity activity, @Nullable String mainComponentName) {
    super(activity, mainComponentName);
  }

  public XXXReactActivityDelegate(
    FragmentActivity fragmentActivity,
    @Nullable String mainComponentName) {
      super(fragmentActivity, mainComponentName);
  }

  @Override
  protected @Nullable Bundle getLaunchOptions() {
    Bundle options = new Bundle();
    // add some stuff to the options
    options.putString("foo", BuildConfig.BAR);
    return options;
  }
}

And then

// MainActivity.java
package com.xxx;

import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import android.content.Intent;

public class MainActivity extends ReactActivity {

    @Override
    protected String getMainComponentName() {
        return "XXX";
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data);
    }

    // return a XXXReactActivityDelegate as delegate
    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
      return new XXXReactActivityDelegate(this, getMainComponentName());
    }
}

getlauchOptions has been moved inside ReactActivityDelegate, now I use this code:

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "myAppName";
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Nullable
            @Override
            protected Bundle getLaunchOptions() {
                Bundle initialProps = new Bundle();
                initialProps.putString("SOME_VARIABLE_1", BuildConfig.SOME_VARIABLE_1);
                initialProps.putString("SOME_VARIABLE_2", "some variable 2 value");
                return initialProps;
            }
        };
    }
}

You can pass initialProperties to the startReactApplication() function. I feel this is simpler than overriding getLaunchOptions()

mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", initialPropsBundle);

See: https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java#L189

@Cxxxx100 any demo?

The variable 'BuildConfig.SOME_VARIABLE_1' derive from the gradle file, set
buildConfigField inside your buildTypes debug or release config.

for example:

buildConfigField "String", "SOME_VARIABLE_!", "\"some string\""

On Fri, Nov 25, 2016 at 8:19 AM, 墨白 notifications@github.com wrote:

@micheletedeschi https://github.com/micheletedeschi where do you define
the variable named 'BuildConfig.SOME_VARIABLE_1'

—
You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
https://github.com/facebook/react-native/issues/4688#issuecomment-262894650,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABwv6gV501NEnZm6DHHN9JMxq7AMI8lZks5rBov8gaJpZM4GyYO5
.

--
Dott. Ing. Michele Tedeschi

@Ge-yuan-jun see the demo code below:

Java code (Android)

// Create reactRootView and reactInstanceManager as described in the demo app
Bundle initialProps = new Bundle();
initialProps.putString("message", "Hello World");

reactRootView.startReactApplication(reactInstanceManager, "AwesomeProject", initialProps);

JS code (React bundle)

AppRegistry.registerComponent("AwesomeProject", () =>
    React.createClass({
        render() {
            return (
                <View>
                    <Text>{this.props.message}</Text>
                </View>
            );
        }
    })
);

This will render a text view with the text "Hello World"

Does anyone know if Android supports updating appProperties like iOS does (see code snippet below)?

rootView.appProperties = @{@"images" : imageList};

What do mean by App Properties in Android ?. Is it AndroidManifest.xml ?

@tianxind No, you should use Native modules or simply use my approach.

@Cxxxx100 @john1jan is there any way to Send ReadableArray from a Java code as Bundle (initialProps)?

@sahir you can use my code and send HashMap from Java as Bundle.

@albertaleksieiev I try to use your code but there is no default constructor available in com.facebook.react.ReactInstanceManager.

@sahir I apologize for potential version mismatch. Can you please send code where you use com.facebook.react.ReactInstanceManager constructor?

@Cxxxx100 Is that possible to pass Props (values) from React bundle to Android?

@SanoopC Yes you can pass data from React bundle to Android using ReactMethod for example

@ReactMethod
    public void saveUser(ReadableMap userData) {
        Log.e("User Res", "" + userData);
    }

in React Using NativeModules you can call ReactMethod for example

const nativeComm = NativeModules.ReactNativeBridge;
nativeComm.saveUser(userData);

@sahir Thank you for the response. Next how to start an Activity from react native button click?

@SanoopC Please refer this repo https://github.com/sahir/ReactNativeBridge for communication between native SDK and React Native.

Was this page helpful?
0 / 5 - 0 ratings