React Native Native Modules,官方地址:https://facebook.github.io/react-native/docs/native-modules-android.html

第一步:使用Android Studio在项目中增加两个Class

TestReactModule.java

package com.tqstablet;

import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView; 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 com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.BaseActivityEventListener;
import com.facebook.react.bridge.ActivityEventListener; import java.util.Map;
import java.util.HashMap; import android.os.Build;
import com.facebook.react.bridge.Callback; /**
* Created by ChenWes on 2018-05-24.
*/ public class TestReactModule extends ReactContextBaseJavaModule { // Toast code
private static final String DURATION_SHORT_KEY = "SHORT";
private static final String DURATION_LONG_KEY = "LONG"; // image code
private static final int IMAGE_PICKER_REQUEST = 467081;
private static final String E_ACTIVITY_DOES_NOT_EXIST = "E_ACTIVITY_DOES_NOT_EXIST";
private static final String E_PICKER_CANCELLED = "E_PICKER_CANCELLED";
private static final String E_FAILED_TO_SHOW_PICKER = "E_FAILED_TO_SHOW_PICKER";
private static final String E_NO_IMAGE_DATA_FOUND = "E_NO_IMAGE_DATA_FOUND"; private Promise mPromise; private final ActivityEventListener mActivityEventListener = new BaseActivityEventListener() {
@Override
public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent intent) {
// Toast.makeText(getReactApplicationContext(), "找到照片" + requestCode + "****" + resultCode, Toast.LENGTH_SHORT).show();
if (requestCode == IMAGE_PICKER_REQUEST) {
if (mPromise != null) {
if (resultCode == Activity.RESULT_CANCELED) {
// Toast.makeText(getReactApplicationContext(), "RESULT_CANCELED", Toast.LENGTH_SHORT).show();
mPromise.reject(E_PICKER_CANCELLED, "Image picker was cancelled");
} else if (resultCode == Activity.RESULT_OK) {
// Toast.makeText(getReactApplicationContext(), "RESULT_OK", Toast.LENGTH_SHORT).show();
Uri uri = intent.getData(); Toast.makeText(getReactApplicationContext(), uri.toString(), Toast.LENGTH_SHORT).show();
if (uri == null) {
mPromise.reject(E_NO_IMAGE_DATA_FOUND, "No image data found");
} else {
mPromise.resolve(uri.toString());
}
}
mPromise = null;
}
}
}
}; public TestReactModule(ReactApplicationContext reactContext) {
super(reactContext); // Add the listener for `onActivityResult`
reactContext.addActivityEventListener(mActivityEventListener);
} @Override
public String getName() {
return "TestReactModule";
} @Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
return constants;
} /* 无回调的方式 *************************************************************/ @ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), "Android :" + message, duration).show();
}
/* 事件回调的方式 *************************************************************/ @ReactMethod
public void getSystemModel(Callback result) {
String sysModel = Build.MODEL;
result.invoke(sysModel);
} @ReactMethod
public void getSystemModelAndVersion(Callback result) {
String sysModel = Build.MODEL;
String sysVersion = Build.VERSION.RELEASE;
result.invoke(sysModel, sysVersion);
} /* Promise的方式 *************************************************************/ @ReactMethod
public void pickImage(final Promise promise) {
Activity currentActivity = getCurrentActivity(); if (currentActivity == null) {
promise.reject(E_ACTIVITY_DOES_NOT_EXIST, "Activity doesn't exist");
return;
}
// Store the promise to resolve/reject when picker returns data
mPromise=null;
mPromise = promise; try {
final Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType("image/*");
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Pick an image");
currentActivity.startActivityForResult(chooserIntent, IMAGE_PICKER_REQUEST); Toast.makeText(getReactApplicationContext(), "弹出照片库", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
mPromise.reject(E_FAILED_TO_SHOW_PICKER, e);
mPromise = null;
}
}
}

TestReactModulePackage.java

package com.tqstablet;

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; /**
* Created by ChenWes on 2018-05-24.
*/ public class TestReactModulePackage 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 TestReactModule(reactContext)); return modules;
}
}

第二步:在MainApplication.java中增加引用

package com.tqstablet;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.AlexanderZaytsev.RNI18n.RNI18nPackage;
import com.imagepicker.ImagePickerPackage;
import com.learnium.RNDeviceInfo.RNDeviceInfo;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader; import java.util.Arrays;
import java.util.List; public class MainApplication extends Application implements ReactApplication { private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
} @Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new RNI18nPackage(),
new ERulerPackage(),
new TestReactModulePackage(),
new RNDeviceInfo(),
new ImagePickerPackage()
);
} @Override
protected String getJSMainModuleName() {
return "index";
}
}; @Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
} @Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
}
}

第三步:在React Native中进行调用

TestModule.js

import { NativeModules } from 'react-native';
module.exports = NativeModules.TestReactModule;

调用代码

import TestReactModule from '../util/TestReactModule';

<Button style={styles.menuButton} onPress={() => {
//无回调
// TestReactModule.show("平板端打开一个对话框", TestReactModule.LONG);

//回调事件
// TestReactModule.getSystemModel((getModel) => {
// Alert.alert(getModel);
// });

//回调事件,多参数
// TestReactModule.getSystemModelAndVersion((sysModel, sysVersion) => {
// Alert.alert(sysModel, sysVersion);
// });

//Promise
TestReactModule.pickImage()
.then((data) => {
Alert.alert(data);
}).catch((err) => {
Alert.alert('Err', err.message);
})

}}>
React Native 测试
</Button>

react native native module的更多相关文章

  1. [RN] React Native 错误 Module does not exist in the module map

    React Native 错误 Module does not exist in the module map 代码如下: import Login from 'login' import Index ...

  2. React Native是一套使用 React 构建 Native app 的编程框架

    React Native是一套使用 React 构建 Native app 的编程框架 React Native at first sight what is React Native? 跟据官方的描 ...

  3. react native-调用react-native-fs插件时,如果数据的接口是需要验证信息的,在android上运行报错

    调用react-native-fs插件时,如果数据的接口是需要验证信息的,在android上运行报错,而在iOS上运行没问题.原因是因为接口是有验证信息的,而调用这个插件时没有传入,在iOS上会自动加 ...

  4. React Native--Animated:`useNativeDriver`is not supported because the native animated module is missing

    目录 问题描述 解决方法 问题描述 react-native init 项目,在运行中报错 解决方法 打开Xcode项目,点击Libraries文件夹右键Add Files to "项目名& ...

  5. react 调用 native 的callShareAllFunc()方法,实现分享

    let shareName = { '0': '微信', '1': '朋友圈', '2': '新浪微博', '3': ' QQ', '4': 'QQ空间'};render(){ //分享YztApp. ...

  6. react-native 计算时间差

    //计算时间var sendTime = this.props.obj.send_time; console.log(sendTime); //当前时间var nowTime = (new Date( ...

  7. [React] {svg, css module, sass} support in Create React App 2.0

    create-react-app version 2.0 added a lot of new features. One of the new features is added the svgr  ...

  8. React使用css module和className多类名设置

    引入样式文件 import styles from './footer.module.css'; 注意: 样式文件名必须要以.module.css结尾 单类名设置 <div className= ...

  9. Cordova VS React Native 谁是未来? - b

    对于原生native还是倍加推崇的,极佳的用户体验和性能让我学的如痴如醉,可是互联网这个世界可以用一句话可以总结:没有什么是不可能的.自从阿里淘宝天猫横空出世,它们教会了人们如何在网上购物,然后仿佛一 ...

随机推荐

  1. 解决oracle数据库 ora-00054:resource busy and acquire with NOWAIT specified 错误

    解决oracle数据库 ora-00054:resource busy and acquire with NOWAIT specified 错误 本人在使用pl/sql developer 客户端调用 ...

  2. js的alert抛出之后怎么让页面停止执行?

    方法: 1.如果是form的submit提交,如果要停止,则返回false:如果提交,则返回true就行了. 2.如果是手工跳转的方式,则如果要停止,则不执行跳转代码:如果要提交,则执行跳转代码 示例 ...

  3. tortoise svn冲突解决

    Tortoiese svn 冲突解决 当文件被别人修改并提交到SVN服务器后,如果自己本地的文件没有被更新为最新的版本,而且已经做了修改,这时候提交将会被成功,系统会提示你的版本已经过期,并要求你先进 ...

  4. tcp/ip 学习-通过视频学习

    视频下载地址:http://down.51cto.com/zt/5518/ http://www.icoolxue.com/album/show/328 每天可以拿两个番茄钟看视频,主要目的还是了解, ...

  5. 与http协作的web服务器、http首部(第五章、第六章)

    第五章 与http协作的web服务器 1.用单台虚拟主机实现多个域名 通过域名访问主机,经过DNS解析成ip地址,反向代理,可以代理多台服务器,正向代理则相反,代理客户端 2.通信数据转化程序:代理. ...

  6. 其他:OI竞赛中的文件操作

    本文介绍三种方法进行文件输入输出,都非常实用 第一种方法是采用重定向的形式进行输入输出,很方便 freopen("input.txt","r",stdin); ...

  7. Ant打jar包时,参数名被修改的问题

    https://blog.csdn.net/landehuxi/article/details/42678117 使用Ant打jar包后,发现jar包中的方法名会在前面自动添加了“param”前缀,导 ...

  8. 一个App架构例子分析--UI层使用MVP模式;各层之间使用Otto实现通信

    一.这个App整体的架构划分: 分为四大模块:   1.app模块 2.common模块 3.domain模块 4.model模块     app模块的依赖: dependencies {     c ...

  9. [Leetcode Week15]Populating Next Right Pointers in Each Node

    Populating Next Right Pointers in Each Node 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/populati ...

  10. Linux内核堆栈使用方法 进程0和进程1【转】

    转自:http://blog.csdn.net/yihaolovem/article/details/37119971 目录(?)[-] 8 Linux 系统中堆栈的使用方法 81  初始化阶段 82 ...