模块化学习(一)

当项目大到一定程度后,各个模块的业务相互耦合,维护的时候非常困难,另外项目大到一定程度后,编译速度也是很慢,所以这个时候模块化就显得很有必要了。网上的解说很多,这里就不再多说。

一般在项目模块划分好之后,各个模块之前要能单独调试,和作为一个依赖之前进行切换,所以就要进行简单的动态配置。

模块作为 application 和 library

我个人的理解的是:application 能启动运行的,library 作为依赖库不能运行的。
那么为了能够动态的去配置我们就需要有一个变量来控制。在 gradle.properties
添加如下:

//来控制模块是否作为一个 Library
isLibrary = true

然后在除了App的各个模块的 build.gradle 下:

if (isLibrary.toBoolean()) {
    //true 的时候作为一个库
    apply plugin: 'com.android.library'
} else {
//true 的时候作为一个程序入口
    apply plugin: 'com.android.application'
}

注意:在作为 .application 和 library 的情况下 他们的清单文件是不同的,作为程序入口的清单文件是要配置启动的activity,而作为 library是不需要的,因此还要再能动态的配置 加载的清单文件夹。
在除了app 外的模块内,在 main 文件夹 新建两个 文件夹 debug 和 release :
8BQ9%_~6O4G@$DM)L7~(YC5.png

debug:

 <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"
        >
        <activity android:name=".ui.activity.RegisterActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

release

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
        >
        <activity android:name=".ui.activity.RegisterActivity"/>
    </application>

然后就去写动态加载清单文件的,在 模块下的 build.gradle 内的 android 域内

 sourceSets{
        main{
            if(isLibrary.toBoolean()){
                manifest.srcFile 'src/main/release/AndroidManifest.xml'
            }else {
                manifest.srcFile 'src/main/debug/AndroidManifest.xml'
            }
        }
    }

最后在 app 模块下添加依赖的时候也需要进行判断

 if (isLibrary.toBoolean()){
        implementation project(':userlibrary')
    }

然后模块化的 单独作为入口 和作为库就搞定了。

猜你喜欢

转载自blog.csdn.net/weixin_37940567/article/details/79964438