RN怎么与native交互的呢?

下面我们通过一个简单的Demo来实现:RN页面调起Native页面,Native页面选择电话本数据,将数据回传给RN展示。

首先是 Native侧

1、MainActivity

  1. package com.rnandroid01;
  2. import android.content.Intent;
  3. import android.database.Cursor;
  4. import android.net.Uri;
  5. import android.provider.ContactsContract;
  6. import com.facebook.react.ReactActivity;
  7. public class MainActivity extends ReactActivity {
  8. /**
  9. * Returns the name of the main component registered from JavaScript.
  10. * This is used to schedule rendering of the component.
  11. */
  12. @Override
  13. protected String getMainComponentName() {
  14. return "RNAndroid01";
  15. }
  16. @Override
  17. public void onActivityResult(int requestCode, int resultCode, Intent data) {
  18. super.onActivityResult(requestCode, resultCode, data);
  19. if(requestCode!=200 || resultCode!=RESULT_OK) return;
  20. Uri contactData = data.getData();
  21. Cursor cursor = managedQuery(contactData, null, null, null, null);
  22. cursor.moveToFirst();
  23. String num = getContactPhone(cursor);
  24. //下面的话  就是将num发送给rn侧 需要调用nativeModule对象里面的方法
  25. MainApplication.getMyReactPackage().myNativeModule.sendMsgToRn(num);
  26. }
  27. //这个是Native代码,与RN其实没什么关系
  28. private String getContactPhone(Cursor cursor) {
  29. // TODO Auto-generated method stub
  30. int phoneColumn = cursor
  31. .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
  32. int phoneNum = cursor.getInt(phoneColumn);
  33. String result = "";
  34. if (phoneNum > 0) {
  35. // 获得联系人的ID号
  36. int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
  37. String contactId = cursor.getString(idColumn);
  38. // 获得联系人电话的cursor
  39. Cursor phone = getContentResolver().query(
  40. ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
  41. null,
  42. ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "="
  43. + contactId, null, null);
  44. if (phone.moveToFirst()) {
  45. for (; !phone.isAfterLast(); phone.moveToNext()) {
  46. int index = phone
  47. .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
  48. int typeindex = phone
  49. .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
  50. int phone_type = phone.getInt(typeindex);
  51. String phoneNumber = phone.getString(index);
  52. result = phoneNumber;
  53. }
  54. if (!phone.isClosed()) {
  55. phone.close();
  56. }
  57. }
  58. }
  59. return result;
  60. }
  61. }

2、MainApplication

  1. package com.rnandroid01;
  2. import android.app.Application;
  3. import android.util.Log;
  4. import com.facebook.react.ReactApplication;
  5. import com.facebook.react.ReactInstanceManager;
  6. import com.facebook.react.ReactNativeHost;
  7. import com.facebook.react.ReactPackage;
  8. import com.facebook.react.shell.MainReactPackage;
  9. import java.util.Arrays;
  10. import java.util.List;
  11. public class MainApplication extends Application implements ReactApplication {
  12. private static final MyReactPackage myReactPackage=new MyReactPackage();
  13. public static MyReactPackage getMyReactPackage() {
  14. return myReactPackage;
  15. }
  16. private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
  17. @Override
  18. protected boolean getUseDeveloperSupport() {
  19. return BuildConfig.DEBUG;
  20. }
  21. @Override
  22. protected List<ReactPackage> getPackages() {
  23. return Arrays.<ReactPackage>asList(
  24. new MainReactPackage(),
  25. myReactPackage
  26. );
  27. }
  28. };
  29. @Override
  30. public ReactNativeHost getReactNativeHost() {
  31. return mReactNativeHost;
  32. }
  33. }

3、MyReactPackage

  1. package com.rnandroid01;
  2. import com.facebook.react.ReactPackage;
  3. import com.facebook.react.bridge.JavaScriptModule;
  4. import com.facebook.react.bridge.NativeModule;
  5. import com.facebook.react.bridge.ReactApplicationContext;
  6. import com.facebook.react.uimanager.ViewManager;
  7. import java.util.ArrayList;
  8. import java.util.Collections;
  9. import java.util.List;
  10. public class MyReactPackage implements ReactPackage {
  11. public MyNativeModule myNativeModule;
  12. @Override
  13. public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
  14. List<NativeModule> modules=new ArrayList<>();
  15. myNativeModule=new MyNativeModule(reactContext);
  16. modules.add(myNativeModule);
  17. return modules;
  18. }
  19. @Override
  20. public List<Class<? extends JavaScriptModule>> createJSModules() {
  21. return Collections.emptyList();
  22. }
  23. @Override
  24. public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
  25. return Collections.emptyList();
  26. }
  27. }

4、MyNativeModule

  1. package com.rnandroid01;
  2. import android.content.Context;
  3. import android.content.Intent;
  4. import android.os.Bundle;
  5. import android.provider.ContactsContract;
  6. import android.widget.Toast;
  7. import com.facebook.react.bridge.ReactApplicationContext;
  8. import com.facebook.react.bridge.ReactContextBaseJavaModule;
  9. import com.facebook.react.bridge.ReactMethod;
  10. import com.facebook.react.modules.core.DeviceEventManagerModule;
  11. public class MyNativeModule extends ReactContextBaseJavaModule {
  12. private ReactApplicationContext mContext;
  13. public MyNativeModule(ReactApplicationContext reactContext) {
  14. super(reactContext);
  15. mContext = reactContext;
  16. }
  17. @Override
  18. public String getName() {
  19. //一定要有这个名字的 在rn代码里面是需要这个名字来调用该类的方法的
  20. return "MyNativeModule";
  21. }
  22. //函数不能有返回值,因为被调用的原生代码是异步的,原生代码执行结束之后只能通过回调函数或者发送消息给rn那边
  23. //有一个错误
  24. @ReactMethod
  25. public void rnCallNative(String msg) {
  26. Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
  27. //        Intent intent = new Intent(mContext, MyActivity.class);
  28. //        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//一定要加上这句 否则报错
  29. //        mContext.startActivity(intent);
  30. Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
  31. Bundle bundle = new Bundle();
  32. mContext.startActivityForResult(intent,200,bundle);
  33. }
  34. public void sendMsgToRn(String msg){
  35. //将消息msg发送给RN侧
  36. mContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit("AndroidToRNMessage",msg);
  37. }
  38. }

在RN侧

  1. /**
  2. * Sample React Native App
  3. * https://github.com/facebook/react-native
  4. * @flow
  5. */
  6. import React, { Component } from 'react';
  7. import {
  8. AppRegistry,
  9. StyleSheet,
  10. Text,
  11. NativeModules,
  12. DeviceEventEmitter,
  13. View
  14. } from 'react-native';
  15. class RNAndroid01 extends Component {
  16. componentWillMount(){
  17. DeviceEventEmitter.addListener('AndroidToRNMessage',this.handleAndroidMessage);
  18. }
  19. componentWillunMount(){
  20. DeviceEventEmitter.remove('AndroidToRNMessage',this.handleAndroidMessage);
  21. }
  22. handleAndroidMessage=(msg)=>{
  23. //RN端获得native端传递的数据
  24. console.log(msg);
  25. }
  26. render() {
  27. return (
  28. <View style={styles.container}>
  29. <Text style={styles.welcome}
  30. onPress={this.CallAndroid}
  31. >
  32. Welcome to React Native!RN与Android的通信
  33. </Text>
  34. <Text style={styles.instructions}>
  35. To get started, edit index.android.js
  36. </Text>
  37. <Text style={styles.instructions}>
  38. Shake or press menu button for dev menu
  39. </Text>
  40. </View>
  41. );
  42. }
  43. CallAndroid=()=>{
  44. NativeModules.MyNativeModule.rnCallNative('rn调用原生模块的方法-成功啦');
  45. }
  46. }

上面的例子实现了RN与Native端的交互及数据传递。

重点使用了React Native的RCTDeviceEventEmitter,通过消息机制来实现。

好了,RN与native的交互还可以通过Promise和Callback回调方式实现,我们下篇文章再看。

引用原文:http://blog.csdn.net/codetomylaw/article/details/51926421

写博客是为了记住自己容易忘记的东西,另外也是对自己工作的总结,文章可以转载,无需版权。希望尽自己的努力,做到更好,大家一起努力进步!

如果有什么问题,欢迎大家一起探讨,代码如有问题,欢迎各位大神指正!

《React-Native系列》RN与native交互与数据传递的更多相关文章

  1. MIFARE系列3《卡能源和数据传递》

    在MIFARE卡中,能量和数据通过天线传输,卡中天线为几匝线圈,直接连接到芯片上,不再需要额外的组件.线圈嵌入塑料中,形成了一个无源的非接触卡. 读卡器向IC发一组固定频率的电磁波,卡内有一个IC串联 ...

  2. 《React-Native系列》3、RN与native交互之Callback、Promise

    接着上一篇<React-Native系列>RN与native交互与数据传递,我们接下来研究另外的两种RN与Native交互的机制 一.Callback机制 首先Calllback是异步的, ...

  3. React Native移动开发实战-3-实现页面间的数据传递

    React Native使用props来实现页面间数据传递和通信.在React Native中,有两种方式可以存储和传递数据:props(属性)以及state(状态),其中: props通常是在父组件 ...

  4. react native 0.50与OC交互 && Swift与RN交互

    新公司也打算做rn,还是得捡起来再度学习.开撸! react native一个版本一个样子,之前写的rn与iOS交互系列在最新版本中有点出入(0.50.4版本).今天填一下坑. 首先上npm版本,re ...

  5. 【REACT NATIVE 系列教程之十二】REACT NATIVE(JS/ES)与IOS(OBJECT-C)交互通信

    http://blog.csdn.net/xiaominghimi/article/details/51586492 一用到跨平台的引擎必然要有引擎与各平台原生进行交互通信的需要.那么Himi先讲解R ...

  6. 【react native】rn踩坑实践——从输入框“们”开始

    因为团队技术栈变更为react native,所以开始写起了rn的代码,虽然rn与react份数同源,但是由于有很多native有关的交互和变动,实际使用还是碰到蛮多问题的,于是便有了这个系列,本来第 ...

  7. React Native 系列(五) -- 组件间传值

    前言 本系列是基于React Native版本号0.44.3写的.任何一款 App 都有界面之间数据传递的这个步骤的,那么在RN中,组件间是怎么传值的呢?这篇文章将介绍到顺传.逆传已经通过通知传值. ...

  8. React Native 系列(三) -- 项目结构介绍

    前言 本系列是基于React Native版本号0.44.3写的,相信大家看了本系列前面两篇文章之后,对于React Native的代码应该能看懂一点点了吧.本篇文章将带着大家来认识一下React N ...

  9. React Native 系列(三)

    前言 本系列是基于React Native版本号0.44.3写的,相信大家看了本系列前面两篇文章之后,对于React Native的代码应该能看懂一点点了吧.本篇文章将带着大家来认识一下React N ...

随机推荐

  1. poj 3281(网络流+拆点)

    题目链接:http://poj.org/problem?id=3281 思路:设一个超级源点和一个超级汇点,源点与食物相连,饮料与汇点相连,然后就是对牛进行拆点,一边喜欢的食物相连,一边与喜欢的饮料相 ...

  2. 洛谷oj U3936(分成回文串) 邀请码:a0c9

    题目链接:传送门 题目大意:略 题目思路:DP 先预处理,分别以每个字母为中心处理能形成的回文串,再以两个字母为中心处理能形成的回文串. 然后 dp[i] 表示1~i 能形成的数目最少的回文串. 转移 ...

  3. android eclipse 环境配置(win 7)

    一.下载安装android SDK 两种方式: (1)官网下载(需FQ):https://developer.android.com/studio/index.html (2)无需FQ下载:http: ...

  4. Oracle的聚合函数group by结合CUBE和ROLLUP的使用

    转自:https://docs.oracle.com/cd/E11882_01/server.112/e25554/aggreg.htm#DWHSG8618 CUBE Syntax CUBE appe ...

  5. 烂笔头-Spring3

    1.spring相关jar包的导入 2.配置文件bean.xml <?xml version="1.0" encoding="UTF-8"?> &l ...

  6. Hessian接口测试

  7. POJ 2609 Ferry Loading(双塔DP)

    Ferry Loading Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 1807   Accepted: 509   Sp ...

  8. extern的原理很简单,就是告诉编译器:“你现在编译的文件中,有一个标识符虽然没有在本文件中定义,但是它是在别的文件中定义的全局变量,你要放行!”

    extern的原理很简单,就是告诉编译器:“你现在编译的文件中,有一个标识符虽然没有在本文件中定义,但是它是在别的文件中定义的全局变量,你要放行!”

  9. Python菜鸟之路:Django ModelForm的使用

    一.简单使用案例 #views.py #views.py from django.shortcuts import render,HttpResponse from app01 import mode ...

  10. JavaScript 入门之常见对象

    常见对象 1. Object 对象 2. String 对象 3. Array 对象 4. Date 对象 5. Number 对象 6. 自定义对象 with 语句 为了简化对象调用内容的书写 格式 ...