大佬教程收集整理的这篇文章主要介绍了Android原生项目集成React Native的方法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
开发环境准备
首先按照开发环境搭建教程来安装React Native在安卓平台上所需的一切依赖软件(比如npm)。
在项目的根目录中运行:
$ 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"
{ "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 依赖:
然后Sync的时候可能会有如下报错(坑一):
Google一下解决方案,我们需要在app的build.gradle中添加如下代码:
编译完美通过!哈哈~
在项目的 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 中声明:
想要通过原生代码调用 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") .setJsmainModul@R_607_8371@("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:" + getPackag@R_607_8371@())); 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,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,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
真是个悲伤地故事,跳转报错了。
继续Google大法寻求帮助:
我们需要在module中新建一个assets目录,android studio为我们提供了非常方便的方式,一键搞定!
然后我们在根目录的命令行执行如下命令:
这是为了把React Native的代码打包到android的assets目录中,命令执行完毕之后,我们会发现assets目录中多了三个文件,
这个就是我们React Native的代码打包之后的样子,然后我们run app。
然后我们就会惊喜的发现APP成功运行起来啦!
但是
到这里并没有结束,我们试着摇晃一下手机,开启传说中的debug设置对话框,但是好像并没有反应,难道是摇晃的力度不够?我们使出吃奶的力气摇晃手机,还是没卵用~而且有的同学可能已经发现了,我们刚才用的是官方的打包命令,才完成了app的显示。也就是说我们现在用的是app内部的代码,而不是我们本地node服务上的代码。
这个就是官方教程的一个坑,我们回到初始化activity的地方,修改一点点代码。
mReactRootView = new ReactRootView(this); mReacTinstanceManager = ReacTinstanceManager.builder() .setApplication(getApplication()) .setBundleAssetName("index.android.bundle") .setJsmainModul@R_607_8371@("index.android") .addPackage(new MainReactPackage()) // .setUseDeveloperSupport(BuildConfig.DEBUG) //开发者支持,BuildConfig.DEBUG的值默认是false,无法使用开发者菜单 .setUseDeveloperSupport(true) //开发者支持,开发的时候要设置为true,不然无法使用开发者菜单 .seTinitialLifecycleState(LifecycleState.RESUMED) .build(); // 注意这里的react-example必须对应“index.android.js”中的 // “AppRegistry.registerComponent()”的第一个参数 mReactRootView.startReactApplication(mReacTinstanceManager,"peoplus",null);
setUseDeveloperSupport方法并没有起作用,因为这个Config.DEBUG默认值为false,所以这个地方我们手动写成true。我们这个时候重新run一遍程序,发现非常完美。到此结束。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
以上是大佬教程为你收集整理的Android原生项目集成React Native的方法全部内容,希望文章能够帮你解决Android原生项目集成React Native的方法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。