mac下Android应用集成react-native

作者: 李moumou | 来源:发表于2017-09-13 00:23 被阅读0次

    本文源码地址:https://github.com/smart1024/AndroidWithReact.git

    首先需要搭建好react-native环境请参考下面两份文档:

    1. 脸书官方文档:http://facebook.github.io/react-native/docs/getting-started.html
    2. React-Native中文网:http://reactnative.cn/docs/0.48/getting-started.html
      上面步骤比较简单,不再赘述。

    然后是项目结构,生成的几个重要文件我已重点画出看下图

    项目结构.jpg

    最后是集成Reac-Native的具体步骤

    1. 去到项目的根路径,创建package.json文件


      创建package.json文件.jpg

      这是生成的json文件内容:

    {
      "name": "MyReactNativeApp",
      "version": "0.0.1",
      "private": true,
      "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start"
      }
    }
    

    其中name本只能小写我改成MyReactNativeApp
    然后运行:npm install --save react@16.0.0-alpha.12 react-native最终的json文件如下:

    {
      "name": "MyReactNativeApp",
      "version": "0.0.1",
      "private": true,
      "scripts": {
        "start": "node node_modules/react-native/local-cli/cli.js start"
      },
      "dependencies": {
        "react": "^16.0.0-alpha.12",
        "react-native": "^0.48.3"
      }
    }
    
    1. 创建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('MyReactNativeApp', () => HelloWorld);
    
    1. 在app module下build.gradle添加react-native和在全局build.gradle在maven依赖:
    dependencies {
      ...
      compile "com.facebook.react:react-native:+" // From node_modules.
    }
    
    
    allprojects {
        repositories {
            jcenter()
            maven {
                // All of React Native (JS, Android binaries) is installed from npm
                url "$rootDir/node_modules/react-native/android"
            }
        }
    }
    
    1. 配置权限
    <uses-permission android:name="android.permission.INTERNET" />
    

    在manifest.xml文件中添加(真机模式晃动手机可调出此界面)

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

    5.创建Activity并注册到清单文件下面是核心代码:

    public class MyReactActivity extends Activity implements DefaultHardwareBackBtnHandler {
        private static final int OVERLAY_PERMISSION_REQ_CODE =100 ;
        private ReactRootView mReactRootView;
        private ReactInstanceManager mReactInstanceManager;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    //这里是动态申请窗口权限
            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);
                }
            }
            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();
            mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);
    
            setContentView(mReactRootView);
        }
    
        @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();
            }
        }
    
        //真机晃动弹出dev menu菜单
        @Override
        public boolean onKeyUp(int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_MENU && mReactInstanceManager != null) {
                mReactInstanceManager.showDevOptionsDialog();
                return true;
            }
            return super.onKeyUp(keyCode, event);
        }
    
        @Override
        public void invokeDefaultOnBackPressed() {
            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...
                        Log.e("onActivityResult","SYSTEM_ALERT_WINDOW permission not granted");
                    }
                }
            }
        }
    

    注册到清单文件

    <activity android:name=".MyReactActivity" android:theme="@style/Theme.AppCompat.Light.NoActionBar">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
    1. 在项目中创建assets文件在项目根路径运行如下命令
       react-native bundle \
       --platform android \
       --dev false \
       --entry-file ./index.android.js \
       --bundle-output ./app/src/main/assets/index.android.bundle \
       --sourcemap-output ./app/src/main/assets/index.android.map\
       --assets-dest ./app/src/main/res/
    

    会在assets下生成三个文件分别是:

    assets下文件.jpg
    1. 测试集成结果:
    • 去项目根路径运行packager:npm start并保持窗口不关闭
    • 在android studio中点击run app按钮运行
    运行结果.jpg

    会遇到的问题

    1. findbugs版本问题:
      在app module 的build.gradle文件中加入如下
    android {
      ...
    //    Warning:Conflict with dependency 'com.google.code.findbugs:jsr305'. Resolved versions for app (3.0.0
        configurations.all {
            resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
        }
    }
    
    1. Android SDK版本选择问题:
      按如下配置即可
    compileSdkVersion 23
        buildToolsVersion "23.0.1"
        defaultConfig {
            applicationId "com.lilin.androidwithreact"
    //    Manifest merger failed : uses-sdk:minSdkVersion 15 cannot be smaller than version 16 declared in library [com.facebook.react:react-native:0.20.1] /Users/lilin/AndroidStudioProjects/AndroidIntegratedWithReact/android/AndroidWithReact/app/build/intermediates/exploded-aar/com.facebook.react/react-native/0.20.1/AndroidManifest.xml
            minSdkVersion 16
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
    

    需要注意的点:

    package.json中的name的值MyReactNativeApp与
    index.android.js中的AppRegistry.registerComponent('MyReactNativeApp', () =>HelloWorld);
    以及MyReactActivity中mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null) 务必保持一致
    怎么样简单吧,如果有点帮助,帮忙点个赞O(∩_∩)O谢谢!

    相关文章

      网友评论

        本文标题:mac下Android应用集成react-native

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