少停
>
Android和React-Native的简单交互
首先在Android原生中.新建class文件TransMissonMoudle:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 /** * Created by shaotingzhou on 2018/3/7. */ package com.androidrn.RN; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Promise; 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.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.text.SimpleDateFormat; import java.util.Date; import javax.annotation.Nullable; public class TransMissonMoudle extends ReactContextBaseJavaModule { private static final String REACT_CLASS = "TransMissonMoudle"; private ReactContext mReactContext; public TransMissonMoudle(ReactApplicationContext reactContext) { super(reactContext); this.mReactContext = reactContext; } @Override public String getName() { return REACT_CLASS; } //延迟0.1秒获取时间。 @ReactMethod public void getTime() { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } String time = getTimeMillis(); WritableMap writableMap = new WritableNativeMap(); writableMap.putString("key", time); sendTransMisson(mReactContext, "EventName", writableMap); } }).start(); } private String getTimeMillis() { SimpleDateFormat formatDate = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss"); Date date = new Date(System.currentTimeMillis()); String time = formatDate.format(date); return time; } /** * RCTDeviceEventEmitter方式 * * @param reactContext * @param eventName 事件名 * @param params 传惨 */ public void sendTransMisson(ReactContext reactContext, String eventName, @Nullable WritableMap params) { reactContext .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } /** * CallBack方式 * * @param name * @param callback */ @ReactMethod public void callBackTime(String name, Callback callback) { callback.invoke(getTimeMillis()); } /** * Promise方式 * @param name * @param promise */ @ReactMethod public void sendPromiseTime(String name, Promise promise) { WritableMap writableMap=new WritableNativeMap(); writableMap.putString("age","20"); writableMap.putString("time",getTimeMillis()); promise.resolve(writableMap); } }
再建class文件TransMissonPackage:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 package com.androidrn.RN; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.JavaScriptModule; 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 shaotingzhou on 2018/3/7. */ public class TransMissonPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { List<NativeModule> modules = new ArrayList<>(); modules.add(new TransMissonMoudle(reactContext));//摇一摇 return modules; } // @Override // public List<Class<? extends JavaScriptModule>> createJSModules() { // return Collections.emptyList(); // } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { List<ViewManager> viewManagerList=new ArrayList<>(); // viewManagerList.add(new PTRRefreshManager()); return viewManagerList; } }
接着在MainApplication里引入TransMissonPackage,加入包. 如 import com.androidrn.RN.TransMissonPackage;
new TransMissonPackage()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 package com.androidrn; import android.app.Application; import com.androidrn.RN.TransMissonPackage; import com.facebook.react.ReactApplication; 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 TransMissonPackage() ); } @Override protected String getJSMainModuleName() { return "index"; } }; @Override public ReactNativeHost getReactNativeHost() { return mReactNativeHost; } @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); } }
我的文件放置情况如图:
然后只需要在RN这边:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 /** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, {Component} from 'react'; import { AppRegistry, StyleSheet, Text, View, DeviceEventEmitter, NativeModules, ToastAndroid, Platform } from 'react-native'; const instructions = Platform.select({ ios: 'Press Cmd+R to reload,\n' + 'Cmd+D or shake for dev menu', android: 'Double tap R on your keyboard to reload,\n' + 'Shake or press menu button for dev menu', }); type Props = {}; export default class App extends Component<Props> { componentWillMount() { DeviceEventEmitter.addListener('EventName', function (msg) { console.log('DeviceEventEmitter收到消息'+msg); alert('DeviceEventEmitter收到消息'+ msg.key) }); } render() { return ( <View style={styles.container}> <Text style={styles.welcome} onPress={this.getDeviceEventEmitterTime.bind(this)} > RCTDeviceEventEmitter获取时间 </Text> <Text style={styles.welcome} onPress={this.getCallBackTime.bind(this)} > CallBack获取时间 </Text> <Text style={styles.welcome} onPress={this.getPromiseTime.bind(this)} > Promise获取时间 </Text> </View> ); } getDeviceEventEmitterTime() { NativeModules.TransMissonMoudle.getTime(); } getCallBackTime() { NativeModules.TransMissonMoudle.callBackTime("Allure", (msg) => { console.log('callBack:---' + msg); alert('callBack:---'+msg) } ); } getPromiseTime() { NativeModules.TransMissonMoudle.sendPromiseTime("Allure").then(msg=> { console.log("年龄:" + msg.age + "/n" + "时间:" + msg.time); alert("年龄" + msg.age + "时间" + msg.time) this.setState({ age: msg.age, time: msg.time, }) }).catch(error=> { console.log('错误' + error); }); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, });
源码
效果图: