編輯:關於 Android 程式設計
React Native 已經進入了越來越多開發者的視野。身為一名原生開發者,我對 RN 也充滿好奇與期待。本文詳細說明如何把最新的 RN 模組嵌入一個既有的原生 Android App。
1. 一個既有的 Android 原生專案;
2. 已設定好的原生 Android 開發環境,以及 node.js 與 RN 環境;
3. 改造後的整體流程如下圖。

在原生專案的 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" />
廢話不多說,直接上程式碼:
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 與設定檔就完成了最基本的配置。
依序執行以下命令:
$ 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"

由於只是測試,直接沿用 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。
先確認前面所有步驟都沒有遺漏。在專案目錄下啟動開發伺服器:
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,省下大量排查時間。
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 的專案地址,請參考文末連結。
自定義圓形漸變刻度進度條:Android 繪圖實戰
普通的圓形進度條到處都有,但只要加上漸變配色與刻度,質感就差很多。本文示範如何從零畫一個帶刻度、漸變色的圓環進度條。 一、畫出圓環 核心 API 是 drawArc:
Android TabHost 仿微信底部菜單實作
TabHost 是一個用來容納標籤頁的容器,它通常包含兩個部分:一個是顯示標籤的 TabWidget,另一個是用來顯示內容的 FrameLayout。早期 Android
仿斗魚滑動登錄驗證:自定義拼图驗證控件 DouYuView 實作
最近不太忙,閒暇時看看直播,總能撞見一些新奇的登錄驗證方式。恰好我也想熟悉一下新的開發工具 Android Studio,於是決定親手實現一個類似斗魚的滑動拼图驗證。
用 Intent 在 Activity 之間傳遞物件:Serializable 實作與生命週期全解
一、先回顧 Activity Activity 是 Android 最重要的元件之一,也是使用者與 App 互動的主要入口,概念上近似桌面程式的視窗。Android 應用