Communication between React Native and native (Android)

Software to prepare:

(1)Android studio

(2)vscode

In addition, we need to prepare an android real machine and a charging line

 

Step 1: create a new project folder and open it in vscode

 

Step 2: execute react native init ProjectName [version No. (optional)] to create a react native project

 

Step three: turn on the developer mode of the android real machine, ensure that the usb option is turned on, and allow file transfer, not just charging

 

Step 4: execute npm start or yarn start to check whether the project can work normally (if it is a mac computer, you can try to download Xcode, otherwise you can connect to the real machine to check)

 

Step 5: use Android studio to open the android/build.gradle file of our react native project

 

 

Step 6: find the app/java/com.projectname folder, create the ToastModule.java file, and write the following code:

package com.projectname;

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 ToastModule extends ReactContextBaseJavaModule {
    private static ReactApplicationContext reactContext;

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

    public ToastModule(ReactApplicationContext reactContext) {
        super(reactContext);
//        reactContext = 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();
    }
}

 

 

Step 7: find the app/java/com.projectname folder, create the CustomToastPackage.java file again, and write the following code:

// CustomToastPackage.java

package com.rndemo;

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 CustomToastPackage 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;
    }

}

 

 

Step 8: in the main application, add the following code in the red box

 

 

Step 9: now that we have finished the native part of the code, we need to reference our custom native module in vscode and declare the js trigger event function (the project here is the react native scaffolding project we created in vscode before)

The complete code of App.js is as follows:

// App.js
/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  StatusBar,
  NativeModules,
  AppRegistry,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
class App extends Component {
  call_button() {
    NativeModules.ToastExample.show(
      'Awesome66666',
      NativeModules.ToastExample.SHORT,
    );
  }
  render() {
    return (
      <>
        <View style={styles.container}>
          <Text onPress={this.call_button.bind(this)}>Test native communication</Text>
        </View>
      </>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'orange',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;

 

Step 10: carry out the following steps

(1) Check again whether the usb interface of the computer is connected to the android real machine, and whether the real machine has the usb option open, and allows the transfer of files

(2) Check whether the real machine is connected to the same wifi as the computer

(3) Run our react native project in vscode and execute npm start or yarn start again

(4) Execute adb devices to view the list of devices. If there are devices, the following effect will appear. If not, please check whether the above steps are followed

List of devices attached
654QAEUY1Q7EK   device

(5) Execute adb reverse tcp:8081 tcp:8081 to let the computer map the port to the android real machine to access the port

(6) Execute react native run android to package the local react native project to the android real machine. This is the apk download package

OK, the above steps are finished. Let's check the effect on the real machine:

 

 

 

207 original articles published, 40 praised, 110000 visitors+
Private letter follow

Tags: React Android Java npm

Posted on Mon, 13 Jan 2020 05:18:56 -0500 by Danny620