混合开发之Android原生调用ReactNative方法

首先这篇过程和上一篇混合开发之Android原生加载ReactNative页面的大部分步骤都是一样的
首先还是大概的讲一下流程:
1、Androidstudio新建Android项目,命令行执行npm init,把项目初始化成RN项目
2、执行npm install –save react react-native 安装react和react-native,这里要注意一下react-native的版本问题,在使用0.56.0版本的时候,项目编译会出问题,建议使用其他版本,比如0.55.4
3、Android目录下的build.gradle引入

dependencies {
    compile "com.facebook.react:react-native:+"
        ...
}

Project目录下的build.gradle引入

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            //这里要注意路径 不要写错!!!切记
            url "$rootDir/node_modules/react-native/android"
        }
    }

}

添加完之后,项目先编译一遍
4、在Project目录下新建index.android.js以及App.js文件,编写ReactNative代码
5、在Project目录下的scr/main中新建assets文件夹,并且在命令行中输入(每次RN文件有变动都需要重新执行)一下命令

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res

6、然后在MainActivity中编码(具体看后面的代码)

下面看具体步骤:
1、初始化 npm init
并且在生成的package.json文件中添加下面一行

"start": "node node_modules/react-native/local-cli/cli.js start"

修改完的package.json

{
  "name": "hydemo2",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^16.4.2",
    "react-native": "^0.55.4"
  }
}

2、安装react和指定版本的react-native
这里安装react-native0.55.4版本是因为最新的0.56.0版本会出问题,最后还是需要降级

npm install --save react-native@0.55.4
npm install --save react

3、Android目录下的build.gradle引入

dependencies {
    compile "com.facebook.react:react-native:+"
        ...
}

Project目录下的build.gradle引入

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            //这里要注意路径 不要写错!!!切记
            url "$rootDir/node_modules/react-native/android"
        }
    }

}

4、在Project目录下新建index.android.js文件,编写ReactNative代码

/** @format */

import {AppRegistry} from 'react-native';
import App from './App';

AppRegistry.registerComponent("hydemo090304", () => App);

编辑App.js代码

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 * @flow
 */

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ToastAndroid, DeviceEventEmitter, Button} 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',
});

export default class App extends Component<Props> {


    constructor(props) {
        super(props);
        this.state = {
            info: "嘟嘟嘟嘟"
        }
    }

    componentWillMount() {
    //注册接收器
        this.testDataListener = DeviceEventEmitter.addListener('testData', e => {//for Android
            ToastAndroid.show(e.data, 2000);
            //更新状态及其他操作
             。。。。
        });
    }


    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>{this.state.info}</Text>
                <Text style={styles.instructions}>To get started, edit App.js</Text>
                <Text style={styles.instructions}>{instructions}</Text>

            </View>
        );
    }


}

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,
    },
});

5、在Project目录下的scr/main中新建assets文件夹,并且在命令行中输入

react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res

6、编辑Android代码

package com.android.sjq.hydemo090304;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.devsupport.DoubleTapReloadRecognizer;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.shell.MainReactPackage;

public class MainActivity extends AppCompatActivity {


    private Button mButton;
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;
    private ReactContext reactContext;
    private DoubleTapReloadRecognizer mDoubleTapReloadRecognizer;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mDoubleTapReloadRecognizer = new DoubleTapReloadRecognizer();
        mButton = (Button) findViewById(R.id.button);
        mButton.setOnClickListener(mOnClickListener);
        mReactRootView = (ReactRootView) findViewById(R.id.react_view);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        // 这个"App1"名字一定要和我们在index.js中注册的名字保持一致AppRegistry.registerComponent()
        mReactRootView.startReactApplication(mReactInstanceManager, "hydemo090304", null);
    }


    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            WritableMap params = Arguments.createMap();
            params.putString("data", "AAAA");
            sendEvent(getReactContext(), "testData", params);
        }
    };

    private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
        if (reactContext == null) {
            return;
        }
        reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class).emit(eventName, params);
    }

    private ReactContext getReactContext() {
        return reactContext != null ? reactContext : mReactInstanceManager != null ? mReactInstanceManager.getCurrentReactContext() : null;
    }
}

xml代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sendMsgToRN"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <com.facebook.react.ReactRootView
        android:id="@+id/react_view"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_below="@+id/button">

    </com.facebook.react.ReactRootView>

</RelativeLayout>

完事 运行 看效果
这里写图片描述

还有一个Android和RN混合开发的demo,需要的可以下载参考,demo包含了
1、Android加载RN页面
2、Android调用RN函数
3、RN调用Android函数
传送门

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值