開發環境準備
首先按照開發環境搭建教程來安裝React Native在安卓平臺上所需的一切依賴軟件(比如npm)。
在應用中添加JS代碼
在項目的根目錄中運行:
$ npm init$ npm install --save react react-native$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig
npm init創建了一個空的node模塊(其實就是創建了一個package.json描述文件),而npm install則創建了node_modules目錄并把react和react-native下載到了其中。至于第三步curl命令,其實質是下載.flowconfig配置文件,這個文件用于約束js代碼的寫法。這一步非必需,可跳過。下面我們打開新創建的package.json文件,然后在其scripts字段中加入:
"start": "node node_modules/react-native/local-cli/cli.js start"
現在你的package.json內容應該類似這樣:
{ "name": "react-example", "version": "1.0.0", "description": "this is my first react example", "main": "index.js", "scripts": {  "test": "echo /"Error: no test specified/" && exit 1",  "start": "node node_modules/react-native/local-cli/cli.js start" }, "keywords": [  "react",  "android",  "example" ], "author": "max", "license": "ISC", "dependencies": {  "react": "^15.4.2",  "react-native": "^0.42.3" }}接下來在項目根目錄中創建index.android.js文件,然后將下面的代碼復制粘貼進來:
'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}>Hello, World</Text>   </View>  ) }}var styles = StyleSheet.create({ container: {  flex: 1,  justifyContent: 'center', }, hello: {  fontSize: 20,  textAlign: 'center',  margin: 10, },});AppRegistry.registerComponent('react-example', () => HelloWorld);準備工作
在你的app中 build.gradle 文件中添加 React Native 依賴:
dependencies {   ...   compile "com.facebook.react:react-native:+" // From node_modules. }然后Sync的時候可能會有如下報錯(坑一):
Google一下解決方案,我們需要在app的build.gradle中添加如下代碼:
android {  configurations.all {    resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'  }}編譯完美通過!哈哈~
在項目的 build.gradle 文件中為 React Native 添加一個 maven 依賴的入口,必須寫在 “allprojects” 代碼塊中:
allprojects {  repositories {    ...    maven {      // All of React Native (JS, Android binaries) is installed from npm      url "$rootDir/../node_modules/react-native/android"    }  }  ...}正常情況下項目的build.gradle文件和node_modules目錄都是在根目錄下面,所以需要把
url "$rootDir/../node_modules/react-native/android"改為url "$rootDir/node_modules/react-native/android"
接著,在 AndroidManifest.xml 清單文件中聲明網絡權限:
<uses-permission android:name="android.permission.INTERNET" />
如果需要訪問 DevSettingsActivity 界面,也需要在 AndroidManifest.xml 中聲明:
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
添加原生代碼
想要通過原生代碼調用 React Native ,就像這樣,我們需要在一個 Activity 中創建一個 ReactRootView 對象,將它關聯一個 React application 并設為界面的主視圖。
如果你想在安卓5.0以下的系統上運行,請用 com.android.support:appcompat 包中的 AppCompatActivity 代替 Activity 。
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")        .addPackage(new MainReactPackage())        .setUseDeveloperSupport(BuildConfig.DEBUG)        .setInitialLifecycleState(LifecycleState.RESUMED)        .build();    // 注意這里的react-example必須對應“index.android.js”中的    // “AppRegistry.registerComponent()”的第一個參數    mReactRootView.startReactApplication(mReactInstanceManager, "react-example", null);    setContentView(mReactRootView);  }  @Override  public void invokeDefaultOnBackPressed() {    super.onBackPressed();  }  @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();    }  }  @Override  public void onBackPressed() {    if (mReactInstanceManager != null) {      mReactInstanceManager.onBackPressed();    } else {      super.onBackPressed();    }  }  @Override  public boolean onKeyUp(int keyCode, KeyEvent event) {    if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {      mReactInstanceManager.showDevOptionsDialog();      return true;    }    return super.onKeyUp(keyCode, event);  }}注意這里的react-example必須對應“index.android.js”中的“AppRegistry.registerComponent()”的第一個參數,以及package.json中的name屬性保持一致
我們需要把 MyReactActivity 的主題設定為 Theme.AppCompat.Light.NoActionBar ,因為里面有許多組件都使用了這一主題。
<activity android:name=".MyReactActivity" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.Light.NoActionBar"> </activity>
配置權限以便開發中的紅屏錯誤能正確顯示
如果你的設備版本在23及以上,你需要確認你的APP是否具有overlay permission
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中判斷是否獲得權限
@Overrideprotected 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...      }    }  }}運行你的應用
運行應用首先需要啟動開發服務器(Packager)。你只需在項目根目錄中執行以下命令即可:
$ npm start
你可以把你的MyReactActivity作為launchActivity,直接啟動,或者從別的Activity跳轉過去都可以,現在你只需要run app,下面貼出我的MainActivity的代碼
public class MainActivity extends AppCompatActivity {  private static final int OVERLAY_PERMISSION_REQ_CODE = 0x1111;  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    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);      }    }    findViewById(R.id.text1).setOnClickListener(new View.OnClickListener() {      @Override      public void onClick(View v) {        Intent intent = new Intent(MainActivity.this, MyReactActivity.class);        startActivity(intent);      }    });  }  @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...        }      }    }  }}界面中只有一個TextView,點擊跳轉到MyReactActivity
真是個悲傷地故事,跳轉報錯了。
	
繼續Google大法尋求幫助:
我們需要在module中新建一個assets目錄,android studio為我們提供了非常方便的方式,一鍵搞定!
	
然后我們在根目錄的命令行執行如下命令:
這是為了把react native的代碼打包到android的assets目錄中,命令執行完畢之后,我們會發現assets目錄中多了三個文件,
	
這個就是我們react native的代碼打包之后的樣子,然后我們run app。
然后我們就會驚喜的發現APP成功運行起來啦!
	
但是
	到這里并沒有結束,我們試著搖晃一下手機,開啟傳說中的debug設置對話框,但是好像并沒有反應,難道是搖晃的力度不夠?我們使出吃奶的力氣搖晃手機,還是沒卵用~而且有的同學可能已經發現了,我們剛才用的是官方的打包命令,才完成了app的顯示。也就是說我們現在用的是app內部的代碼,而不是我們本地node服務上的代碼。
	這個就是官方教程的一個坑,我們回到初始化activity的地方,修改一點點代碼。
mReactRootView = new ReactRootView(this);mReactInstanceManager = ReactInstanceManager.builder()    .setApplication(getApplication())    .setBundleAssetName("index.android.bundle")    .setJSMainModuleName("index.android")    .addPackage(new MainReactPackage())//        .setUseDeveloperSupport(BuildConfig.DEBUG) //開發者支持,BuildConfig.DEBUG的值默認是false,無法使用開發者菜單    .setUseDeveloperSupport(true)        //開發者支持,開發的時候要設置為true,不然無法使用開發者菜單    .setInitialLifecycleState(LifecycleState.RESUMED)    .build();// 注意這里的react-example必須對應“index.android.js”中的// “AppRegistry.registerComponent()”的第一個參數mReactRootView.startReactApplication(mReactInstanceManager, "peoplus", null);setUseDeveloperSupport方法并沒有起作用,因為這個Config.DEBUG默認值為false,所以這個地方我們手動寫成true。我們這個時候重新run一遍程序,發現非常完美。到此結束。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答