zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

RN集成到Android原生项目

2023-09-27 14:28:53 时间

最近一段时间比较忙,也没时间梳理下自己的学习笔记,隔了好久也不知道要整理些什么出来,刚好最近在整理下React Native相关的东东,所以在此记录下留作笔记使用。(在这就不描述Android项目和RN项目环境如何搭建了。)

一、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: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
     },
     welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
     },
     instructions: {
       textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
     },
    });   
    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(this, false);
     }
     
     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或者设备链接电脑的代理。


到此仅记录Android原生集成RN项目的方法,即初级技能,稍后整理下稍微升级点的技能,清单如下:

  1. Android原生与RN如何交互通信
  2. RN使用Android原生控件或自定义组件
  3. RN预加载实现
  4. React Native Linking与 Android原生页面路由跳转实现
  5. RN项目拆包和热更新



作者:闲庭CC
链接:https://www.jianshu.com/p/f546ad231382
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。