Android 組件化-Gradle配置

組件化 Gradle 配置

1. 項目基本業務結構如下圖。
在這裏插入圖片描述

  • 新建項目結構如下:
    在這裏插入圖片描述
    2. 抽取 gradle 基本配置到 config.gradle
ext {
    // 是否開啓組件化開發 true -> 開啓 false -> 不開啓
    isOpenComponent = false
    android = [
            compileSdkVersion: 29,
            buildToolsVersion: "29.0.3",
            minSdkVersion    : 23,
            targetSdkVersion : 29,
            versionCode      : 1,
            versionName      : "1.0"
    ]
    // 定義各個組件 applicationId 如果是組件模式則需要配置 ,如果是集成模式則不需要配置。
    appId = ["app"    : "com.component.based",
             "module1": "com.component.module1",
             "module2": "com.component.module2"]
    // 可以配置一些公共的庫和版本放到這裏 demo 裏面我都放到base裏面了 所以這裏面只是記錄了一下可以這麼做
    supportLibrary = ["29.0.0"]
    // 公共配置包可以放在這裏
    dependencies = [
            "appcompat-v7": "androidx.appcompat:appcompat-v7:${supportLibrary}",
    ]
}

3. application 的 Gradle

// 引入 config.gradle 相當於java中的 import:
apply from: 'config.gradle'
apply plugin: 'com.alibaba.arouter'
buildscript {

    repositories {
        google()
        jcenter()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.6.2'
        // 採用 ali的 ARouter
        classpath "com.alibaba:arouter-register:1.0.2"
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

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

4. 引用配置 config.gradle

  • app中
apply plugin: 'com.android.application'
// 獲取 config.gradle 中的配置
def androidConfig = rootProject.ext.android
def appId = rootProject.ext.appId
android {
    // 引用配置項
    compileSdkVersion androidConfig.compileSdkVersion
    buildToolsVersion androidConfig.buildToolsVersion

    defaultConfig {
        applicationId appId.app
        minSdkVersion androidConfig.minSdkVersion
        targetSdkVersion androidConfig.targetSdkVersion
        versionCode androidConfig.versionCode
        versionName androidConfig.versionName

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        javaCompileOptions {
            annotationProcessorOptions {
                // ARouter配置
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
    }

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    // 引入 base  因爲我在 app裏面也做了一些業務代碼 充當了 一個模塊
    implementation project(path: ':base')
    annotationProcessor 'com.alibaba:arouter-compiler:1.2.2'
    // 集成開發時 且 module1 和 module2 是 library 的情況下才需要依賴
    if (!rootProject.ext.isOpenComponent){
        implementation project(path: ':module1')
        implementation project(path: ':module2')
    }
}
  • module1.gradle 配置 (每個業務module基本配置都差不多 其他需求根據自己需要配置)
def isOpenComponent = rootProject.ext.isOpenComponent
if (isOpenComponent) {
    // 如果是組件開發 則設置成 application
    apply plugin: 'com.android.application'
} else {
    // 如果是集成開發 則設置成 library
    apply plugin: 'com.android.library'
}
def androidConfig = rootProject.ext.android
def appId = rootProject.ext.appId
android {
    compileSdkVersion androidConfig.compileSdkVersion
    buildToolsVersion androidConfig.buildToolsVersion
    defaultConfig {
        // 如果是組件開發 則需要設置 applicationId
        if (isOpenComponent) {
            applicationId appId.app
        }
        minSdkVersion androidConfig.minSdkVersion
        targetSdkVersion androidConfig.targetSdkVersion
        versionCode androidConfig.versionCode
        versionName androidConfig.versionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
		// 添加一條 boolean類型的變量 
		// 可以在java代碼中通過 buildConfig 獲取設置的值 用來做業務邏輯判斷
     buildConfigField("boolean","isOpenComponent",String.valueOf(isOpenComponent))
    }

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

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(path: ':base')
    annotationProcessor 'com.alibaba:arouter-compiler:1.2.2'
}
  • base 和其他 core模塊都是正常的配置就不貼出來了

5. 根據切換 config.gradle 中的 isOpenComponent = false 來切換是否是組件開發。

  1. 那麼有個問題是每個組件模塊中都有可能需要自定義的 application 初始化一些功能,比如下面的 ARouter初始化操作。
public class MyApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(this);
    }
}

但是如果每個組件中都自定義了 application 會報錯如下:項目進行打包時會合並AndroidManifest ,如果在多個AndroidManifest中指定了 android:name=".MyApplication" 就會報錯。

Manifest merger failed : Attribute application@name value=(com.component.based.MyApplication) from AndroidManifest.xml:8:9-38
	is also present at [:module1] AndroidManifest.xml:14:9-64 value=(com.component.module1.Module1Application).
	Suggestion: add 'tools:replace="android:name"' to <application> element at AndroidManifest.xml:6:5-23:19 to override.

這裏不去闡述合併原理,那麼怎麼解決上面的問題呢?下面提供兩個方法。
(1)在 app 的 manifest 中添加如下代碼,替換掉

 <application
 	android:name=".MyApplication"
 	// 通過 replace 替換 android:name 屬性
	tools:replace="android:name">

(2)每個module都配置自己的 application ,然後在 gradle 中根據是否是組件模式進行資源替換。
以例子中的module1爲例,新建 manifest 和 aplication 文件 結構如下(結構可以自己隨意定義):
在這裏插入圖片描述
其中新增的 AndroidManifest 如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.component.module1">
    <uses-permission android:name="android.permission.INTERNET " />
    <application
        android:name=".Module1Application"
        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=".Module1Activity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

application 如下:


public class Module1Application extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        if (BuildConfig.DEBUG) {
            ARouter.openLog();
            ARouter.openDebug();
        }
        ARouter.init(this);
    }
}

然後在 module1 gradle 的 android{} 中增加配置如下:

//資源配置
    sourceSets{
        main{
            //在組件模式下 使用不同的manifest文件
            if(isOpenComponent){
                manifest.srcFile 'src/main/module/AndroidManifest.xml'
                java.srcDirs 'src/main/module/java','src/main/java'
            }else{
                manifest.srcFile 'src/main/AndroidManifest.xml'
            }
        }
    }

然後就可以了。

demo下載鏈接

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