Call native android activity from react-native

Call native activity methods from react-native

To call native activity from react-native, first I am considering that our react-native project has successfully integrated into existing Android studio project if not then read my previous articles on

How to setup react-native step by step Click here

How to integrate react-native in existing android app Click here

Before moving forward I consider that you complete react-native setup and integration in existing native android app, and now to need to call the native android method from react-native to do this

We have use react-native

Native Modules

Create native module

This guide will use one method, let’s say we would like to call this method from JavaScript

Create a call OpenAndroid.java and extends this call with ReactContextBaseJavaModule

import android.widget.Toast;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import java.util.Map;
import java.util.HashMap;

public class OpenAndroid extends ReactContextBaseJavaModule {

  public ToastModule(ReactApplicationContext reactContext) {

    super(reactContext);

  }
}

ReactContextBaseJavaModule  Require the method call getName the purpose of this method is to return string name in javaScript, you can access method by calling React.NativeModules.NativeCalls

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

We need to annotate the method with @ReactMethod to expose this method in JavaScript, the return type of this method is always Void and the React-native bridge is asynchronous

@ReactMethod
public void nextScreen(String message) {
    Intent intent = new Intent(this,NextScreenActivity.class);
       startActivity(intent);
}

We can pass following argument type from native module

Float -> number 
String -> String
Boolean -> bool
Integer -> number
Double -> number
Callback -> function   
ReadableMap -> Object
ReadableArray-> Array

Register the Module

We have to register this module in java code, if module not registered then it will not available in JavaScript to do this create one class name OpenAndroidPackage.java and implement it with React-Package as follows

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class OpenAndroidPackage 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 OpenAndroid(reactContext));
    return modules;

  }
}

Now, our native module created and the package is registered,

we need to pass this registered package to react-native project through the getPackage method of the MainApplication.java

you will get this file at the following path android/app/src/main/java/com/yourAppName/MainApplication.java

Or if you are open react-native project from some other activity like below then you want to pass our package like below

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

public class ReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {

    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .addPackage(new OpenAndroidPackage())  <-- like this
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "NativeApp", null)

        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostPause(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostResume(this, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostDestroy(this);
        }
    }

    @Override
    public void onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}

Use native module in JavaScript

To access native module in JavaScript, we need to wrap native module with javaScript module to do this

create JS module file in the react-native project,  ex. create NativeCalls.js and add the following line in it

import {NativeModules} from 'react-native';
module.exports = NativeModules.NativeCalls;

Then import this NativeCalls module where you want to use like as below

import NativeCalls from './NativeCalls';

and call the method like

NativeCalls.nextScreen('Awesome');

That set, you can use any existing android module using this method, just create module package–> Register that module package –> pass this package through the .addPackage method and done

 

Thank you 🙂 enjoy coding

34 Replies to “Call native android activity from react-native”

  1. Excellent way of describing, and fastidious piece of writing to take facts on the topic of my presentation topic, which i am going to convey in institution of higher education.|

  2. Excellent web site. A lot of helpful information here. I am sending it to some friends ans also sharing in delicious. And certainly, thank you for your effort!|

Leave a Reply

Your email address will not be published.