RN虽可以独立打成apk包作为独立应用,但目前更多情形是将其嵌入Native中。本文记录如何将RN集成到android(需要了解一点android知识噢)
1、新建Android Studio 工程为AndroidRnDemo
- 1、在根目录AndroidRnDemo下执行npm init 建立package.json并安装react react-native的依赖
npm init
npm install --save react react-native
- 2、修改package.json的scripts字段,新增start
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node node_modules/react-native/local-cli/cli.js start"
},
2、将ReactNative添加到Android项目
- 1、配置app目录下的build.gradle:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
api "com.facebook.react:react-native:+" //将RN相关库添加至Android依赖
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}
- 2、配置根目录下的build.gradle:
allprojects {
repositories {
google()
maven {
url "$rootDir/node_modules/react-native/android"
}
jcenter()
}
}
- 3、配置Android-Manifest.xml,添加权限
/**设置调试 的权限**/
<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要放在application内)
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity"/>
3、添加RN界面
- 1、在项目根目录下新建index.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('AndroidRnDemoApp', () => HelloWorld);
- 2、新建一个Activity作为RN界面的容器,命名为RNActivity
package com.example.com.androidrndemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactRootView;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.shell.MainReactPackage;
public class RNActivity 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")
.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);
}
}
- 3、在MainActivity中添加Intent跳转到RNActivity逻辑(button的点击触发)
package com.example.com.androidrndemo;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Intent intent = new Intent(MainActivity.this,RNActivity.class); //沟通两个activity的桥梁
startActivity(intent);
}
});
}
}
// layout_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.com.androidrndemo.MainActivity">
<Button android:id='@+id/button'
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:text="go RN Page"></Button>
</android.support.constraint.ConstraintLayout>
- 4、在Android-Manifest.xml中注册activity
<activity
android:name=".RNActivity"
android:theme="@style/Theme.AppCompat.Light.NoActionBar">
</activity>
4、打包、编译、安装、运行
4.1 本地开发
- 1、将RN编译到Android,并在模拟器上安装debug版apk包
gradlew build
gradlew installDebug
- 2、RN的调试、热更新
先启动Package提供服务
//先开启本地react native服务
npm start
然后在模拟器上打开应用,当点击button时,进入RN界面,此时需要设置本地ip和端口
window上“ctrl+M” 打开dev settings设置界面:
设置dev settings
-
3、开启热更新、实时刷新功能
image.png
注意:开启chrome远程调试时有时需先用google浏览器访问:你的ip:8081。
远程调试看不到RN界面,只能打断点和输出一些信息
远程调试
若是在真机上调试需执行:adb reverse tcp:8081 tcp:8081
4.2 、打包发布
- 1 、在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/
- 2、将RN编译进Android
gradlew assembleRelease
5、遇到过的崩溃问题
- 如果出现32 64等.so包的报错
// 1.在build.gradle加入
android {
...
defaultConfig {
...
ndk {
abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
}
packagingOptions {
exclude "lib/arm64-v8a/librealm-jni.so"
}
}
// 2.在gradle.properties尾部加入
Android.useDeprecatedNdk=true
网友评论