安卓原生app嵌入React-Native

本文的记录适合已经按照 React-Native 中文网搭建好环境并且能够成功运行 Hello World 的 React-Native 原生项目的同学。文末会放上 github 的地址。

各种环境的搭建参照 React-Native中文网,环境搭建好后就可以开始了。

1. 打开 AS ,新建一个原生项目,这里项目名为 RNDemo

2.在 AS 终端中输入命令

npm init

接下来按照提示输入对应信息,有的可以不填,如图:

安卓原生app嵌入React-Native_第1张图片
这里写图片描述

**这里注意,名字不能有大写字母!

初始化完成后就会在项目根目录下生成一个 package.json 文件。打开文件,在 scripts{} 里添加如下部分,用于之后启动 packager:

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

**注意两行之间要有逗号。

文件整体如下:

{
  "name": "rnapp",
  "version": "1.0.0",
   "description": "This is my first RN-App!",
   "main": "index.android.js",
   "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node node_modules/react-native/local-cli/cli.js start"
   },
   "author": "yq",
   "license": "ISC"
 }

2. 终端输入命令:

npm install --save react react-native

有一个等待的过程,完成后会在项目根目录下生成一个 node_modules 文件夹,文件夹里的内容就是执行命令所下载的,如图所示:

安卓原生app嵌入React-Native_第2张图片
node_modules

但是终端会有一些警告,如图:

安卓原生app嵌入React-Native_第3张图片
这里写图片描述

按照提示安装对应版本,命令如下:

npm install --save [email protected] [email protected]

3. 在项目根目录 build.gradle 文件的 allprojects{} (注意是:allprojects 里)添加如下地址:

maven{
        url "$rootDir/node_modules/react-native/android"
     }

添加完后是这样的:

allprojects {
repositories {
    jcenter()
    maven{
        url "$rootDir/node_modules/react-native/android"
    }
  }
}

然后在 app 目录下的 build.gradle 里添加依赖:

compile 'com.facebook.react:react-native:+'

同步项目,会报如下的错误:

Error:Conflict with dependency 'com.google.code.findbugs:jsr305' in project ':app'. Resolved versions for app (3.0.0) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

在 app/bulid.gradle 文件的 android{} 模块里添加

 configurations.all {
    //for Error:Conflict with dependency 'com.google.code.findbugs:jsr305'
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}

同步项目,上面的问题解决了,但是又有新的错误,如下:

Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.facebook.react:react-native:0.47.2]
C:\Users\yinqi.android\build-cache\1db15acba046d1d8bc220e7717d1e2ffd328aad6\output\AndroidManifest.xml

这个还是能看的明白的,最低版本不能低于16,那我们就修改最低支持版本为16,修改后在同步项目 ok 了。

解决了错误,还要确认下下载到的 react-native 依赖包的版本是否是 0.47.2,如果不是 0.47.2 而是0.20.1,说明上面的 maven 地址配置的可能有问题。

3. 在项目根目录下新建 index.android.js (这里的文件名要和第一步输入的那个package name 对应的名字一样)文件,加入如下代码:

'use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';
//hello world 对应代码
class HelloWorld extends React.Component {
  render() {
    return (
      
        Hello, World!\nThis is my first rnApp!
      
    )
  }
}
var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  hello: {
    fontSize: 20,
    color:'red',
    textAlign: 'center',
    margin: 10,
  },
});
//这里的 rnapp 可以和项目的名字不一样
AppRegistry.registerComponent('rnapp', () => HelloWorld);

4. 新建用于加载 index.android.js 的 Activity,要实现 DefaultHardwareBackBtnHandler 接口,代码如下:

package com.yq.rndemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

public class RNActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

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

        mReactRootView = new ReactRootView(this);
        mReactInstanceManager = ReactInstanceManager.builder()
                .setApplication(getApplication())
                .setBundleAssetName("index.android.bundle")//bundle 的名字
                .setJSMainModuleName("index.android")//js 文件的名字
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(true)//开发者模式
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "rnapp", null);

        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }

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

5. 添加权限并注册 RN 的设置界面, manifest文件如下:









    
        
            

            
        
    
    
    
    

最后在 MainActivity 中加入跳转到 RNActivity 的按钮,原生项目嵌入 React-Native 就完成了,接下来就是运行项目看是否能成功。

5.首先启动 package server ,命令如下:

npm start

看到 Loading dependency graph, done. 就是启动成功了。

然后安装 app 到手机,命令如下:

gradlew installDebug

运行 app 跳转到 RNActivity 界面,有时候可能不会显示,这时候就要配置调试端口再 Reload了,直接 Reload 会提示:

安卓原生app嵌入React-Native_第4张图片
这里写图片描述

端口配置步骤如下:

手机菜单(Menu)按键 --> Dev Setting --> Debugging 下的 Debug server host & port for device,点击输入 192.168.1.xxx:8081 就可以了。

** 注:手机要和电脑在同一局域网下。

这时候返回点击手机菜单键再次 Reload 就可以了;如果不行,返回重新进入页面。

6.另外需要注意的两点

(1)调试需要悬浮窗权限,如果 app target设置为 23 以上,手机系统版本为 6.0 以上并且没有动态申请权限的话,一定要记得手动开启悬浮窗权限;

(2)在调试过程中 packger 必须要保证运行状态,否则进行 Reload 操作的时候会报错误,如图:

安卓原生app嵌入React-Native_第5张图片
packger没有运行报错

补充:加载 index.android.js 的 Activity 的另一种写法:

1. 继承 ReactActivity ,重写 getMainComponentName 方法,返回值为 js 文件中注册的名字(demo 中为 ‘rnapp’),代码如下:

package com.yq.rndemo;

import com.facebook.react.ReactActivity;

public class MyReactActivity extends ReactActivity {

    @Override
    protected String getMainComponentName() {
        return "rnapp";
    }
}

(2) 自定义 Application 类,实现 ReactApplication 接口(上面那种方法不需要),否则会报错:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yq.rndemo/com.yq.rndemo.MyReactActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to com.facebook.react.ReactApplication

具体代码如下:

package com.yq.rndemo;

import android.app.Application;

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;

/**
 * Created by yinqi on 2017/8/31.
 */

public class RNApplication extends Application implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List getPackages() {
            return Arrays.asList(
                    new MainReactPackage()
            );
        }

    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, /* native exopackage */ false);
    }
}

(3)不要忘了在 manifest 中注册:




    
    
    

    
        android:name=".RNApplication"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
            
                

                
            
        
        
        
        
        
        
        
    


最后,打正式包:

首次在 app/src/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/

以上过程是我一边操作一边记录下来的,尽可能地详细说明了步骤,过程中肯定会遇到其他问题,这就需要耐心慢慢解决了。如果有说的不对的地方,请指正!

GitHub Demo,node-modules文件夹由于过大没有上传,请自行下载

你可能感兴趣的:(安卓原生app嵌入React-Native)