在Android项目中植入React Native

一、植入

  1. 用Android Studio新建一个Android项目:MixAndroid
  2. 使用命令行工具进入到MixAndroid项目根目录
  3. 执行以下代码:
$ npm init
$ npm install --save react react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

若有类似npm WARN [email protected] requires a peer of [email protected] but none was installed.的提示,则执行相应的代码:npm install --save [email protected]

  1. 执行完以上命令后,在根目录会出现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. 在项目根目录中创建index.android.js文件,然后将下面的代码复制粘贴进来:
>```
  'use strict';
import React from 'react';
import {
  Text,
  View,
  StyleSheet,
  AppRegistry
} from 'react-native';
class MyAwesomeApp extends React.Component {
  render() {
    return (
      
        Hello, World
      
    )
  }
}
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文件夹所在的目录有关
8. 在Android项目的`AndroidManifest `文件中添加如下代码:
  * 网络权限:
  * 界面声明:
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 `文件中添加该界面:

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

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

#二、运行
1. 启动服务器:在根目录下执行该命令:

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)

你可能感兴趣的:(在Android项目中植入React Native)