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. 解决WAS更新web.xml文件不生效的问题(web_merged.xml是罪魁祸首)

    问题原因分析 近日碰到更新web.xml文件到WAS服务器(WebSphere Application Server 8.5.5.3)后,不生效的问题. 网上找了一圈,基本都是说WAS缓存引起的. 手 ...

  2. asp 之 让实体中字段类型为DateTime的字段仅仅显示日期不显示时间

           在我们平时的工作开发中.我们一般会遇到这种一个问题:某个实体的某个字段是DateTime类型的,但是我们在界面上仅仅想让它显示日期不显示时间! 一个订单实体: //订单类 public ...

  3. RocketMQ性能压测分析(转载)

    一   机器部署 1.1  机器组成 1台nameserver 1台broker  异步刷盘 2台producer 2台consumer   1.2  硬件配置 CPU  两颗x86_64cpu,每颗 ...

  4. iOS UITextView 输入内容实时更新cell的高度

    iOS UITextView 输入内容实时更新cell的高度 2014-12-26 11:37 编辑: suiling 分类:iOS开发 来源:Vito Zhang'blog  11 4741 UIT ...

  5. ZOJ 3332 Strange Country II

    Strange Country II Time Limit: 1 Second      Memory Limit: 32768 KB      Special Judge You want to v ...

  6. 解决URL地址中的中文乱码问题的办法

    解决URL地址中的中文乱码问题的办法 引言: 在Restful类的服务设计中,经常会碰到需要在URL地址中使用中文作为的参数的情况,这种情况下,一般都需要正确的设置和编码中文字符信息.乱码问题就此产生 ...

  7. Career Planning:Developers Best Practices Tutorial

    This small tutorial is based on my past 16+ years of experience in software development industry. I ...

  8. Java 之单例设计模式

    设计模式: 对问题行之有效的解决方式, 其实它是一种思想. 单例设计模式 解决的问题:就是可以保证一个类在内存中的对象唯一性. 即单个实例. 比如对于A 和 B 两个程序使用同一个配置信息对象时, A ...

  9. PHP去除所有的空格

    1.去除两边的空格 trim($arr) 2.正则匹配去除所有的空格 preg_replace('# #','',$goodid)

  10. 浅谈 Python 的 with 语句(转)

    add by zhj: 上下文管理器是对try-except-finally的再封装而已,只能算是优化代码这一级别的feature 原文:http://www.ibm.com/developerwor ...