Android 继承 React Native 遇到的那些坑

开发环境准备

首先按照开发环境搭建教程来安装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的时候可能会有如下报错(坑一):

Error:Conflict with dependency 'com.google.code.findbugs:jsr305' in project ':app'. Resolved versions for app (3.0.0) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.

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中判断是否获得权限

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

运行你的应用

运行应用首先需要启动开发服务器(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
真是个悲伤地故事,跳转报错了。
《Android 继承 React Native 遇到的那些坑》
继续Google大法寻求帮助:
我们需要在module中新建一个assets目录,android studio为我们提供了非常方便的方式,一键搞定!
《Android 继承 React Native 遇到的那些坑》
然后我们在根目录的命令行执行如下命令:

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

这是为了把react native的代码打包到android的assets目录中,命令执行完毕之后,我们会发现assets目录中多了三个文件,
《Android 继承 React Native 遇到的那些坑》
这个就是我们react native的代码打包之后的样子,然后我们run app。
然后我们就会惊喜的发现APP成功运行起来啦!
《Android 继承 React Native 遇到的那些坑》

    原文作者:Android
    原文地址: https://juejin.im/entry/58ec9561ac502e006baf2d08
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞