react native 調(diào)用 Android 原生組件

1:安裝環(huán)境

Node:18.9

React native :0.69.5

Expo:46.0.9

2:創(chuàng)建項目

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 創(chuàng)建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<String, Object> 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:創(chuàng)建MyAppPackage class


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

        modules.add(new CalendarModule(reactApplicationContext));

        return modules;
    }

    @NonNull
    @Override
    public List<ViewManager> 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<ReactPackage> getPackages() {
      @SuppressWarnings("UnnecessaryLocalVariable")
      List<ReactPackage> 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 (
    <View style={styles.container}>
      <Text>react native call native method</Text>
      <Button
        title="Press me"
        onPress={() => buttonPress()}
      />

    <Button
        title="print"
        onPress={() => buttonPrint()}
      />

    <Button
        title="nativeReturn"
        onPress={() => nativeReturn()}
      />  


    <Button
        title="testCallBack"
        onPress={() => testCallBack()}
      />

      <Button
        title="iminPrintStatus"
        onPress={() => iminPrintStatus()}
      />    
      <StatusBar style="auto" />
    </View>

    
    
  );
}

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

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末呈昔,一起剝皮案震驚了整個濱河市勺爱,隨后出現(xiàn)的幾起案子撵幽,更是在濱河造成了極大的恐慌,老刑警劉巖侦香,帶你破解...
    沈念sama閱讀 207,113評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異郎仆,居然都是意外死亡炕婶,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評論 2 381
  • 文/潘曉璐 我一進店門唐片,熙熙樓的掌柜王于貴愁眉苦臉地迎上來丙猬,“玉大人,你說我怎么就攤上這事费韭』吹浚” “怎么了?”我有些...
    開封第一講書人閱讀 153,340評論 0 344
  • 文/不壞的土叔 我叫張陵揽思,是天一觀的道長。 經(jīng)常有香客問我见擦,道長钉汗,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,449評論 1 279
  • 正文 為了忘掉前任鲤屡,我火速辦了婚禮损痰,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘酒来。我一直安慰自己卢未,他們只是感情好,可當我...
    茶點故事閱讀 64,445評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著辽社,像睡著了一般伟墙。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上滴铅,一...
    開封第一講書人閱讀 49,166評論 1 284
  • 那天戳葵,我揣著相機與錄音,去河邊找鬼汉匙。 笑死拱烁,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的噩翠。 我是一名探鬼主播戏自,決...
    沈念sama閱讀 38,442評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼伤锚!你這毒婦竟也來了擅笔?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,105評論 0 261
  • 序言:老撾萬榮一對情侶失蹤见芹,失蹤者是張志新(化名)和其女友劉穎剂娄,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體玄呛,經(jīng)...
    沈念sama閱讀 43,601評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡阅懦,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,066評論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了徘铝。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片耳胎。...
    茶點故事閱讀 38,161評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖惕它,靈堂內(nèi)的尸體忽然破棺而出怕午,到底是詐尸還是另有隱情,我是刑警寧澤淹魄,帶...
    沈念sama閱讀 33,792評論 4 323
  • 正文 年R本政府宣布郁惜,位于F島的核電站,受9級特大地震影響甲锡,放射性物質(zhì)發(fā)生泄漏兆蕉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 39,351評論 3 307
  • 文/蒙蒙 一缤沦、第九天 我趴在偏房一處隱蔽的房頂上張望虎韵。 院中可真熱鬧,春花似錦缸废、人聲如沸包蓝。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽测萎。三九已至亡电,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間绳泉,已是汗流浹背逊抡。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評論 1 261
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留零酪,地道東北人冒嫡。 一個月前我還...
    沈念sama閱讀 45,618評論 2 355
  • 正文 我出身青樓,卻偏偏與公主長得像四苇,于是被迫代替她去往敵國和親孝凌。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,916評論 2 344

推薦閱讀更多精彩內(nèi)容