天天看點

已有Android項目內建react native

文章目錄

    • 已有Android項目內建react native
      • 效果
      • 環境
        • Android studio 4.0.1
        • gradle
      • 前置準備
      • 內建步驟
      • 應用位址

已有Android項目內建react native

效果

已有Android項目內建react native
已有Android項目內建react native

環境

Android studio 4.0.1

gradle

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.1"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

           
#Thu Feb 18 17:57:36 CST 2021
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip

           

前置準備

Android P(9.0) http網絡請求的問題

參考官網,把這些改安裝的安裝了

已有Android項目內建react native

內建步驟

  1. 建立個Android項目
  2. 初始化項目

根目錄輸入以下指令

npm init

已有Android項目內建react native

在第一個包名輸入自己項目的包名,其他一直按回車即可

  1. 添加腳本

    在根目錄會生成package.json這個檔案,将啟動腳本加入進去

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

已有Android項目內建react native
  1. 安裝React 和React Native

根目錄輸入以下指令

npm install --save react react-native

  1. 在日志中找到這句話
    已有Android項目內建react native
    繼續在根目錄中執行

    npm i -S [email protected]

    已有Android項目內建react native
  2. 下載下傳.flowconfig檔案(非必須)

    curl -o .flowconfig https://raw.githubusercontent.com/facebook/react-native/master/.flowconfig

  3. 建立index.android.js

    項目根目錄下建立index.android.js檔案,目錄内容如下:

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);
           
已有Android項目內建react native
  1. 在app下的build.gradle加入依賴
apply plugin: 'com.android.application'
// 新增
project.ext.react = [
        // your index js if not default, other settings
        // Hermes JSC ?
        enableHermes: false,
]
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
// 新增結束
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        applicationId "com.example.myapplication"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
	// 新增
    if (enableHermes) {
        // For RN 0.60.x
        // def hermesPath = "../../node_modules/hermesvm/android/"
        // 二選一
        // for RN 0.61+
        def hermesPath = "../../node_modules/hermes-engine/android/";

        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
    implementation "com.facebook.react:react-native:+"
     // 新增結束
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

}
           
  1. 在根目錄下的build.gradle下增加
allprojects { Project project ->
    project.repositories {RepositoryHandler repositories ->
        repositories.google()
        repositories.jcenter()
        addRepos(repositories)
        // 新增
        maven {
            // All of React Native (JS, Android binaries) is installed from npm
            url "$rootDir/node_modules/react-native/android"
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/node_modules/jsc-android/dist")
        }
		// 新增結束
    }

    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
    }
}
           
  1. 建立activity
package com.example.myapplication;


import androidx.annotation.Nullable;

import com.facebook.react.ReactActivity;



public class MyReactActivity extends ReactActivity {
    private static final String MAIN_COMPONENT = "MyReactNativeApp";
    /**
     * 傳回在index.android.js 中注冊的元件名
     * @return
     */
    @Nullable
    @Override
    protected String getMainComponentName() {
        return MAIN_COMPONENT;
    }

}
           

在MainActivity跳到MyReactActivity

public class MainActivity extends AppCompatActivity {

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

    public void jump_to_rn(View view) {
        Intent intent = new Intent(MainActivity.this, MyReactActivity.class);
        startActivity(intent);
    }
}
           
  1. application
package com.example.myapplication;

import android.app.Application;

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;

public class BaseApplication extends Application implements ReactApplication {

    /**
     * ReactNative的host
     */
    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()
            );
        }
    };

    /**
     * ReactNative的host
     *
     * @return
     */
    @Override
    public ReactNativeHost getReactNativeHost() {
        return mReactNativeHost;
    }

}
           
  1. manifest
<application
        android:name=".BaseApplication"
        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" />
    </application>
           
  1. 在app工程下建立assets
    已有Android項目內建react native
    在指令行輸入

    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/

    會在assets下生成bundle檔案
    已有Android項目內建react native
  2. 啟動

    react-native start

    已有Android項目內建react native

應用位址

已有Android項目內建react native