Skip to content
Advertisement

How to call a Java method from Javascript

How do you call a Java method/ function from Javascript?

Java Function:

class Javafunction{

   public static void main(String[] args){

       System.out.println("It Works!");


   }
}

Javascript Function:

  function CallJavafunction() {
    
    Javafunction()

  }

Advertisement

Answer

To call java code from javascript in your react-native app, you have to create a module

I suggest reading the docs: https://reactnative.dev/docs/native-modules-android

Java code – android/app/src/main/java/com/your-app-name/JavaModule.java

package com.your-app-name; // replace com.your-app-name with your app’s name
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 JavaModule extends ReactContextBaseJavaModule {
   JavaModule(ReactApplicationContext context) {
       super(context);
   }

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

   @ReactMethod
   public void Javafunction(){
       System.out.println("It Works!");
   }
}

Register the Module – android/app/src/main/java/com/your-app-name/MyAppPackage.java

package com.your-app-name; // replace your-app-name with your app’s name
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 List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
       return Collections.emptyList();
   }

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

       modules.add(new JavaModule(reactContext));

       return modules;
   }

}

To register the package change the getPackages method in this file: android/app/src/main/java/com/your-app-name/MainApplication.java

@Override
protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    // below MyAppPackage is added to the list of packages returned
    packages.add(new MyAppPackage());
    return packages;
}

JavaScript code

const { JavaModule } = ReactNative.NativeModules;
JavaModule.Javafunction();
2 People found this is helpful
Advertisement