Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在既有 Android 專案中嵌入 React Native 模組的完整流程

編輯:關於 Android 程式設計

React Native 已經進入了越來越多開發者的視野。身為一名原生開發者,我對 RN 也充滿好奇與期待。本文詳細說明如何把最新的 RN 模組嵌入一個既有的原生 Android App。

1. 事前準備

1. 一個既有的 Android 原生專案;
2. 已設定好的原生 Android 開發環境,以及 node.js 與 RN 環境;
3. 改造後的整體流程如下圖。

2. 開始改造

在原生專案的 app/build.gradle 中加入 React Native 依賴:

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

加入 .so 庫:

ndk {
    abiFilters "armeabi-v7a", "x86"
}

在專案根目錄的 build.gradle 中加入 maven 依賴:

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

在 app 目錄加入所需權限:

<uses-permission android:name="android.permission.INTERNET" />
<!-- 設定 debug 用的權限 -->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

3. 編寫原生的 React Native 模組

廢話不多說,直接上程式碼:

package com.allen.reactapp;

import android.app.Activity;
import android.os.Bundle;
import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

/**
 * 作者: allen on 16/7/31
 */
public class MyReactActivity extends Activity 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")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                /**
                 * 參考:https://stackoverflow.com/questions/37951246
                 * 除錯模式下建議直接寫成 true,我曾因為這個設定卡了兩天
                 */
                // .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setUseDeveloperSupport(true)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "myreactactivity", null);
        setContentView(mReactRootView);
    }

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

    @Override
    protected void onPause() {
        super.onPause();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onHostResume(this, this);
        }
    }

    @Override
    public void onBackPressed() {
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onBackPressed();
        } else {
            super.onBackPressed();
        }
    }
}

到這裡,Android 專案的 Activity 與設定檔就完成了最基本的配置。

4. 設定專案的 RN 開發環境

依序執行以下命令:

$ npm init

這個命令會建立 package.json,並提示輸入一些資訊,直接按 Enter 用預設值即可,不過 name 一定要是全英文小寫。

接著再依序執行:

$ npm install --save react
$ npm install --save react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

完成後,到專案目錄下修改 package.json,在 scripts 區塊加入:

"start": "node_modules/react-native/packager/packager.sh"

5. 建立 index.android.js

由於只是測試,直接沿用 FaceBook 的範例源碼:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';

class AwesomeProject extends Component {
    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>
                    Welcome to React Native!
                </Text>
                <Text style={styles.instructions}>
                    我是原生專案嵌入的 ReactNative
                </Text>
                <Text style={styles.instructions}>
                    Press Cmd+R to reload,{'\n'}
                    Cmd+D or shake for dev menu
                </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('myreactactivity', () => AwesomeProject);

注意:這裡註冊的入口名稱必須和原生端 startReactApplication() 傳入的字串保持一致,我這邊用的是 myreactactivity。

6. 執行你的混合 App

先確認前面所有步驟都沒有遺漏。在專案目錄下啟動開發伺服器:

react-native start

或者:

npm start

接著用 Android Studio 除錯執行 App。

常見錯誤與解法

Process: com.allen.reactapp, PID: 20469
java.lang.RuntimeException: java.util.concurrent.ExecutionException:
java.lang.RuntimeException: Could not connect to development server.
Try the following to fix the issue:
Ensure that the packager server is running
Ensure that your device/emulator is connected to your machine and has USB debugging enabled
- run 'adb devices' to see a list of connected devices
If you're on a physical device connected to the same machine,
run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device
If your device is on the same Wi-Fi network,
set 'Debug server host & port for device' in 'Dev settings'
    at com.facebook.react.ReactInstanceManagerImpl.createReactContext(...)

解法很直接:把 .setUseDeveloperSupport(true) 寫死。除錯階段建議就先寫成 true,省下大量排查時間。

簽名打包混合 App

1. 把 JS 檔打包進 bundle:

curl -k "https://localhost:8081/index.android.bundle" > reactapp/src/main/assets/index.android.bundle

執行成功後,應該能在 assets 目錄看到 index.android.bundle 檔。

2. 用 Android Studio 進行打包流程(作為一名 Android 老司機,這部分就不再細說了)。

原 Android 專案移植 React Native 的專案地址,請參考文末連結。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved