React-Native移植-Android

Introduction

Reference link: Integrating with Existing Apps 

Due to the company's business needs, some modules need to transfer the native code to react-native , and since it is an existing project, I am here to port react-native to the project alone. I encountered some problems during the porting process, which are also recorded here. Down.

Some tutorial materials on the Internet are not very complete, and some key steps are not very detailed. Here we start from scratch.

There is also the environment configuration, which is not mentioned here, it is all very basic!

Create a new Android project

Here we create a new ReactNativeProject and initialize the directory structure as follows:

Introduce React-Native

Add react-native dependencies to build.gradle in your app directory, I added the latest version 0.20.1

compile 'com.facebook.react:react-native:0.20.1'

Then add the access network permission in AndroidManifest.xml . Of course, the project already has this permission. If you have this step, you can ignore it.

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

In order for the project to support debugging RN, you need to add RN's DevSettingsActivity in AndroidManifest.xml , as follows:

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

In this way, the real machine shakes the phone or clicks the Menu menu to open the relevant debugging page, as shown below:

After the deployment here, there is still a pit, that is, React-Native has requirements for the compiled version and the minimum compiled version. It requires the compileSdkVersion of the app's build.gradle file to be 23 and the minSdkVersion to be 16, because our project requires the minimum version to be 15. Even lower, it needs to be added in the AndroidManifest.xml of the app

<uses-sdk tools:overrideLibrary="com.facebook.react" />

Add basic Android native code and JS code

We create a new MyReactActivity and paste the complete code

public class MyReactActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler {

    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

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

        mReactRootView = (ReactRootView) findViewById(R.id.react_root);

        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, "ReactNativeProject", null);

    }

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


}

Because ReactRootView itself is a FrameLayout, I did not directly create a new one according to the official website, but put it directly into the layout activity_my_react.xml . The code is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.hhl.reactnativeproject.MyReactActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:gravity="center"
        android:text="我是本地控件TextView"
        android:textSize="20sp" />

    <com.facebook.react.ReactRootView
        android:id="@+id/react_root"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

It needs to be emphasized here that there are two methods in Activity, setBundleAssetName and setJSMainModuleName , among which setBundleAssetName indirectly calls setJSBundleFile , and setJSBundleFile is the key to the hot repair we will talk about later; and setJSMainModuleName sets the name of index.Android.js , This can change the directory location.

After the Android code is added, start adding the JS code. Here we add the index.android.js file and the package.json file to the project root directory, that is, our ReactNativeProject directory. The simple code of the index.android.js file is as follows:

'use strict';

import React, {
  Text,
  View
} from 'react-native';

class ReactNativeProject extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.hello}>Hello, World</Text>
        <Text>测试ReactNative</Text>
      </View>
    )
  }
}
var styles = React.StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
  },
  hello: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

React.AppRegistry.registerComponent('ReactNativeProject', () => ReactNativeProject);

The package.json code is as follows:

{
  "name": "ReactNativeProject",
  "version": "1.0.0",
  "description": "demo",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "author": "hanhailong",
  "license": "ISC",
  "dependencies": {
    "react": "^0.14.8",
    "react-native": "^0.24.1"
  }
}

Project configuration run and debug

Execute the following command in the ReactNativeProject directory

$ npm init
$ npm install --save react-native
$ curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

The npm init command does not need to be executed. If it is used to generate the package.json file, we have already created it before. After npm install –save react-native is executed, the node_modules folder will be generated under the directory and the npm dependency of react-native will be added.

First start the npm local service of RN:

$ npm start

After startup it is as follows:

npm start

In MainActivity, we add the code that jumps to MyReactActivity ,

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

Project structure diagram

Project running effect

Finally, we run the project, and the running effect is as follows:

Compilation problems you may encounter

Caused by: java.lang.IllegalAccessError: tried to access method android.support.v4.net.ConnectivityManagerCompat.:(Lcom/facebook/react/bridge/ReactApplicationContext;)V from class com.facebook.react.modules.netinfo.NetInfoModule

The version of appcompat of my project is 23.2.1, just change it to 23.0.1

compile 'com.android.support:appcompat-v7:23.0.1'

Demo download

ReactNativeProject

The next section explains the RN hot update

In the next section, we will explain the hot update of RN, so stay tuned! ! !

Transfer: http://blog.csdn.net/hanhailong726188/article/details/51236285

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326769833&siteId=291194637