本文由 愛學園平臺 進行聯合編輯整理輸出
原作者:愛學園——莫比烏斯環
如果你正準備從頭開始制作一個新的應用,那么React Native會是個非常好的選擇。但如果你只想給現有的原生應用中添加一兩個視圖或是業務流程,React Native也同樣不在話下。只需簡單幾步,你就可以給原有應用加上新的基于React Native的特性、畫面和視圖等。
1.核心概念
這里把React Native組件植入到Android應用中有如下幾個主要步驟:
- 首先要了解你要植入的React Native組件。
- 在Android項目根目錄中使用npm來安裝
react-native
,這樣同時會創建一個node_modules/
的目錄。 - 創建js文件,編寫React Native組件的js代碼。
- 在
build.gradle
文件中添加com.facebook.react:react-native:+
,以及一個指向node_nodules/
目錄中的react-native
預編譯庫的maven
路徑。 - 創建一個React Native專屬的
Activity
(可混合使用),在其中再創建ReactRootView
。 - 生成對應
bundle
文件,啟動React Native的Packager服務,運行應用。 - 接下來可自由發揮,添加更多的React Native組件。
- 在真機上運行、調試(這里需要先更新
bundle
文件)。 - 打包。
2.開發環境準備
此處可參考我寫的另一篇文章React Native環境搭建,(已有環境的,此處可選擇跳過).
3.添加JS代碼管理
- 在項目的根目錄運行以下命令:
$ npm init
$ npm install --save react react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
此時可在Android項目根目錄下看到如下文件/文件夾:node_modules/
、package.json
- 打開
package.json
文件,在scripts
屬性下添加如下字段:
"start": "node node_modules/react-native/local-cli/cli.js start"
- 在根目錄下新建js文件夾(存放React Native相關組件),index.android.js(RN啟動文件)。
主要啟動代碼如下:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import {AppRegistry} from 'react-native';
import AwesomeProject from './js/AwesomeProject'
//注冊(只要一遍)
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
4.添加App開發準備操作
- 在你app的
build.gradle
文件內添加React Native
相關依賴:
compile 'com.facebook.react:react-native:+' // From node_modules.
- 在你工程
build.gradle
文件內添加本地React Native
maven庫:
allprojects {
repositories {
jcenter()
maven {
// All of React Native (JS, Android binaries) is installed from npm
url "$rootDir/node_modules/react-native/android"
}
}
}
<font color='red'>注意事項:這里的url路徑要寫對,否則將出現如下錯誤:
“Failed to resolve: com.facebook.react:react-native:0.x.x" errors after running Gradle sync in Android Studio.
</font>
-
AndroidManifest.xml
清單文件配置
- 如果你需要訪問React Native的DevSettingsActivity,則需要注冊
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
5.準備工作搞定:接下來添加原生代碼
- 純React Native頁面主要代碼(底部有完整代碼地址)
package com.itingchunyu.reactnative.view;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.appcompat.BuildConfig;
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;
/**
* Created by liyanxi on 2016/12/13.
* Copyright (c) itingchunyu@163.com. All rights reserved.
*/
public class MyReactActivity 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")//根目錄下index.android.js文件
.addPackage(new MainReactPackage())//如果為true,則會啟用諸如JS重新加載和調試之類的開發人員選項.反之打包
.setUseDeveloperSupport(true)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
//'AwesomeProject'==>index.android.js 頁面內注冊名稱,可根據自己隨意調整
mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", null);
setContentView(mReactRootView);
}
@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 boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
mReactInstanceManager.showDevOptionsDialog();
return true;
}
return super.onKeyUp(keyCode, event);
}
@Override
public void invokeDefaultOnBackPressed() {
super.onBackPressed();
}
}
- 原生和RN混合頁面主要代碼(底部有完整代碼地址):
package com.itingchunyu.reactnative.view;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.appcompat.BuildConfig;
import android.widget.LinearLayout;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.shell.MainReactPackage;
import com.itingchunyu.reactnative.R;
/**
* Created by liyanxi on 2016/12/13.
* Copyright (c) itingchunyu@163.com. All rights reserved.
*/
public class HybridActivity extends AppCompatActivity {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
private LinearLayout layoutReactContainer;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
mReactRootView = new ReactRootView(this);
mReactInstanceManager = ReactInstanceManager.builder()
.setApplication(getApplication())
.setBundleAssetName("index.android.bundle")
.setJSMainModuleName("index.android")
.addPackage(new MainReactPackage())
//如果為true,則會啟用諸如JS重新加載和調試之類的開發人員選項.反之打包
.setUseDeveloperSupport(true)
.setInitialLifecycleState(LifecycleState.RESUMED)
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", null);
layoutReactContainer= (LinearLayout) findViewById(R.id.layout_react);
layoutReactContainer.addView(mReactRootView);
}
}
6.配置權限保證開發過程中紅屏錯誤能正確展示
如果您的應用程式指定的Android API等級為23或更高,請確定您已為開發版本啟用了重疊權限。您可以使用“設置”進行檢查。 canDrawOverlays(this);.這在開發版本中是必需的,因為反應本地開發錯誤必須顯示在所有其他窗口之上。由于在API級別23中引入了新的權限系統,用戶需要批準它。這可以通過將下面的代碼添加到onCreate()方法中的Activity文件來實現。 OVERLAY_PERMISSION_REQ_CODE是類的一個字段,它負責將結果傳遞回Activity。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
}
}
最后,必須覆蓋onActivityResult() 方法(如下面的代碼所示)來處理一致性UX的權限接受或拒絕的情況。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!Settings.canDrawOverlays(this)) {
// SYSTEM_ALERT_WINDOW permission not granted...
}
}
}
}
7.應用飛起來
- 啟動服務器
React packager
$npm start(配合package.json文件
start
)
或者
$react-native start
- 啟動App應用(看效果)
- 調試過程踩過的坑
啟動ReactNative相關Activity頁面崩潰
解決方案看代碼截圖:
<font color='red'> 此處紅框內需要注意開發調試過程需要設置為true動態加載,false涉及到靜態bundle文件,下面打包會單獨講。</font>
8.在Android Studio中打包apk
你也可以使用Android Studio來打包!You can use Android Studio to create your release builds too! It’s as easy as creating release builds of your previously-existing native Android app. There’s just one additional step, which you’ll have to do before every release build. You need to execute the following to create a React Native bundle, which’ll be included with your native Android app:
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/
<font color='red'>上面主要意思是說在打包前不可避免的操作如下:</font>
1.在根目錄下執行上述命令,生成
React Native Activity頁面bundle文件
,此處注意路徑不要寫錯(這里是在./app/src/main/assets/
目錄下生成對應index.android.bundle
文件)2.遠程bundle文件(用于動態更新,這里暫不詳解)