android 添加React Native支持更新版

时间:2022-04-27
本文章向大家介绍android 添加React Native支持更新版,主要内容包括前言、环境搭建、集成步骤、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

前言

之前已经写过了有关React Native移植原生Android项目的文章,不过因为RN版本更新的原因吧,跟着以前的文章可能会出现一些问题,对于初学者来讲还是会有很多疑难的困惑的,这里针对最新的版本做一个新的讲解。

环境搭建

官方文档

英文官方文档 中文官方文档

集成步骤

用android studio创建一个基本的android hello world程序。

在项目根目录中通过npm向导生成package.json文件,在cmd中输入命令:

npm init

在package.json文件中添加启动脚本:

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

注:这里可能会报一个json的错误,请仔细检查json。附上我本地的实例:

{
  "name": "shopping",
  "version": "0.0.1",
  "description": "shopping",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "author": "xiangzhihong",
  "license": "ISC",
  "dependencies": {
    "react": "^15.4.2",
    "react-native": "^0.40.0"
  }
}

添加react-native npm依赖,在命令行输入:

npm install react react-native --save

创建index.android.js文件,也可以从之前的项目中拷贝。

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

在你app的build.gradle文件中添加react native依赖库。

compile "com.facebook.react:react-native:+"

在你project的build.gradle文件中添加react native路径。

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

注:这里可能报一个错误,兼容的问题:

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

解决方法:在你的app(应用程序的build.gradle中添加下面的配置脚本,不是项目的那个build.gradle)。

configurations.all {
    resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}

修改AndroidManifest.xml文件中添加权限:

<uses-permission android:name="android.permission.INTERNET" />

添加AndroidReactActivity:

package com.rn.shopping;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;

import com.facebook.react.LifecycleState;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;

import static com.facebook.react.common.ApplicationHolder.getApplication;


public class AndroidReactActivity 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")
                .setJSMainModuleName("index.android")
                .addPackage(new MainReactPackage())
                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloWorld", null);


        setContentView(mReactRootView);
    }


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


    @Override
    protected void onPause() {
        super.onPause();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onPause();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onResume(this, this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mReactInstanceManager != null) {
            mReactInstanceManager.onDestroy();
        }
    }

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

build android,如果报错,请自行检查错误原因。 将AndroidReactActivity加入AndroidManifest.xml文件中:

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

将DevSettingsActivity配置加入到AndroidManifest.xml文件中:

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

最终完整的AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.platform.ourplam.androidreacttest">

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".AndroidReactActivity"
            android:label="@string/app_name"
            android:theme="@style/Theme.AppCompat.Light.Dialog">
        </activity>
        <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
    </application>

</manifest>

在MainActivity中添加Button,添加点击事件启动AndroidReactActivity作为我们的测试。

 Intent intent = new Intent(MainActivity.this, AndroidReactActivity.class);
                startActivity(intent);

最后我们使用命令启动npm就好了:

npm start

注:如果你遇到下面的问题,这是由于不兼容的问题,需要将编译环境改一下:

Method 'void android.support.v4.NET.ConnectivityManagerCompat.()' is inaccessible to class 'com.facebook.react.modules.netinfo.NetInfoModule'

解决方法:

com.android.support:appcompat-v7:23.0.1

附:https://cloud.tencent.com/developer/article/1035990 https://cloud.tencent.com/developer/article/1035975