首页 {{menuItem.firstTitle}} {{menuItem.secondTitle}}

windows下android项目集成react native

2018年12月29日 131

一、安装环境

RN所需node和android环境即可

1.1下载安装node官网下载即可,安装和一般的exe程序一样安装简单,安装完成后会自动再path追加路径。

图片.png

我们可以输入node --version 验证是否安装成功以及查看版本号

图片.png

二、添加ReactNative到Android项目

1.新建Android原生项目命名ReactNative

2.配置ReactNative的js环境 进入到ReactNative的项目根目录,然后在终端输入:npm init 图片.png 然后依次回车默认即可

此步骤会在项目根目录生成package.jsonindex.js二个文件

image.png

3.将React、ReactNative添加到项目中 根目录输入npm install --save react react-native,回车后会下载相关依赖,生成node_modules文件夹

image.png

安装完成之后,我们再去配置.flowconfig,这个是对js代码做约束的,建议配置(也可以不配置)。 windows下新建.flowconfig文件(直接新建文件会提示文件名不能为空,可以通过命令行生成)

echo >.flowconfig

然后记事本编辑,然后把这个链接的文件内容复制到.flowconfig中

4.编辑index.js 在scripts标签下添加 ,"start": "node node_modules/react-native/local-cli/cli.js start"语句

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node node_modules/react-native/local-cli/cli.js start"
},

这时RN环境已经添加好了

三、添加ReactNative到Android项目

3.1添加ReactNative的依赖到你的app目录下的build.gradle中:

dependencies {


     // From node_modules.
    compile "com.facebook.react:react-native:+"
}

3.2配置项目根目录下的build.gradle:

allprojects {
    repositories {
        maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}
        maven {
            url "$rootDir/node_modules/react-native/android"
        }
        google()
        jcenter()
    }
}

注意如果不加maven{ url 'http://maven.aliyun.com/nexus/content/groups/public/'}阿里云镜像,可能会出现如下错误,因为被墙了

Error:Could not resolve all dependencies for configuration ':app:debugRuntimeClasspath'.
Could not determine artifacts for com.facebook.fresco:imagepipeline:1.10.0
Could not get resource 'https://jcenter.bintray.com/com/facebook/fresco/imagepipeline/1.10.0/imagepipeline-1.10.0.aar'.
Could not HEAD 'https://jcenter.bintray.com/com/facebook/fresco/imagepipeline/1.10.0/imagepipeline-1.10.0.aar'.
Remote host closed connection during handshake
SSL peer shut down incorrectly

3.3添加权限

<uses-permission android:name="android.permission.INTERNET"/>
/**设置调试 的权限**/
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" />

添加debug模式Activity(正式打包注释掉就好了)

<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>

3.4添加ReactNative界面

首先我们在项目根目录添加index.js,这个文件作为RN的入口文件

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('AndroidRnDemoApp', () => HelloWorld);

AppRegistry.registerComponent('AndroidRnDemoApp', () => HelloWorld);里面的AndroidRnDemoApp,这个作为接下来我们要绑定的activity的入口通道名。

原生页面作为入口

public class MainActivity extends AppCompatActivity {

    static final int OVERLAY_PERMISSION_REQ_CODE = 1000;
    private Button mBtnRn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initEvent();
    }

    private void initEvent() {
        initView();
        checkAppPermission();
    }

    private void initView() {
        mBtnRn = (Button) findViewById(R.id.btn_rn);
        mBtnRn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转RN页面
                Intent intent = new Intent(MainActivity.this, BaseRnActivity.class);
                startActivity(intent);
            }
        });
    }

    private void checkAppPermission() {
        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);
            }
        }
    }

    @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被拒绝
                }
            }
        }
    }
}

RN页面

public class BaseRnActivity extends Activity 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")
                .setJSMainModulePath("index")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();

        //这里的AndroidRnDemoApp必须对应“index.js”中的“AppRegistry.registerComponent()”的第一个参数
        mReactRootView.startReactApplication(mReactInstanceManager, "AndroidRnDemoApp", null);
        //加载ReactRootView到布局中
        setContentView(mReactRootView);
    }

    @Override
    public void invokeDefaultOnBackPressed() {
        super.onBackPressed();
    }


    /**
     * ReactInstanceManager生命周期同activity
     */

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

四、RN打离线包到Android

首先在项目app/src/main下面必须要创建一个assets目录,然后我们就开始打离线包啦: 根目录下运行

react-native bundle --platform android --dev false --entry-file index.js --bundle-output app/src/main/assets/index.android.bundle --assets-dest app/src/main/res/

此步骤会生成如下文件 image.png

如果提示'react-native' 不是内部或外部命令,也不是可运行的程序 或批处理文件。那么安装react-native-cli即可:

npm install -g react-native-cli

参照:Android项目集成ReactNative

转载请注明:原文链接 https://www.it399.com/article?id=55
相关文章 全部

扫一扫,体验小程序

线助手小程序
-
-
-
Copyright © 2017-2018 . All Rights Reserved.

粤ICP备18008506号