开发环境准备
首先按照开发环境搭建教程来安装React Native在安卓平台上所需的一切依赖软件(比如npm
)。
1. 打开现在Android项目
注意:react native支持最新sdk version 必须是16以上
2. 安装JavaScript依赖包
1. $ npm install
1. $ npm install
注意:安装的过程中可能会提示react版本不正确。(react-native对react的版本有严格要求,高于或低于某个范围都不可以。本文无法在这里列出所有react native和对应的react版本要求,只能提醒读者先尝试执行npm install,然后注意观察安装过程中的报错信息,例如require react@x.y.z版本, but none was installed
,然后根据这样的提示,执行npm i -S react@x.y.z版本
。如果你使用多个第三方依赖,可能这些第三方各自要求的react版本有所冲突,此时应优先满足react-native
所需要的react
版本。)
react版本不对解决方法:
执行命令:
yarn add react@16.0.0-alpha.12
2. npm install --save react react-native
2. npm install --save react react-native
注意:安装的过程中可能会forbidden 403
forbidden 403解决方法:
1.可能没设置npm镜像
yarn config set registry https://registry.npm.taobao.org --global
yarn config set disturl https://npm.taobao.org/dist --global
2.npm不是最新
查看当前版本 npm -v
查看最新版本号 npm info npm
安装最新 npm install npm@latest - g (@ 符号后面添加你查到的最新版本号)
3. 执行命令成功
把React Native添加到你的应用中
配置maven
在你的app中 build.gradle
文件中添加 React Native 依赖:
apply plugin: 'com.android.application' android { compileSdkVersion 25 buildToolsVersion "25.0.2" defaultConfig { applicationId "bluemoon.com.cn.reactnativeapp" minSdkVersion 16 targetSdkVersion 25 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" ndk { abiFilters "armeabi-v7a", "x86" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } configurations.all { resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9' } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support.constraint:constraint-layout:1.0.2' testCompile 'junit:junit:4.12' compile "com.facebook.react:react-native:+" // From node_modules. }
在项目的build.gradle添加maven依赖入口
buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.1.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { mavenLocal() jcenter() maven { // All of React Native (JS, Android binaries) is installed from npm url "$rootDir/node_modules/react-native/android" } } } task clean(type: Delete) { delete rootProject.buildDir }
修改package.json
{ "name": "reactnativeapp", "version": "1.0.0", "private": true, "scripts": { "start": "node node_modules/react-native/local-cli/cli.js start" }, "dependencies": { "react": "16.0.0-alpha.12", "react-native": "^0.46.4" } }
编写MyReactActivity类
package bluemoon.com.cn.reactnativeapp; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.KeyEvent; import com.facebook.react.ReactInstanceManager; import com.facebook.react.ReactPackage; import com.facebook.react.ReactRootView; import com.facebook.react.bridge.JavaScriptModule; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.common.LifecycleState; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.shell.MainReactPackage; import com.facebook.react.uimanager.ViewManager; import java.util.List; public class MyReactActivity 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(); // 注意这里的HelloWorld必须对应“index.android.js”中的 // “AppRegistry.registerComponent()”的第一个参数 mReactRootView.startReactApplication(mReactInstanceManager, "reactnativeapp", 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); } }
权限和声明
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="bluemoon.com.cn.reactnativeapp" > <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" > <activity android:name=".MainActivity" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" /><!--开发者菜单--> <activity android:name=".MyReactActivity" android:label="@string/app_name" android:theme="@style/Theme.AppCompat.Light.NoActionBar" /> </application> </manifest>
在根目录新建index.android.js,并添加react native组件
'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('reactnativeapp', () => HelloWorld);
修改MainActivity
如果你的应用会运行在Android 6.0(API level 23)或更高版本,请确保你在开发版本中有打开悬浮窗(overlay)权限
package bluemoon.com.cn.reactnativeapp; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.provider.Settings; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.txt_to_hello_world).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(MainActivity.this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, 1); return; } } Intent i = new Intent(MainActivity.this, MyReactActivity.class); startActivity(i); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 1) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (!Settings.canDrawOverlays(this)) { // SYSTEM_ALERT_WINDOW permission not granted... Toast.makeText(this, "error", Toast.LENGTH_SHORT).show(); return; } } } Intent i = new Intent(MainActivity.this, MyReactActivity.class); startActivity(i); } }
到这里就可以运行项目了!!!
还是有一点注意的是添加ndk,不然运行项目时会报错:
java.lang.UnsatisfiedLinkError: dlopen failed: "/data/data/bluemoon.com.cn.reactnativeapp/lib-main/libgnustl_shared.so" is 32-bit instead of 64-bit
app中 build.gradle 文件中添加
ndk { abiFilters "armeabi-v7a", "x86" }gradle.properties文件添加:
android.useDeprecatedNdk=true
最终集成运行结果如下:
打包APK
设置gradle变量生产签名密钥
$ keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000
设置gradle变量
signingConfigs { release { storeFile file('./my-release-key.keystore') storePassword "123456" keyAlias "my-key-alias" keyPassword "123456" } }buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' signingConfig signingConfigs.release } }
生成离线的jsbundle文件
$ react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/com/your-company-name/app-package-name/src/main/assets/index.android.bundle --assets-dest android/com/your-company-name/app-package-name/src/main/res/
生成发行APK包
gradle assembleRelease