react native 调用 Android 原生组件

1:安装环境

Node:18.9

React native :0.69.5

Expo:46.0.9

2:创建项目

npx create-expo-app expo-call-native-code
cd expo-call-native-code

3:安装Android studio

https://developer.android.com/studio

4:启动项目

expo run:android

5:用Android studio 打开 react native Android 文件夹

image-20220918094001473.png

6:在Android studio 创建CalendarModule class

public class CalendarModule extends ReactContextBaseJavaModule {


    CalendarModule(ReactApplicationContext context) {
        super(context);
    }

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

    @ReactMethod
    public void createCalendarEvent(String name, String location) {
        Log.d("CalendarModule", "Create event called with name: " + name
                + " and location: " + location);

    }
    @ReactMethod
    public String test() {
        Log.d("==getConstants======","rrrr");
        final Map constants = new HashMap();
        constants.put("DEFAULT_EVENT_NAME", "New Event");
        return "test====";
    }

    @ReactMethod
    public void testCallBack(String name, String location, Callback callBack) {
        Log.d("==testCallBack======","test===");
        callBack.invoke("testCallback");
    }
}

7:创建MyAppPackage class


public class MyAppPackage implements ReactPackage {
    @NonNull
    @Override
    public List createNativeModules(@NonNull ReactApplicationContext reactApplicationContext) {
        List modules = new ArrayList<>();

        modules.add(new CalendarModule(reactApplicationContext));

        return modules;
    }

    @NonNull
    @Override
    public List createViewManagers(@NonNull ReactApplicationContext reactApplicationContext) {
        return Collections.emptyList();
    }
}

8:向Android application注册module

public class MainApplication extends Application implements ReactApplication {
  private final ReactNativeHost mReactNativeHost = new ReactNativeHostWrapper(
    this,
    new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List packages = new PackageList(this).getPackages();
      // Packages that cannot be autolinked yet can be added manually here, for example:
      // packages.add(new MyReactNativePackage());
      packages.add(new MyAppPackage());
      
      return packages;
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  });

  private final ReactNativeHost mNewArchitectureNativeHost =
      new ReactNativeHostWrapper(this, new MainApplicationReactNativeHost(this));

  @Override
  public ReactNativeHost getReactNativeHost() {
    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      return mNewArchitectureNativeHost;
    } else {
      return mReactNativeHost;
    }
  }

  @Override
  public void onCreate() {
    super.onCreate();
    // If you opted-in for the New Architecture, we enable the TurboModule system
    ReactFeatureFlags.useTurboModules = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED;
    SoLoader.init(this, /* native exopackage */ false);

    initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
    ApplicationLifecycleDispatcher.onApplicationCreate(this);
  }

  @Override
  public void onConfigurationChanged(@NonNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig);
  }

  /**
   * Loads Flipper in React Native templates. Call this in the onCreate method with something like
   * initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
   *
   * @param context
   * @param reactInstanceManager
   */
  private static void initializeFlipper(
      Context context, ReactInstanceManager reactInstanceManager) {
    if (BuildConfig.DEBUG) {
      try {
        /*
         We use reflection here to pick up the class that initializes Flipper,
        since Flipper library is not available in release mode
        */
        Class aClass = Class.forName("com.zcdmaple.expocallnativecode.ReactNativeFlipper");
        aClass
            .getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
            .invoke(null, context, reactInstanceManager);
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      } catch (NoSuchMethodException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (InvocationTargetException e) {
        e.printStackTrace();
      }
    }
  }
}

9:前端代码

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View ,Button,Alert,NativeModules} from 'react-native';
const { CalendarModule,IminPrintModule } = NativeModules;


export default function App() {

  const buttonPress = () => {
    console.log("button===press");
    CalendarModule.createCalendarEvent('testName', 'testLocation');
  }

  const buttonPrint = () => {
    console.log("button===print");
    console.log("Printing......");
     let type = "test" + "\n";
    

    IminPrintModule.iminPrint(
      type
    );

  }


  const nativeReturn = () => {
    console.log("nativeReturn===");
    let test = CalendarModule.test();
    console.log("CalendarModule.getConstants map",test);
  }

  const testCallBack = () => {
    console.log("testCallBack====");
    CalendarModule.testCallBack("fdf","test",(result) => {
      console.log("CalendarModule.test================================",result);
    })
  }

  const iminPrintStatus = () => {
    console.log("iminPrintStatus====");
    IminPrintModule.iminPrintStatus((resultSatus) => {
      console.log("resultSatus======",resultSatus)
    })

  }
  return (
    
      react native call native method
      

10:运行效果

查看Android log 命定 adb -d logcat or adb logcat -v time >xxx/t.log

image-20220918101443311.png

代码链接
https://github.com/knowledgeAlan/expo-call-native-code

你可能感兴趣的:(react native 调用 Android 原生组件)