react-native + androidstudio 混合開發 - 1(基礎配置)

謝謝。最近好熱,大家夏天快樂~早日成爲技術大牛
希望一起學習,互相進步 ^ ^
老規矩,先上圖
這裏寫圖片描述
注意版本匹配問題package.json

"dependencies": {
    "install": "^0.10.1",
    "react": "^16.0.0-alpha.12",
    "react-native": "^0.46.1"
  }

之前一直load不出來好急,最後決定更新版本
這裏寫圖片描述
終於搞定

前提:node環境git環境
(以window爲例)
這裏寫圖片描述

1:新建安卓工程
新建工程

2:選擇sdk版本 一定要 參考官方文檔http://facebook.github.io/react-native/docs/getting-started.html
sdk - plateforms
sdk plateforms
sdk - tools
sdk tools
接下來點擊next - >就好了
這裏寫圖片描述
3:進入項目,修改bulid
compileSdkVersion 23
compile ‘com.android.support:appcompat-v7:23.0.1’

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.gmz.myreact"
        minSdkVersion 23
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

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:23.0.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
}

4:andoridstudio 的Terminal終端 使用命令行導入react 和 react-native包

npm init

生成package.json文件

package.json文件是npm下載模塊Module時會帶有這個json文件 裏面有當前模塊的介紹。如版本信息,依賴的模塊 以及運行Node命令的起始文件路徑等等 

entrypoint最好先寫成index.android.js,一會兒就不用配了
生成package.json文件
輸完後按enter ,yes?提示時繼續enter
這裏寫圖片描述

這裏寫圖片描述
繼續npm命令導包
爲了快速下載,配置淘寶鏡像

npm config set registry “https://registry.npm.taobao.org

開始安裝

npm install --save react react-native

這裏寫圖片描述

完成後會多一個node_modules包

node_modules 目錄是一個Node模塊 裏面主要是js文件,我們使用js編寫代碼時引用的一些模塊,組件主要是在這裏面,比如reative,react-native

這裏寫圖片描述

5:配置
①添加.flowconfig文件(可以不搞,flow是一種代碼檢查規範)
新建file,將https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig裏的內容複製
這裏寫圖片描述
②配置 package.json 信息
script 標籤下添加start(執行語句)

 "start": "node node_modules/react-native/local-cli/cli.js start"

這裏寫圖片描述
③新建一個入口 index.android.js文件,複製點東西過去,就helloworld吧

index.android.js 文件是編寫android項目的起始文件  
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image
} from 'react-native';

class HelloWorld extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}> 你好世界</Text>
        <Image style={styles.pic} source={{uri: 'http://192.168.10.124:8080/gmz.jpg'}}></Image>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  pic: {
        width:96,
        height:83,
  },
});
AppRegistry.registerComponent('HelloWorld', function() { return HelloWorld });

這裏寫圖片描述
④gradle配置
依賴
這裏寫圖片描述

這裏寫圖片描述
ndk配置 ndk 、packagingOptions 、configurations.all(這個是爲了解決react和google在debug代碼時候的衝突)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.0"
    defaultConfig {
        applicationId "com.gmz.myreact"
        minSdkVersion 16
        targetSdkVersion 23
        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'
        }
    }
    packagingOptions {
        exclude "lib/arm64-v8a"
    }
    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:23.0.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile "com.facebook.react:react-native:0.46.1" //天node_modules下自己的
    testCompile 'junit:junit:4.12'
}

build successful 後就可以了

查看librarys裏是否有react最新版本這裏寫圖片描述

6:添加基礎代碼

保證getMainComponentName與index.android.js裏function返回值一致,es6好像可以 => 代替callback- function了

Mainactivity

package com.gmz.myreact;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.bt);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, MyReactActivity.class));
            }
        });
    }
}

MyReactActivity(記得在清單文件中配置)直接繼承模板代碼,很6~

package com.gmz.myreact;

import android.support.annotation.Nullable;

import com.facebook.react.ReactActivity;

/**
 * 作者:haoran   on https://github.com/woaigmz 2017/7/11.
 * 郵箱:[email protected]
 * 說明:
 */

public class MyReactActivity extends ReactActivity {
    @Nullable
    @Override
    protected String getMainComponentName() {
        //這個在Registry.registerComponent註冊
        return "HelloWorld";
    }
}

MyApplication (記得在清單文件中配置)

import android.app.Application;

import com.facebook.react.BuildConfig;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;

import java.util.Arrays;
import java.util.List;

/**
 * 作者:haoran   on https://github.com/woaigmz 2017/7/11.
 * 郵箱:[email protected]
 * 說明:
 */

public class MyAppliaction extends Application implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
        @Override
        public boolean getUseDeveloperSupport() {
            return BuildConfig.DEBUG;
        }

        @Override
        protected List<ReactPackage> getPackages() {
            return Arrays.<ReactPackage>asList(new MainReactPackage());
        }
    };

    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

}

添加DevSettingsActivity

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

7:另開一個 Termial 運行react-native start 編譯js代碼 啓動服務

react-native start

這裏寫圖片描述
這個提示說明服務已開啓,可以測試一下
http://localhost:8081/index.android.bundle?platform=android
會很慢,請耐心等待
出現一下頁面說明js編譯成功,服務開啓 –>
這裏寫圖片描述
8:AS運行項目 – 真機調試
apk安裝成功以後在原生的MainActivity點擊按鈕進入react界面。
會load一下js腳本(確保npm - start 或 react-native start )
AS
這裏寫圖片描述
真機
這裏寫圖片描述
當報缺少
index.android.bundle時有2種解決方案
①打開Termial窗口 , 新建assets文件夾創建bundle文件,生成bundle文件(assets下),(assets目錄存在執行下面命令纔有效)

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

這裏寫圖片描述
哈哈~
這裏寫圖片描述
②package.json裏添加

"scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "bundle-android": "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 android/app/src/main/res/"
  }

重啓服務,手機reload,進行調試
9:react界面會出現的異常
先挖坑,白屏(應用管理–權限管理–允許彈窗)
紅屏 ( 使勁搖晃手機 )
這裏寫圖片描述
點擊DevSettings,更改靜態ip與react服務一致
這裏寫圖片描述
繼續搖晃手機reload

出現bug提示,建議google,stackoverflow,github

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章