Native Module - Android

使用Android Studio編輯

部分的code請參考圖片內容

新建

1.在專案內新建一個HelloWorld.java

2.我們還需要建構Package檔案包裝此模組,讓我們可以在建置中加以引用。它也應該與HelloWorld.java放在一起。

3.必須在MainApplication.java => getPackages()中加入套件。

4.在RN專案內要使用的.js中:

//.js檔案內 最上方做import的動作
import { NativeModules } from 'react-native';
var HelloWorld = NativeModules.HelloWorld;

//在要call此function的地方使用下方的code
HelloWorld.greeting('Bonnie’);

callback

1.new Module (最下方有附code)

  • 1) 在src/main/java/..../新建 .java檔案 - extends ReactContextBaseJavaModule @Override getName方法 - return the string name of the NativeModule which represents this class in JavaScript

  • 2) @ReactMethod function,function內需帶入callback參數 使用callback.invoke()回傳值,可帶入多個參數 ps.To expose a method to JavaScript a Java method must be annotated using @ReactMethod. The return type of bridge methods is always void.

2.Register the Module (最下方有附code)

  • 1)在src/main/java/..../新建 packager.java檔案 - implements ReactPackage

3.在MainApplication.java 中 getPackages方法中 提供此package The path to this file is: android/app/src/main/java/com/your-app-name/MainApplication.java

4.在RN專案內要使用的.js中

//此.js檔案內上方做import和宣告等動作
import{
    NativeModules,
} from 'react-native';
var AllPayPassMethod = NativeModules.AllPayPassMethod;

//在要使用該方法的地方,使用以下的code來實作該方法
  AllPayPassMethod.bridgeTest("hello”);
  AllPayPassMethod.encryptMap(json,
      (errMsg) => {
        console.warn(errMsg);
      },
      (SuccessMsg) => {
        console.log(SuccessMsg);
        this.post(SuccessMsg);
      });

附上

參考

Last updated