美文网首页
react native 项目 和android 项目的整合

react native 项目 和android 项目的整合

作者: 人生吴平坦路V5 | 来源:发表于2019-01-17 18:08 被阅读0次

    前提是要将环境搭配 好搭建开发环境

    参考了一下 官网的东西嵌入到现有原生应用坑还是比较多的 可能是没有  写将 已有的react native 项目 和已有的android 项目整合吧

    在RN项目根目录中 运行 npm install 命令 下载 node_modules 文件夹 如果有了就不需要 运行了

    如果后面报错的话可以 删除 node_modules 文件夹 再在RN项目根目录中 运行 npm install  命令 试试

    1. 将RN项目根目录下面android文件夹下面的 文件都删除

    2.将你android项目根目录下面的文件复制 RN项目根目录下面android文件夹下

    3. 将android app build.gradle 文件的        minSdkVersion  最低修改到minSdkVersion 16

    4 在项目的 build.gradle 文件添加  maven {

                // All of React Native (JS, Android binaries) is installed from npm

                url "$rootDir/../node_modules/react-native/android"

            }

    记住要在 allprojects  中 如下:

    allprojects {

        repositories {

            google()

            jcenter()

    //有多个的的话用

    maven {

                // All of React Native (JS, Android binaries) is installed from np

              xxxxxxxxxx

            }

    maven {

                // All of React Native (JS, Android binaries) is installed from npm

    // 这个你要看一下 了有说 要去掉../ 根据你的项目来 我的项目添加了

                url "$rootDir/../node_modules/react-native/android"

            }

        }

    }

    5.在 App项目 的 build.gradle 文件中添加如下代码:

    dependencies {

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

        ...

    //如果报错 就改成RN 项目下package.json 文件中"react-native": "xxxx",的xxx 版本号

          implementation 'com.facebook.react:react-native:+'// From node_modules

    }

    要指定特定的 React Native 版本,可以用具体的版本号替换 “+”,当然前提是你从 npm 里下载的是这个版本。

    6. 在app build.gradle 文件

    apply plugin: 'com.android.application' 这一行下面 

        ....

    android {

        compileSdkVersion 26

        .............

    上面

    添加

    如:

    apply plugin: 'com.android.application'

    //以下从添加的内容

    project.ext.react = [

            entryFile: "index.js"

    ]

    apply from: "../../node_modules/react-native/react.gradle"

    /**

    * Set this to true to create two separate APKs instead of one:

    *  - An APK that only works on ARM devices

    *  - An APK that only works on x86 devices

    * The advantage is the size of the APK is reduced by about 4MB.

    * Upload all the APKs to the Play Store and people will download

    * the correct one based on the CPU architecture of their device.

    */

    def enableSeparateBuildPerCPUArchitecture = false

    /**

    * Run Proguard to shrink the Java bytecode in release builds.

    */

    def enableProguardInReleaseBuilds = false

    //以上是添加的内容

    android {

        compileSdkVersion 26

        .............

    7. 先执行 react-native link 这个命令是将 RN项目中的插件mode  连接到你的android中  然后在右边的 Gradle 窗口中 选中根目录 可能是“android ” 右键 Refresh 刷新 然后修改程序 入口

    public class MainApplication extends Application implements ReactApplication {

    public final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

            @Override

            public boolean getUseDeveloperSupport() {

                return BuildConfig.DEBUG;

            }

            @Override

            protected List<ReactPackage> getPackages() {

                return Arrays.<ReactPackage>asList(

                        new RNDeviceInfo(),/*这些是 执行react-native link  命令 连接上的插件 还有原生程序 和RN交互的ativity 中的  mReactInstanceManager = ReactInstanceManager.builder(). .addPackages(Arrays.<ReactPackage>asList(

                            new RNDeviceInfo(),

                            new SvgPackage(),

                            new PickerViewPackage(),

                            new RNReactNativeDocViewerPackage(),

                            new MainReactPackage()

                    ))要添加 不然会报 插件加载报错*/

                        new SvgPackage(),//同上

                        new PickerViewPackage(),//同上

                        new RNReactNativeDocViewerPackage(),//同上

                        new MainReactPackage()//这个不需要的

                );

            }

            @Override

            protected String getJSMainModuleName() {

                return "index";

            }

        };

        @Override

        public ReactNativeHost getReactNativeHost() {

            return mReactNativeHost;

        }

    public void onCreate() {

    ..............................

    }

    查看 在app build.gradle 文件中 有没有 连接的插件

    dependencies {

    compile project(':react-native-svg')

    compile project(':react-native-picker')

    compile project(':react-native-doc-viewer')

    compile project(':react-native-device-info')

    .......

    }

    查看 settings.gradle 文件下有没有

    include ':react-native-svg'

    project(':react-native-svg').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-svg/android')

    include ':react-native-picker'

    project(':react-native-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-picker/android')

    include ':react-native-doc-viewer'

    project(':react-native-doc-viewer').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-doc-viewer/android')

    include ':react-native-device-info'

    project(':react-native-device-info').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-device-info/android')

    这个表示 你的插件 link (连接到) android 项目了

    8. 原生和RN的交互  入口ReactActivity 写一个事件跳转 到 ReactActivity

    public class ReactActivity extends Activity implements DefaultHardwareBackBtnHandler {

        private ReactRootView mReactRootView;

        private ReactInstanceManager mReactInstanceManager;

        public static int OVERLAY_PERMISSION_REQ_CODE=1258;

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            mReactRootView = new ReactRootView(this);

            mReactInstanceManager = ReactInstanceManager.builder()

                    .setApplication(getApplication())

                    .setBundleAssetName("index.android.bundle")

                    .setJSMainModulePath("index")

    //                .setJSMainModuleName("index")

    //                .addPackage(new MainReactPackage())

    //这里要特别注意  这里是官网的坑 必须和你程序入口MainApplication 中引入的 插件保持一致 否则 插件加载报错

                    .addPackages(Arrays.<ReactPackage>asList(

                            new RNDeviceInfo(),

                            new SvgPackage(),

                            new PickerViewPackage(),

                            new RNReactNativeDocViewerPackage(),

                            new MainReactPackage()

    //

                    ))

                    .setUseDeveloperSupport(BuildConfig.DEBUG)

                    .setInitialLifecycleState(LifecycleState.RESUMED)

                    .build();

            // 注意这里的MyReactNativeApp必须对应“index.js”中的

            // “AppRegistry.registerComponent()”的第一个参数

            mReactRootView.startReactApplication(mReactInstanceManager, "AwesomeProject", null);

            setContentView(mReactRootView);

        }

        @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

        public void onBackPressed() {

            if (mReactInstanceManager != null) {

                mReactInstanceManager.onBackPressed();

            } else {

                super.onBackPressed();

            }

        }

        @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 boolean onKeyUp(int keyCode, KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {

                mReactInstanceManager.showDevOptionsDialog();

                return true;

            }

            return super.onKeyUp(keyCode, event);

        }

    }

    9.在清单文件 androidMainfest.xml 中

    添加

      <!-- 访问internet权限 -->    <!--用于访问网络,网络定位需要上网-->

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

        <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> <!--reatc--><!-- 用于开启 debug 版本的应用在6.0 系统上 层叠窗口权限 -->

        <uses-permission android:name="android.permission.SYSTEM_OVERLAY_WINDOW" /> <!--reatc-->

    <!--react  摇一摇菜单 -->

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

            <!--react  RN和原生交互的Activity -->

            <activity

                android:configChanges="fontScale"

                android:name="xxxx.xxx.xxx.ReactActivity"

                android:screenOrientation="portrait"

                android:windowSoftInputMode="adjustUnspecified|stateHidden" />

    10 然后 在你RN项目 根目录下在文件路径框中 输入 cmd 回车  运行npm starr 命令 有时

    11. 再开一个 cmd 窗口 运行查看你 真机设备

    查看连接设备

    adb devices

    保证只有一个设备连接的情况下 连接本地服务器

    adb reverse tcp:8081 tcp:8081

    接着可以点击 事件了

    我是用Android studio 运行的

    忘记了 如果用命令运行需要在RN项目下的

    package.json文件中

    "scripts": {

        ........,

    "bundle-android": "react-native bundle --entry-file index.js --platform android --dev false --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/"

      }

    需要手动在app/src/main/ 目录下创建assets文件夹

    相关文章

      网友评论

          本文标题:react native 项目 和android 项目的整合

          本文链接:https://www.haomeiwen.com/subject/pyxwdqtx.html