Android項目集成ReactNative框架

ReactNative推出也有一段日子了,相信很多開發者都想體驗一下rn的強大功能,但是目前代碼都是基于native代碼的,如何加入ReactNative的代碼呢?本文將從簡單介紹下如何在已有工程的基礎上,新增ReactNative模塊。

準備條件

1.一個已有的、基于gradle構建的Android應用。
2.Node.js,參見開始使用React Native來了解相關的設置操作。
首先創建個Android工程,結構如下圖所示:


下面我們開始在這個原生android工程上進行改造,加入我們的ReactNative代碼。

在android/app/build.gradle文件中,添加React Native依賴:

// From node_modules

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

然后在android/build.gradle文件中(注意跟上面的路徑不同)加入本地React Native的maven目錄(現在React Native的所有組件,無論JS還是Android的預編譯包,都是通過npm分發的了):

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

最后在你的AndroidManifest.xml里增加Internet訪問權限:

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

添加原生代碼

你需要添加一些原生代碼來啟動React Native運行庫以及讓它渲染出東西來。我們接下來創建一個Activity和一ReactRootView
,然后在里面啟動一個React應用并把它設置為Activity的主要內容視圖。

public class MainActivity 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")
            .setJSMainModuleName("index.android")
            .addPackage(new MainReactPackage())
            .setUseDeveloperSupport(BuildConfig.DEBUG)
            .setInitialLifecycleState(LifecycleState.RESUMED)
            .build();
    mReactRootView.startReactApplication(mReactInstanceManager, "HelloRn", null);
    setContentView(mReactRootView);
}}

接下來,我們需要傳遞一些Activity的生命周期事件到ReactInstanceManager

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

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

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

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

我們還需要把Back按鈕事件傳遞給React native:

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

把JS代碼添加到你的應用

在你的工程根目錄,運行以下代碼:

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

上面的代碼會創建一個node模塊,然后react-native作為npm依賴添加。現在打開新創建的package.json文件然后在scripts字段下添加如下內容:

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

復制并粘貼下面的這段代碼到你工程根目錄下的index.android.js

 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Text,
StyleSheet,
View,
} from 'react-native';
class HelloRn extends Component {
render() {
return (
  <View style={styles.container}>
    <Text style={styles.hello}>Hello, World</Text>
  </View>
)
  }
}
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
  },
hello: {
fontSize: 20,
textAlign: 'center',
margin: 10,
  },
});
AppRegistry.registerComponent('HelloRn', () => HelloRn);

運行應用

為了運行應用,首先要啟動開發服務器。只需要在你的工程目錄下運行這段代碼:
$ npm start
現在來構建和運行你的Android應用(譬如./gradlew installDebug
)。一旦啟動了React Native制作的Activity,它應該會從開發服務器加載代碼并顯示:

661cbee9e9f91617aceab5e7a2fae49a.png

可能遇到的問題:

  1. Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.facebook.react:react-native:0.29.2]


    在mainfest配置如下參數即可:


  2. java.lang.UnsatisfiedLinkError: could find DSO to load: libreactnativejni.so


    在兩處添加配置:
    app#build.gradle

    defaultConfig {
     //...
     ndk {
         abiFilters "armeabi-v7a", "x86"
       }
     }
    

gradle.properties
android.useDeprecatedNdk=true

3.報錯信息如下:

Loading dependency graph, done.
error: bundling: UnableToResolveError: Unable to resolve module `react/lib/ReactDebugCurrentFrame` from `/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/Libraries/Renderer/src/renderers/shared/stack/reconciler/ReactCompositeComponent.js`: Module does not exist in the module map or in these directories:
  /Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/node_modules/react/lib
,   /Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react/lib
,   /Users/suwantao/node_modules/react/lib

This might be related to https://github.com/facebook/react-native/issues/4968
To resolve try the following:
  1. Clear watchman watches: `watchman watch-del-all`.
  2. Delete the `node_modules` folder: `rm -rf node_modules && npm install`.
  3. Reset packager cache: `rm -fr $TMPDIR/react-*` or `npm start --reset-cache`.
    at UnableToResolveError (/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/packager/src/node-haste/DependencyGraph/ResolutionRequest.js:488:5)
    at p.catch.error (/Users/suwantao/AndroidStudioProjects/ReactNativeDemo/react_native/node_modules/react-native/packager/src/node-haste/DependencyGraph/ResolutionRequest.js:366:19)
    at process._tickCallback (internal/process/next_tick.js:103:7)
Bundling `index.android.js`  84.3% (349/380), failed.
Paste_Image.png

解決方案:添加 react-native-material-design
react-native-material-design依賴react-native-material-design-styles ,如果他的父類是個全局的模塊,則不能被React Native's bundler打包。

參考The development server returned response error code: 500 in react native

執行npm install react-native-material-design 如果報錯,

Paste_Image.png

根據提示,執行:npm install --save react@16.0.0-alpha.6
安裝成功之后再次執行npm install react-native-material-design即可。
4.詭異的問題


image.png

解決方案:
app/build.gradle (將 'com.android.support:appcompat-v7:xx.x.x' 改為 'com.android.support:appcompat-v7:23.0.1')

5.undefined is not an object (evaluating ‘ReactInternals.ReactCurrentOwner’)

IMG_1603.JPG

解決方案:
參考:https://github.com/facebook/react-native/issues/13874
由于本地沒安裝yarm,無法直接調用 yarn add react@16.0.0-alpha.12在package.json手動填入"react": "16.0.0-alpha.12"也沒解決問題。
最后通過一個熱心網友解決了該問題。方案如下:
在項目根目錄輸入 npm install 然后 npm start ,問題完美解決。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,908評論 6 541
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,324評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,018評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,675評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,417評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,783評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,779評論 3 446
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,960評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,522評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,267評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,471評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,009評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,698評論 3 348
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,099評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,386評論 1 294
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,204評論 3 398
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,436評論 2 378

推薦閱讀更多精彩內容

  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,715評論 25 708
  • afinalAfinal是一個android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,474評論 2 45
  • https://github.com/niyingxunzong/AndroidOpenSourceProject...
    奈何心善閱讀 10,634評論 6 223
  • 迭代器模式: 提供一種方法順序訪問一個聚合對象中的各個元素,而又不暴露其內部的表示。 比如說,現在我們有兩個聚合對...
    ghwaphon閱讀 1,508評論 0 5
  • 2017.02.13 星期一 晴 開學第一天,今天作業少,孩子早早把作業做完,老師沒布置的作業也提前做了。 這...
    漳州宸媽閱讀 165評論 0 0