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

實戰:如何把 React Native 嵌入原生 Android 應用

編輯:關於 Android 程式設計

原生應用並非只能整屏跳轉到 RN 頁面,也可以把 RN 組件當作一個普通控件嵌進原生界面,成為其中的一部分。本文記錄完整的接入過程,以及一路上遇到的各類報錯與解法。

第一部分:把 RN 接入 Android

步驟一:初始化工程與依賴

用 Android Studio 新建項目(本文示例名為 RnInAndroid),然後打開命令行終端進入項目根目錄。

執行:

npm init

會生成 package.json,也就是 RN 的配置文件,過程中按需填寫信息。

輸入 yes 確認後,安裝 RN 依賴:

npm install --save react react-native

這會联网下載 node_modules 組件庫。接著下載 flow 配置:

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

打開剛生成的 package.json,在 "scripts" 裡 "test" 那一行末尾補一個逗號(JSON 格式要求),然後新增啟動腳本:

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

步驟二:編寫 index.android.js

在項目根目錄新建 index.android.js,寫入一個最簡單的 RN 頁面(Text 組件相當於 Android 的 TextView):

'use strict';

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

class HelloWorld extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.hello}>這就是 RN 的頁面哦</Text>
        <Text style={styles.hello}>我是劉成</Text>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  hello: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

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

步驟三:配置兩個 build.gradle

打開 app/build.gradle,在 dependencies 塊中加入:

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

再打開項目根目錄的 build.gradle(注意這是另一個文件),在 allprojects 下的 repositories 中新增 maven 源:

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

步驟四:添加網絡權限

在 app/src/main/AndroidManifest.xml 的 manifest 標籤內、與 application 同級處加入:

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

步驟五:編寫承載 RN 的 Activity

在項目包路徑下新建 MyReactActivity.java:

package com.example.vittorio.rninandroid;

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;

/**
 * Created by vittorio on 2016/10/14.
 */
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())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
        setContentView(mReactRootView);
    }

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

幾點注意:

  • 用 Android Studio 的話,先 Build > Clean Project,然後按 Alt + Enter 逐個導入缺失的包。
  • 第一行 package 要換成你自己的包名,與 AndroidManifest.xml 中 package 屬性一致。
  • startReactApplication 的第二個參數必須與 index.android.js 中 AppRegistry.registerComponent 的第一個參數一致。

步驟六:處理依賴衝突

若出現如下錯誤:

Error: Conflict with dependency 'com.google.code.findbugs:jsr305'.
Resolved versions for app (3.0.0) and test app (2.0.1) differ.

在根目錄 build.gradle 的 android 代碼塊中加入:

configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
}

之後 Build > Rebuild Project 重新編譯。

步驟七:注册 Activity 並補全生命週期

在 AndroidManifest.xml 中注册 MyReactActivity,並為它指定一個主題(例如 Theme.AppCompat.Light.NoActionBar,避免標題欄遮擋)。

在 MyReactActivity 中補上生命週期方法:

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

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

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

// 把返回鍵事件交給 React Native 處理
@Override
public void onBackPressed() {
    if (mReactInstanceManager != null) {
        mReactInstanceManager.onBackPressed();
    } else {
        super.onBackPressed();
    }
}

默認情況下搖一搖設備才能調出調試菜單,模擬器上不方便,因此還要攔截菜單鍵(Android Studio 模擬器按 Ctrl + M 可觸發):

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

步驟八:加入跳轉入口並啟動服務

在 MainActivity 的布局中加一個按鈕,點擊後跳轉到 MyReactActivity。

在命令行啟動 Node 服務:

npm start

打開模擬器(筆者用 Genymotion,你也可以用 AS 自帶模擬器或真機),點擊 Run。

第二部分:一路踩過的坑

坑 1:點擊跳轉後直接閃退

E/AndroidRuntime: FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window
-- permission denied for window type 2003

解法是補上懸浮窗相關權限:

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

坑 2:IllegalAccessError

java.lang.IllegalAccessError: Method 'void android.support.v4.net.ConnectivityManagerCompat.<init>()' is inaccessible to class 'com.facebook.react.modules.netinfo.NetInfoModule'

這在 RN 社區也有大量報告。解法是調整三處配置:

  • .gitignore 中加入 node_modules/ 與 npm-debug.log
  • app/build.gradle 中把 com.android.support:appcompat-v7 降為 23.0.1
  • gradle.properties 末尾加上 android.useDeprecatedNdk=true

坑 3:undefined is not a function (evaluating 'remoteModules.forEach')

原因是 maven 的 url 路徑寫錯了。$rootDir 本身就指向項目根目錄,多寫一層 ../ 會找不到 node_modules:

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

坑 4:找不到 onPause / onResume / onDestroy

Error:(52, 34) 錯誤: 找不到符號 符號: 方法 onPause()
位置: 類型為ReactInstanceManager的變量 mReactInstanceManager

這通常是 RN 版本與接入方式不匹配導致的。筆者當時的解法是把這三個方法註釋掉,編譯即可通過。

坑 5:Ctrl + M 調不出調試菜單

在 AndroidManifest.xml 中為該 Activity 補齊相應配置即可恢復。

第三部分:把 RN 當作普通控件嵌入

注意 MyReactActivity 裡其實就是一句 setContentView(mReactRootView)。也就是說,只要把 mReactRootView 塞進任意一個普通布局容器,RN 就變成了一個控件。

做法一:代碼中 addView

新建 myreactactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:background="#6638"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="上半部分是 android 的布局"
        android:textSize="30sp" />

    <LinearLayout
        android:id="@+id/ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
@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)
            .build();
    mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);
    setContentView(R.layout.myreactactivity);
    initView();
}

private void initView() {
    ll = (LinearLayout) findViewById(R.id.ll);
    ll.addView(mReactRootView);
}

做法二:直接在 XML 中聲明 ReactRootView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:background="#6638"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:text="上半部分是 android 的布局"
        android:textSize="30sp">

        <com.facebook.react.ReactRootView
            android:id="@+id/rnview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </TextView>
</LinearLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myreactactivity);

    // 已在布局中聲明,無需 new,直接取出即可
    mReactRootView = (ReactRootView) findViewById(R.id.rnview);

    mReactInstanceManager = ReactInstanceManager.builder()
            .setApplication(getApplication())
            .setBundleAssetName("index.android.bundle")
            .setJSMainModuleName("index.android")
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();

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

至此,RN 頁面已經和原生布局和平共處在一屏之內。剩下的問題是:RN 頁面如何返回原生頁面、Android 的物理返回鍵又該如何與 RN 的路由協調——這留待下一篇處理。

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