RN的Guide文檔詳細(xì)地介紹了整個(gè)過(guò)程,不過(guò)其中有些地方?jīng)]說(shuō)清楚硬贯,可能會(huì)給初學(xué)者埋下深坑。
開(kāi)發(fā)環(huán)境準(zhǔn)備
首先需要搭建開(kāi)發(fā)環(huán)境陨收,才能進(jìn)行后面的步驟饭豹。
添加JS環(huán)境
命令行,cd到app到根文件夾下(也可直接在android studio控制臺(tái)的Terminal下執(zhí)行)务漩,然后按順序執(zhí)行下列命令:
$npminit$npminstall --save react$npminstall --save react-native$curl-o .flowconfighttps://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
注意一:init命令記住name參數(shù)
init命令拄衰,需要填寫(xiě)諸如name、version等參數(shù)饵骨,輸入后按回車接著輸入下一個(gè)參數(shù)翘悉。init之后會(huì)生出package.json文件。name最為重要居触,工程名妖混,在后面的index.android.js和MyJReactActivity里都要用到。其它的都可以一路回車使用默認(rèn)值轮洋。
package.json
注意二:別忘了引入react
上面npm install --save react制市,下載react相關(guān)的資源包。原文里缺了這步命令弊予,最終導(dǎo)致App跑起來(lái)就crash祥楣,大概是這樣的:
java.lang.RuntimeException: Error: Requiring unknown module"react"(index.android.bundle:2)
注意三:添加start,Json格式
打開(kāi)剛生出的 package.json文件汉柒,在“scripts”內(nèi)添加“start”误褪,注意符合Json格式,逗號(hào)別忘了碾褂。
"scripts": {"test":"echo \"Error:notestspecified\" && exit 1","start":"node node_modules/react-native/local-cli/cli.js start"},
注意四:index.android.js里的name
按理說(shuō)init的時(shí)候已經(jīng)指定了“main”兽间,也就是index.android.js,可是沒(méi)有看到自動(dòng)生成的文件斋扰。我們可以手動(dòng)創(chuàng)建這份文件,名字就按照它給的來(lái)吧,作為hello world传货,我們照抄AwesomeProject的好了屎鳍。這里特別要注意的是,最后的AppRegistry.registerComponent问裕,第一個(gè)參數(shù)是前面package.json里設(shè)置的name逮壁,第二個(gè)參數(shù)是自定義的component。為什么是這樣粮宛,現(xiàn)在還沒(méi)去深究窥淆,到此為止,Js的環(huán)境就配置完成了巍杈,后面開(kāi)始Native部分的配置忧饭。
'use strict'importReactfrom'react';import{? AppRegistry,? StyleSheet,? Text,? View}from'react-native';classHelloWorldextendsReact.Component{? render() {return(Hello world!);? }}varstyles = StyleSheet.create({container: {flex:1,justifyContent:'center',? },hello: {fontSize:20,textAlign:'center',margin:10,? },});AppRegistry.registerComponent('rnapp', () => HelloWorld);
配置Native部分
gradle
app的gradle里添加react-native依賴
compile"com.facebook.react:react-native:+"http:// From node_modules
項(xiàng)目的gradle的repositories里添加url:
allprojects {? ? ? ? repositories {? ? ? ? jcenter()? ? ? ? ? ? ? ? ? ? maven {//AllofReact Native (JS, Android binaries)isinstalledfromnpmurl"$rootDir/node_modules/react-native/android"}? ? ? ? }}
添加權(quán)限
AndroidManifest.xml:
/**設(shè)置調(diào)試 的權(quán)限**/####添加RN的調(diào)試Activity:
我們剛開(kāi)始都是先用debug模式,以自己的開(kāi)發(fā)計(jì)算機(jī)作為服務(wù)器筷畦。那份index.android.js就是hello world界面词裤。手機(jī)在debug模式下從自己的計(jì)算機(jī)下載index頁(yè)面。下載的過(guò)程會(huì)有個(gè)提示的dialog鳖宾,顯示它需要上面的權(quán)限吼砂。6.0及以上的系統(tǒng),除了在Manifest里授權(quán)鼎文,還需要在系統(tǒng)設(shè)置里的“應(yīng)用”里的“在其他應(yīng)用的上層顯示”里渔肩,找到我們的應(yīng)用,勾選上允許拇惋。不同廠家的設(shè)置不太一樣周偎,我的是這樣的:
設(shè)置.png
如果沒(méi)有這些權(quán)限和設(shè)置,會(huì)拋這樣的異常:
android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W@fc0db15 -- permission deniedforthis window type
添加RN界面
MyReactActivity完整代碼如下蚤假。需要注意的是栏饮,
setUseDeveloperSupport可以直接設(shè)為true,在debug期間
mReactRootView.startReactApplication()的第二個(gè)參數(shù)磷仰,必須是package.json里的name
importandroid.app.Activity;importandroid.content.Context;importandroid.content.Intent;importandroid.os.Bundle;importcom.facebook.react.LifecycleState;importcom.facebook.react.ReactInstanceManager;importcom.facebook.react.ReactRootView;importcom.facebook.react.modules.core.DefaultHardwareBackBtnHandler;importcom.facebook.react.shell.MainReactPackage;/**
* Created by Byron on 16/9/6.
*/publicclassMyReactActivityextendsActivityimplementsDefaultHardwareBackBtnHandler{privateReactRootView mReactRootView;privateReactInstanceManager mReactInstanceManager;publicstaticvoidstartActivity(Context context){? ? ? ? Intent intent =newIntent(context, MyReactActivity.class);? ? ? ? context.startActivity(intent);? ? }@OverrideprotectedvoidonCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);? ? ? ? mReactRootView =newReactRootView(this);? ? ? ? mReactInstanceManager = ReactInstanceManager.builder()? ? ? ? ? ? ? ? .setApplication(getApplication())? ? ? ? ? ? ? ? .setBundleAssetName("index.android.bundle")? ? ? ? ? ? ? ? .setJSMainModuleName("index.android")? ? ? ? ? ? ? ? .addPackage(newMainReactPackage())? ? ? ? ? ? ? ? .setUseDeveloperSupport(true)? ? ? ? ? ? ? ? .setInitialLifecycleState(LifecycleState.RESUMED)? ? ? ? ? ? ? ? .build();? ? ? ? mReactRootView.startReactApplication(mReactInstanceManager,"rntest",null);? ? ? ? setContentView(mReactRootView);? ? }@OverrideprotectedvoidonResume(){super.onResume();if(mReactInstanceManager !=null){? ? ? ? ? ? mReactInstanceManager.onHostResume(this,this);? ? ? ? }? ? }@OverrideprotectedvoidonPause(){super.onPause();if(mReactInstanceManager !=null){? ? ? ? ? ? mReactInstanceManager.onHostPause();? ? ? ? }? ? }@OverrideprotectedvoidonDestroy(){super.onDestroy();if(mReactInstanceManager !=null){? ? ? ? ? ? mReactInstanceManager.onHostDestroy();? ? ? ? }? ? }@OverridepublicvoidonBackPressed(){super.onBackPressed();if(mReactInstanceManager !=null){? ? ? ? ? ? mReactInstanceManager.onBackPressed();? ? ? ? }else{super.onBackPressed();? ? ? ? }? ? }@OverridepublicvoidinvokeDefaultOnBackPressed(){super.onBackPressed();? ? }}
-運(yùn)行你的應(yīng)用
-還是在項(xiàng)目的根文件夾下袍嬉,命令行運(yùn)行如下命令,啟動(dòng)測(cè)試服務(wù)器灶平。
$npmstart
或者:
$ react-nativestart
npm start成功
回到Android Studio伺通,跟平常一樣,把App運(yùn)行起來(lái)逢享。如果要運(yùn)行在真機(jī)上罐监,要注意在設(shè)備上運(yùn)行的相關(guān)事項(xiàng)是否已經(jīng)做過(guò)。我的測(cè)試機(jī)是6.0點(diǎn)系統(tǒng)瞒爬,那每次連上usb弓柱,都需要先命令行運(yùn)行一次:
真機(jī)測(cè)試 記住一定要執(zhí)行
adbreversetcp:8081tcp:8081
然后再運(yùn)行app沟堡,否則手機(jī)無(wú)法連上測(cè)試服務(wù)器,會(huì)出現(xiàn)“紅屏”(添加了DevSettingsActivity的情況下)矢空。同樣航罗,如果測(cè)試服務(wù)器沒(méi)有開(kāi)啟,也會(huì)出現(xiàn)同樣的錯(cuò)誤屁药,也就是取不到打好包的js粥血,控制臺(tái)的crash log:
java.lang.RuntimeException: CouldnotgetBatchedBridge, make sure your bundleispackaged corr
========================報(bào)錯(cuò)解決辦法============================
如果出現(xiàn)32 64等.so包的報(bào)錯(cuò)
1.在build.gradle加入
android{? ...defaultConfig{? ? ? ? ? ? ...ndk{? ? ? ? ? ? abiFilters"armeabi","armeabi-v7a","x86","mips"}packagingOptions{? ? ? ? ? ? exclude"lib/arm64-v8a/librealm-jni.so"}? ? }
2.在gradle.properties尾部加入
Android.useDeprecatedNdk=true