原生 Android 项目嵌入 ReactNative

本贴最后更新于 2677 天前,其中的信息可能已经斗转星移

首先需要先安装环境 这里就直接引用官方文档地址了,如果没有配置环境的话,请先配置一下环境。

搭建开发环境

初始化项目##

使用 Android 新建项目 最低版本需要设置为 16 因为 RN 只支持最低版本为 16

打开CMD命令,切换到工程目录下面,执行npm init
这时候终端会提示输入一些内容。
name:工程名  (不能有大写  随意起就行了)
version:(版本号 这里回车默认就好了)
description:this is react native project(这里就是一个描述)
entry point:index.android.js(这是入口的js文件名)
test command:(回车使用默认值)
git repository:(输入git地址或者回车)
keywords:react native(关键词)
author:pencilso(作者)
license:(回车使用默认就好)

配置 package.json 文件

这时候你的项目根目录下应该有了一个 package.json 的文件,打开它,找到 scripts 这一栏,在 text 这个字段后面添加一个字段,"start": "node node_modules/react-native/local-cli/cli.js start" 贴一下完整的配置

{
      "name": "reactnative",
      "version": "1.0.0",
      "description": "no description",
      "main": "index.android.js",
      "scripts": {
                "test": "echo \"Error: no test specified\" && exit 1",
                "start": "node node_modules/react-native/local-cli/cli.js start"
      },
      "keywords": [
                "react",
                "native"
      ],
      "author": "pencilso",
      "license": "ISC"
}

这时候 JSON 文件已经配置好了,接下来该安装 React Native 了
使用终端 切换到工程目录下 执行 npm install --save react react-native
然后静静的等待好一会,就可以了,速度跟网络有关,如果没有设置阿里的镜像源的话,是需要科学上网才能安装的。
设置阿里镜像源请查看搭建开发环境

可选操作 :curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
在工程目录下终端执行,下载这个.flowconfig文件,如果你是windows系统,而且没有curl这个命令又想下载的话。
很简单,打开你的下载工具,比如说迅雷,粘贴这个地址https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
然后复制到迅雷里面新建任务,开始下载。如果下载下来的文件名不是.flowconfig的话,就需要重命名。
然而右键文件重命名是不行的,需要cmd命令  ren 旧文件名 新文件名  比如:ren a.txt .flowconfig
然后将该文件,复制到工程目录下即可。

配置 Android gradle

配置 RN 的依赖 打开工程下的 build.gradle 文件 找到 allprojects 这一栏 加入 maven 配置 。

allprojects {
    repositories {
        jcenter()
            maven {
            // All of React Native (JS, Android binaries) is installed from npm
            url "$rootDir/node_modules/react-native/android"
        }
    }
}

然后打开你的 Module 中的 build.gradle 文件

在dependencies里面添加RN依赖。
compile "com.facebook.react:react-native:+" // From node_modules.

然后找到android 这个配置里面 加入:
configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
找到defaultConfig这个配置 加上ndk支持  注意 一定要加:
ndk {
     abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
}
然后重新build一下

创建入口 Js 文件

在你的工程目录创建一个文件,即配置 package.json 的时候输入的入口 js 文件名

index.android.js 创建这个文件之后 把下面的代码粘贴进去就好了

'use strict';

import React from 'react';
import {
      AppRegistry,
      StyleSheet,
      Text,
      View
} from 'react-native';

class HelloWorld extends React.Component {
      render() {
    return (
          
        Hello, World
          
       )
  }
}
var styles = StyleSheet.create({
      container: {
        flex: 1,
        justifyContent: 'center',
      },
      hello: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
      },
});

AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

创建 React Native 界面

新建一个 Activity,我起名叫 ReactNativeActivity,用作 React Native 的界面。

需要注意一点 如果需要支持 5.0 以下的设备的话,需要继承 AppCompatActivity。

另外这个 Activity 需要设置一下主题:Theme.AppCompat.Light.NoActionBar

如果你的 Application 本身就是这个主题的话就不用动了,否则的话,这里在清单文件给 Activity 单独配置一下吧。

        android:name=".ReactNativeActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

直接贴 Activity 代码 在你的入口 Activity 写一个按钮使用 Intent 跳转到 ReactNativeActivity 即可

public class ReactNativeActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;
    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                //.setUseOldBridge(true) // uncomment this line if your app crashes
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);

        setContentView(mReactRootView);
    }
    @Override
    protected void onPause() {
        super.onPause();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostPause(this);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostResume(this, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostDestroy(this);
        }
    }

    @Override
    public void onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
            mReactInstanceManager.showDevOptionsDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}

有一点需要注意的是 Activity 中的代码

mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);

还有入口 js 中的代码

AppRegistry.registerComponent('HelloWorld', () => HelloWorld);

它们都有一个 HelloWorld 这其实就是一个名字,不过 Activity 和 js 当中需要对应。

配置 AndroidManifest##

首先配置一下权限
 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />
 
然后加入RN的设置Activity

        android:name="com.facebook.react.devsupport.DevSettingsActivity"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

基本上配置到这里就结束了,已经搭建完环境了。

Clean Project Rebuild Project 这两个都执行一下

接下来 打开终端 切换到工程目录,执行 npm start(如果你只是嵌入而不需要开发 RN 的话,就不需要 npm start 启动服务了)

当终端出现以下界面的时候,恭喜你,你可以点击 AS 上的运行按钮了。

配置 Bundle 通信

运行跳转到 RN 的界面的时候,我相信你这时候应该报了一个错误:

Could not get BatchedBridge, make sure your bundle is packaged correctly

如果没出现的话,就跳过这一步吧

打开终端 切换到项目目录 执行以下代码  注意:as默认创建的Module叫app,如果你的Module名字不叫app的话,需要将下面命令中的app改为你的Module名。
成功后会在你的assets下面创建两个文件 (index.android.bundle index.android.bundle.meta)
如果失败的话,尝试一下手动创建这两个空文件然后再执行命令。
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.0 的话,我相信你这时候应该崩溃了。

没有悬浮窗权限 需要在跳转到 ReactNative 之前进行一下权限判断

直接贴代码

@Override
public void onClick(View v) {
    if (Build.VERSION.SDK_INT >= 23) {
        if (!Settings.canDrawOverlays(this)) {
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
            startActivity(intent);
            return;
        }
    }
    startActivity(new Intent(this, ReactNativeActivity.class));
}

最后上一下运行效果图

RN 的坑,到此踩了一部分。好心塞。RN 的官方文档都感觉不太全,比如说强制依赖的配置没写,比如 RN 的生命周期方法名都改变了,然而官方文档还是旧的方法名,最后进入 ReactInstanceManager 类当中查看源码才发现生命周期的方法名。

  • React

    React 是 Facebook 开源的一个用于构建 UI 的 JavaScript 库。

    192 引用 • 291 回帖 • 417 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...