React Native嵌入到android原生应用

2017-07-28  本文已影响0人  偏北风23级

rn嵌入到iOS原生应用,有相应的demo支持,而安卓确没有,感觉非亲身的。那我们就只能靠自己一步一步的爬坑吧。
1.使用android studio创建HelloRN工程


2.在工程跟目录下创建package.json。
$npm init

3.创建了node_modules目录并把react和react-native下载到了其中。

$ npm install --save react react-native@0.46.4

安装react native0.46.4

从提示中可以看到,react-native0.46.4需要react 16.0.0-alpha.12.所以我们需要安装它。
$ npm i -S react@16.0.0-alpha.12

在终端运行完成后,再来打开package.json文件。
下面我们打开新创建的package.json文件,然后在其scripts字段中加入:

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

package.json文件如下所示:


4.在工程根目录下创建index.android.js。添加如下代码:


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

export default class HelloRN extends Component {
    render() {
        return (
            <Text> Hello world</Text>
        );
    }
}

AppRegistry.registerComponent('HelloRN', () => HelloRN);

5.在你的app中build.gradle文件中添加 React Native 依赖:

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

点击sync now,如果出现


请参考stackoverflow.com/questions/37347326/errorconflict-with-dependency-com-google-code-findbugsjsr305
6.在项目的build.gradle文件中为 React Native 添加一个 maven 依赖的入口

maven {
url"$rootDir/./node_modules/react-native/android" (⚠️:这里的路径一定要保持一致,否则会出现编译报错
}

7.在AndroidManifest.xml清单文件中声明网络权限:

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

8.添加原生代码MyReactActivity.java.

public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;
    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;

    @Override
    protected void onCreate(@Nullable 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();

        // 注意这里的HelloWorld必须对应“index.android.js”中的
        // “AppRegistry.registerComponent()”的第一个参数
        mReactRootView.startReactApplication(mReactInstanceManager, "HelloRN", null);

        setContentView(mReactRootView);

        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 permission not granted...
                }
            }
        }
    }

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

9.把MyReactActivity的主题设定为Theme.AppCompat.Light.NoActionBar

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

10.在MainActivity中增加一个button用来点击之后跳转到rn界面。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = (Button)findViewById(R.id.button);
        button.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                Intent intent = new Intent(MainActivity.this,MyReactActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }
}

11.在工程根目录下运行$npm start
12.Android Studio中启动项目。

上一篇下一篇

猜你喜欢

热点阅读