React Native + Java

Modules (1)

public class ToastModule extends ReactContextBaseJavaModule {

  private static final String DURATION_SHORT_KEY = "SHORT";
  private static final String DURATION_LONG_KEY = "LONG";

  public ToastModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

***
}

extends ReactContextBaseJavaModule

Modules (2)

public class ToastModule extends ReactContextBaseJavaModule {

  private static final String DURATION_SHORT_KEY = "SHORT";
  private static final String DURATION_LONG_KEY = "LONG";

  public ToastModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "ToastExample";
  }

***
}

has getName() method that exposes the name of the module to the JS code

Modules (3)

public class ToastModule extends ReactContextBaseJavaModule {

  private static final String DURATION_SHORT_KEY = "SHORT";
  private static final String DURATION_LONG_KEY = "LONG";

  public ToastModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "ToastExample";
  }

  @Override
  public Map<String, Object> getConstants() {
    final Map<String, Object> constants = new HashMap<>();
    constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
    constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
    return constants;
  }

***
}

has getConstants() method that returns constants exposed to the JS code 

Modules (4)

public class ToastModule extends ReactContextBaseJavaModule {

  private static final String DURATION_SHORT_KEY = "SHORT";
  private static final String DURATION_LONG_KEY = "LONG";

  public ToastModule(ReactApplicationContext reactContext) {
    super(reactContext);
  }

  @Override
  public String getName() {
    return "ToastExample";
  }

  @Override
  public Map<String, Object> getConstants() {
    final Map<String, Object> constants = new HashMap<>();
    constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
    constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
    return constants;
  }

  @ReactMethod
  public void show(String message, int duration) {
    Toast.makeText(getReactApplicationContext(), message, duration).show();
  }
}

has methods exposed with @ReactMethod annotation to the JS code

Module Registration (1)

public class AnExampleReactPackage implements ReactPackage {

  @Override
  public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
    return Collections.emptyList();
  }

  @Override
  public List<NativeModule> createNativeModules(
                              ReactApplicationContext reactContext) {
    List<NativeModule> modules = new ArrayList<>();

    modules.add(new ToastModule(reactContext));

    return modules;
  }

}
  • implement ReactPackage
  • Register the module inside the createNativeModules method

Module Registration (2)

public class MainApplication extends Application implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            // Enable dev menu
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.asList(
                    new ActivityStarterReactPackage(),
                    new MainReactPackage()
            );
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }
}

Register the ReactPackage class in the MainApplication class

Communication (1)

Callbacks

import com.facebook.react.bridge.Callback;
    
@ReactMethod
void getActivityName(@Nonnull Callback callback) {
    Activity activity = getCurrentActivity();
    if (activity != null) {
        callback.invoke(activity.getClass().getSimpleName());
    }
}
 <Button
        onPress={() => activityStarter.getActivityName((name) => { alert(name); })}
        title='Get activity name'
      />

JS

Java

Communication (2)

Promise

import com.facebook.react.bridge.Promise;
    
@ReactMethod
void getActivityNameAsPromise(@Nonnull Promise promise) {
    Activity activity = getCurrentActivity();
    if (activity != null) {
        promise.resolve(activity.getClass().getSimpleName());
    }
}
<Button
        onPress={async () => {
          try {
            var name = await activityStarter.getActivityNameAsPromise();
            alert(name);
          } catch (e) {
              alert(e.message);
          }
        }}
        title='Get activity name as promise' />

JS

Java

Communication (3)

EventEmitter

getReactApplicationContext().getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
    .emit("MyEventValue", message);
import { NativeEventEmitter } from 'react-native';

const eventEmitter = new NativeEventEmitter(activityStarter);
eventEmitter.addListener(activityStarter.MyEventName, (params) => alert(params));

JS

Java

ActivityStarterModule.java

@Nullable
@Override
public Map<String, Object> getConstants() {
    final Map<String, Object> constants = new HashMap<>();
    constants.put("MyEventName", "MyEventValue");
    return constants;
}

Sources

Topics left:

- How to deliver activity result to JS

- How to listen for lifecycle events

Both are covered in the React Native docs

Thank you!

React Native + Java

By Georgi Mirchev

React Native + Java

  • 836