查看原文
其他

RN集成到Android原生项目实践

闲庭CC 刘望舒 2022-06-30

作者:闲庭CC
https://www.jianshu.com/p/f546ad231382

一、Android项目集成RN

1.新建普通Android项目
新建一个普通的Android项目即可,打开Android Studio -> File -> New -> New Project… 按步骤执行即可。

2.在项目根目录下引入React Native模块
在AS中的Terminal中输入npm init ,输入一些项目的描述属性(默认一路回车也行),为了生成·文件的项目描述,根据提示来填写就好了,生成的json文件内容大致如下:

{
      "name""rnappdemo",
      "version""1.0.0",
      "description""test",
      "main""index.js",
      "scripts": {
        "start""node node_modules/react-native/local-cli/cli.js start",
        "test""no"
      },
      "repository": {
        "type""git",
        "url""no"
      },
      "keywords": [
        "no"
      ],
      "author""liu",
      "license""ISC",
      "dependencies": {
        "react""^16.5.2",
        "react-native""^0.55.4"
      }
    }

3.引入rn的一些模块文件

npm install --save react react-native

会在根目录生成一个node_modules文件夹,存的是RN的一些模块文件,如果在这个过程中出现require react@某.某.某版本, but none was installed ,那么就使用命令
npm i -S react@某.某.某版本//此处为提示的版本号.
注意:如何安装React Native指定版本,命令如:npm install --save react-native@0.55.4 ,这里建议使用因为最新版本使用可能会出错,稍微比新版低个版本,我这里没用最新版,使用的是0.55.4。
如何查看当前rn版本信息:npm info React-native

4.引入.flowconfig文件

方法一:.flowconfig文件可以从facebook的github上复制,然后在工程的根目录创建.flowconfig文件,将其内容复制进去即可。
方法二:在Terminal中执行以下命令:

curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

5.接下来打开package.json文件,在scripts模块下添加,如上步骤2显示。
"start": "node node_modules/react-native/local-cli/cli.js start"

6.在项目根目录下的build.gradle添加以下配置

allprojects {
      repositories {
          jcenter()
          maven {
              url "https://maven.google.com"
          }
          maven {
              // All of React Native (JS, Android binaries) is installed from npm
              url "$rootDir/node_modules/react-native/android"//此处目录请额外注意
          }
      }
  }

7.在app下的build.gradle -> dependencies 添加以下依赖:

compile "com.facebook.react:react-native:+" // From node_modules.

同时在android -> defaultConfig 中添加
ndk{ abiFilters "armeabi-v7a","x86"}
完整如下:

   defaultConfig {
            applicationId "com.liujc.rnappdemo"
            minSdkVersion 16
            targetSdkVersion 27
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            ndk{
                abiFilters "armeabi-v7a","x86"
            }
        }

8.在 AndroidManifest.xml 清单文件中声明网络权限:

<uses-permission android:name="android.permission.INTERNET" />

如果需要访问 DevSettingsActivity 界面(即开发者菜单),则还需要在 AndroidManifest.xml 中声明:

<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

二、编写RN代码运行到Android项目中

1.在根目录下创建index.android.js文件:

'use strict';
import React, { Component } from 'react';
import {
 AppRegistry,
 StyleSheet,
 Text,
 NativeModules,
 View,
 ToastAndroid,
 DeviceEventEmitter
from 'react-native';
let title = 'React Native界面';

class reactNative extends Component {

/**加载完成*/
componentWillMount() {
  let result = NativeModules.MyNativeModule.Constant;
  console.log('原生端返回的常量值为:' + result);
}

/**
* 原生调用RN
*/

componentDidMount() {
   DeviceEventEmitter.addListener('nativeCallRn',(msg)=>{
        title = "React Native界面,收到数据:" + msg;
        ToastAndroid.show("发送成功", ToastAndroid.SHORT);
   })
}
render() {
return (
  <View style={styles.container}>
    <Text style={styles.welcome} >
        {title}
    </Text>

    <Text style={styles.instructions}>
      To get started, edit index.android.js
    </Text>

    <Text style={styles.instructions}>
      Double tap R on your keyboard to reload,{'\n'}
      Shake or press menu button for dev menu
    </Text>

    <Text style={styles.welcome}>
      我是RN界面!
    </Text>
  </View>

);
 }
}
const styles = StyleSheet.create({
 container: {
flex1,
justifyContent'center',
alignItems'center',
backgroundColor'#F5FCFF',
 },
 welcome: {
fontSize20,
textAlign'center',
margin10,
 },
 instructions: {
   textAlign'center',
color'#333333',
marginBottom5,
 },
});   
AppRegistry.registerComponent('reactNative', () => reactNative);

2.在Terminal中执行启动命令
npm run start 或者 yarn start//默认启动端口为8081,后面会描述如何修改端口号.
启动完成后出现如下界面:

┌──────────────────────────────────────────────   ────────────────────────────────┐
│                                                                              │
│  Running Metro Bundler on port 8081.                                         │
│                                                                              │
│  Keep Metro running while developing on any JS projects. Feel free to   

│  close this tab and run your own Metro instance if you prefer.               │
│                                                                              │
│  https://github.com/facebook/react-native                                    │
│                                                                              │
└──────────────────────────────────────────────────────────────────────────────┘

Looking for JS files in
E:\workspace\WsForRN\RNAppDemo\RNAppDemo

Metro Bundler ready.

Loading dependency graph, done.

然后在浏览器中输入http://localhost:8081/index.android.bundle 访问没有报错,则说明启动成功.

3.在Application里面添加如下代码:

public class AppApplication extends Application implements ReactApplication {
 private static AppApplication instance;
 @Override
 public void onCreate() {
     super.onCreate();
     instance = this;
     SoLoader.init(thisfalse);
 }

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

 /**
  * 获取Application实例
  */

 public static AppApplication getInstance() {
     return instance;
 }
 @Override
 public ReactNativeHost getReactNativeHost() {
     return mReactNativeHost;
 }
}

4.在对应Activity中添加如下代码:

public class MyRNActivity extends ReactActivity {
 @Override
 protected String getMainComponentName() {
     return "reactNative";//此处容器名要与index.android.js里面注册的控件名一致
 }
}

5.记得把Application和对应的Activity在AndroidManifest.xml中注册使用。运行APP即可加载RN界面。
备注:设备要和服务端在同一局域网下调试,即链接同一WiFi或者设备链接电脑的代理。

— — — END — — —

推荐文章

知乎 Android 客户端组件化实践

Flutter最佳入门方式:写一个计算器

Groovy快速入门看这篇就够了

Android 性能优化最佳实践

Android输入系统的事件传递流程和IMS的诞生


Android进阶和面试必备的书籍

《Android进阶解密》已在京东、当当、天猫等商场全面开售。本书基于Android8.0,将系统源码和应用开发结合讲解,帮助读者融会贯通,破解Android应用开发进阶秘密。具体见:破解Android进阶奥秘!《Android进阶解密》已出版(文末送签名书)


您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存