Android知识

安卓项目遇上ReactNative

2016-08-25  本文已影响155人  小张呵呵

#######参考

最终安卓项目目录结构最终如下
B12FBF2E-325D-46AC-ADBB-5F441E012C8A.png

1.新建原生安卓MyApplacation,一个rn项目如下

63C9C22C-0806-4010-972F-109AABF6B559.png

2.在原生 Android 项目的在app/build.gradle文件中,添加React Native依赖

 apply plugin: 'com.android.application'
 android {        
       compileSdkVersion 24    
       buildToolsVersion "24.0.0"    

       defaultConfig {       
               applicationId "example.com.myapplication"        
               minSdkVersion 16       
               targetSdkVersion 24        
               versionCode 1        
               versionName "1.0"       
       ndk {            
             abiFilters "armeabi-v7a", "x86"       
              }    
}   
 buildTypes {       
        release {           
              minifyEnabled false      
              proguardFiles getDefaultProguardFile('proguard-android.txt'),'proguard-rules.pro'       
                }   
            }
}
dependencies {  
      compile fileTree(dir: 'libs', include: ['*.jar'])    
      compile 'com.android.support:appcompat-v7:24.2.0'    
      compile 'com.facebook.react:react-native:+'
}

3添加package.json,注意 "name": "testinit",这个"testinit",后面index.android.js 用到,MyReactActivity中也需要用到,保持一致

  {
  "name": "testinit",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "react": "^15.1.0",
    "react-native": "^0.27.0-rc2"
  }
}

4.添加index.android.js

 import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View
} from 'react-native';

class AwesomeProject extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          我是 原生项目嵌入的 ReactNative
        </Text>
        <Text style={styles.instructions}>
          Press Cmd+R to reload,{'\n'}
          Cmd+D or shake for dev menu
        </Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});
// testinit需要保持一致
AppRegistry.registerComponent('testinit', () => AwesomeProject);

5.添加node_modules,从rn项目,之后直接copy过来的

6.修改project的build.gradle文件,这样可以关联到你添加的node_modules

  buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.0-beta2'

        // 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, Obj-C sources, Android binaries) is installed from npm
            url "$projectDir/../../node_modules/react-native/android"
        }
    }
}


task clean(type: Delete) {
    delete rootProject.buildDir
}

7.测试activity

 public class HomeActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void react(View view) {
        startActivity(new Intent(this, MyReactActivity.class));
    }

}

8.跳转目标MyReactActivity

 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())
                /**
                 * http://stackoverflow.com/questions/37951246/react-native-cannot-find-development-server-integrating-existing-android-app
                 * 调试模式下,建议直接写成 true 吧,我就因为这个错误,调了两天原因
                 */
//                .setUseDeveloperSupport(BuildConfig.DEBUG)
                .setUseDeveloperSupport(true)
                .setInitialLifecycleState(LifecycleState.RESUMED)
                .build();
       // testinit需要package.json,index.android.js保持一致
        mReactRootView.startReactApplication(mReactInstanceManager,  "testinit", 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();
        }
    }

}

8.终端 一定要启动包服务器 react-native start 否则报错

9.用AS运行项目,报错 如下,终端运行adb reverse tcp:8081 tcp:8081

 React: Exception in native call from JS
                                                                        java.lang.RuntimeException: java.util.concurrent.ExecutionException: java.lang.RuntimeException: Could not connect to development server.
                                                                        Try the following to fix the issue:
                                                                        Ensure that the packager server is running
                                                                        Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices
                                                                        If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device
                                                                        If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to y
                                                                            at com.facebook.react.ReactInstanceManagerImpl.createReactContext(ReactInstanceManagerImpl.java:860)
                                                                            at com.facebook.react.ReactInstanceManagerImpl.access$700(ReactInstanceManagerImpl.java:98)
                                                                            at com.facebook.react.ReactInstanceManagerImpl$ReactContextInitAsyncTask.doInBackground(ReactInstanceManagerImpl.java:194)
                                                                            at com.facebook.react.ReactInstanceManagerImpl$ReactContextInitAsyncTask.doInBackground(ReactInstanceManagerImpl.java:177)
                                                                            at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                            at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                            at java.lang.Thread.run(Thread.java:818)

10.有错误多看错误信息,一个一个的填坑

上一篇 下一篇

猜你喜欢

热点阅读