在Android項目中植入React Native

一、植入

  1. 用Android Studio新建一個Android項目:MixAndroid
  2. 使用命令行工具進入到MixAndroid項目根目錄
  3. 執(zhí)行以下代碼:
$ npm init
$ npm install --save react react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

若有類似npm WARN react-native@0.45.1 requires a peer of react@16.0.0-alpha.12 but none was installed.的提示,則執(zhí)行相應(yīng)的代碼:npm install --save react@16.0.0-alpha.12

  1. 執(zhí)行完以上命令后,在根目錄會出現(xiàn)package.json文件,打開文件,在script屬性下添加:

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

> 如圖:![WechatIMG5.jpeg](http://upload-images.jianshu.io/upload_images/1006564-c310d256e2a9bb9c.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
> 注意:文件中的`name`后的值只能是小寫字母,并且請留意它,之后會用到

5. 在項目根目錄中創(chuàng)建index.android.js文件,然后將下面的代碼復(fù)制粘貼進來:
>```
  'use strict';
import React from 'react';
import {
  Text,
  View,
  StyleSheet,
  AppRegistry
} from 'react-native';
class MyAwesomeApp 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('mixandroid', () => MyAwesomeApp);

注意:此處最后一行的mixandroid即為package.json中name的屬性值

  1. app目錄下的build.gradle文件中添加依賴:
 dependencies {
     ...
     compile "com.facebook.react:react-native:+" // From node_modules.
 }
  1. 在工程目錄的build.gradle文件中添maven目錄

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

>注意:`"$rootDir/node_modules/react-native/android"`目錄和你node_modules文件夾所在的目錄有關(guān)
8. 在Android項目的`AndroidManifest `文件中添加如下代碼:
  * 網(wǎng)絡(luò)權(quán)限:<uses-permission android:name="android.permission.INTERNET" />
  * 界面聲明:<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
9. 添加原生代碼:

package com.example.jsnow.mixandroid;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.os.Bundle;
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;

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
private int OVERLAY_PERMISSION_REQ_CODE = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    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);
        }
    }


    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, "mixandroid", 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
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);
}


@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...
            }
        }
    }
}

}

注意:`mReactRootView.startReactApplication(mReactInstanceManager, "mixandroid", null);`這行里面用的也是`mixandroid`
10. 在`AndroidManifest `文件中添加該界面:

<activity
android:name=".MyReactActivity"
android:label="@string/app_name"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>

注意:主題模式是`Theme.AppCompat.Light.NoActionBar`

#二、運行
1. 啟動服務(wù)器:在根目錄下執(zhí)行該命令:

npm start


2. 在Android Studio中運行該App

#三、效果


![WechatIMG6.jpeg](http://upload-images.jianshu.io/upload_images/1006564-f7890789345f4fc5.jpeg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容