How to create an Android native module with React Native
1. Create a module class MyTestModule at android/app/main/java/com/example/MyTestModule.java
import android.util.Log; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; public class MyTestModule extends ReactContextBaseJavaModule { public MyTestModule(ReactApplicationContext context) { super(context); } @Override public String getName() { return "MyTestModule"; } @ReactMethod public void createTestEvent(String name, String location) { Log.d("MyTestModule", "Create event called with name: " + name + " and location: " + location); } }
2. Create a package class MyAppPackage.java at android/app/main/java/com/example/MyAppPackage.java
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 MyAppPackage implements ReactPackage { @Override public ListcreateViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } @Override public List createNativeModules( ReactApplicationContext reactContext) { List modules = new ArrayList<>(); modules.add(new MyTestModule(reactContext)); return modules; } }
4. To register the MyTestModule package, you must add MyAppPackage to the list of packages returned in ReactNativeHost’s getPackages() method. Open up your MainApplication.java file, which can be found in the following path: android/app/src/main/java/com/your-app-name/MainApplication.java
Locate ReactNativeHost’s getPackages() method and add your package to the packages list getPackages() returns:
@Override protected ListgetPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); // below MyAppPackage is added to the list of packages returned packages.add(new MyAppPackage()); return packages; }
5. In React native, here is how to use the Android native module created above.
import React from 'react'; import { Button, NativeModules } from 'react-native'; const { MyTestModule } = NativeModules; const NativeTestView: React.FC = (props)=>{ const onPress = () => { console.log('Invoking the native module here!'); MyTestModule.createTestEvent('testName', 'testLocation'); }; return ( ); } export default NativeTestView;
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts