组件化Android开发经验谈Android开发

组讲化项目详细部署与运用ARouter进行组件间数据交互

2020-03-21  本文已影响0人  程序员三千_

项目结构图:


image.png

定义app_config.gradle进行组件和宿主app的gradle公共管理

// 把一些公用的,共用的,可扩展的,加入到这里面来
// 整个App项目的Gradle配置文件
// ext 自定义增加我们的内容

ext {
    usename = "jack"

    // 开发环境 / 生产环境(测试/正式)
    isRelease = true

    // 建立Map存储,对象名、key都可以自定义,groovy糖果语法,非常灵活
    app_android = [
            compileSdkVersion        : 28,
            buildToolsVersion        : "29.0.0",

            applicationId            : "com.xiangxue.new_modular_gradle",
            minSdkVersion            : 15,
            targetSdkVersion         : 28,
            versionCode              : 1,
            versionName              : "1.0",
            testInstrumentationRunner: "androidx.test.runner.AndroidJUnitRunner"
    ]

    appId = ["app"     : "com.xiangxue.new_modular_interaction",
             "order"   : "com.xiangxue.order",
             "personal": "com.xiangxue.personal"]

    //  测试环境,正式环境 URL
    url = [
            "debug"  : "https://11.22.33.44/debug",
            "release": "https://11.22.33.44/release"
    ]

    // 依赖相关的
    app_implementation = [
            "appcompat"      : "androidx.appcompat:appcompat:1.1.0",
            "junit"          : "junit:junit:4.12",
            "runner"         : "androidx.test:runner:1.2.0",
            "espresso"       : "androidx.test.espresso:espresso-core:3.2.0",
            "arouterapi"     : "com.alibaba:arouter-api:1.5.0",//arouter的api
            "aroutercompiler": "com.alibaba:arouter-compiler:1.2.2",//arouter的compiler
    ]
}

宿主app的grade配置

apply plugin: 'com.android.application'

// 定义变量
def app_android = /*this.*/getRootProject().ext.app_android;

// 定义变量
def app_implementation = rootProject.ext.app_implementation;

// 定义变量
def url = this.getRootProject().ext.url;

android {
    compileSdkVersion app_android.compileSdkVersion
    buildToolsVersion app_android.buildToolsVersion
    defaultConfig {
        applicationId app_android.applicationId
        minSdkVersion app_android.minSdkVersion
        targetSdkVersion app_android.targetSdkVersion
        versionCode app_android.versionCode
        versionName app_android.versionName
        testInstrumentationRunner app_android.testInstrumentationRunner

        // 这个方法接收三个非空的参数,第一个:确定值的类型,第二个:指定key的名字,第三个:传值(必须是String)
        // 为什么需要定义这个?因为src代码中有可能需要用到跨模块交互,如果是组件化模块显然不行
        // 切记:不能在android根节点,只能在defaultConfig或buildTypes节点下
        buildConfigField("boolean", "isRelease", String.valueOf(isRelease))

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }



    }
    buildTypes {
        debug {
            // 增加服务器URL地址---是在测试环境下
            buildConfigField("String", "SERVER_URL", "\"${url.debug}\"")
        }
        release {
            // 增加服务器URL地址---是在正式环境下
            buildConfigField("String", "SERVER_URL", "\"${url.release}\"")

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

    // 源集 - 设置源集的属性,更改源集的 Java 目录或者自由目录等
    // 注意:我们先加入进来,后续在学习哦
    sourceSets {
        main {
            if (!isRelease) {
                // 如果是组件化模式,需要单独运行时
                manifest.srcFile 'src/main/AndroidManifest.xml'
                java.srcDirs = ['src/main/java']
                res.srcDirs = ['src/main/res']
                resources.srcDirs = ['src/main/resources']
                aidl.srcDirs = ['src/main/aidl']
                assets.srcDirs = ['src/main/assets']
            } else {
                // 集成化模式,整个项目打包
                manifest.srcFile 'src/main/AndroidManifest.xml'
            }
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'

    /*implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'*/

    implementation app_implementation.appcompat
    testImplementation app_implementation.junit
    androidTestImplementation app_implementation.runner
    androidTestImplementation  app_implementation.espresso


    annotationProcessor app_implementation.aroutercompiler



    // 更简洁的方式,由于我们config那边定义的是 map,那么是不是可以遍历map
//    app_implementation.each {
//        k, v -> implementation v
//    }

    implementation project(":common") // 公共基础库

    // 如果是集成化模式,做发布版本时。各个模块都不能独立运行了
    if (isRelease) {
        implementation project(':order')  // 这样依赖时,必须是集成化,有柱状图, 否则会循环依赖问题
        implementation project(':personal')  // 这样依赖时,必须是集成化,有柱状图, 否则会循环依赖问题
    }
}

order组件库gradle的配置

if (isRelease) { // 如果是发布版本时,各个模块都不能独立运行
    apply plugin: 'com.android.library'
} else {
    apply plugin: 'com.android.application'
}

// 定义变量
def app_android = this.rootProject.ext.app_android;

android {
    compileSdkVersion app_android.compileSdkVersion
    buildToolsVersion app_android.buildToolsVersion

    defaultConfig {
        if (!isRelease) { // 如果是集成化模式,不能有applicationId
            appId.personal // 组件化模式能独立运行才能有applicationId
        }

        minSdkVersion app_android.minSdkVersion
        targetSdkVersion app_android.targetSdkVersion
        versionCode app_android.versionCode
        versionName app_android.versionName
        testInstrumentationRunner app_android.testInstrumentationRunner

        // 这个方法接收三个非空的参数,第一个:确定值的类型,第二个:指定key的名字,第三个:传值(必须是String)
        // 为什么需要定义这个?因为src代码中有可能需要用到跨模块交互,如果是组件化模块显然不行
        // 切记:不能在android根节点,只能在defaultConfig或buildTypes节点下
        buildConfigField("boolean", "isRelease", String.valueOf(isRelease))



        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    // 配置资源路径,方便测试环境,打包不集成到正式环境
    sourceSets { // 节省apt大小
        main {
            if (!isRelease) {
                // 如果是组件化模式,需要单独运行时
                manifest.srcFile 'src/main/debug/AndroidManifest.xml'
            } else {
                // 集成化模式,整个项目打包apk
                manifest.srcFile 'src/main/AndroidManifest.xml'
                java {
                    // release 时 debug 目录下文件不需要合并到主工程
                    exclude '**/debug/**'
                }
            }
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    /*implementation 'androidx.appcompat:appcompat:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'*/

    implementation app_implementation.appcompat
    testImplementation app_implementation.junit
    androidTestImplementation app_implementation.runner
    androidTestImplementation  app_implementation.espresso
    annotationProcessor app_implementation.aroutercompiler


//    app_implementation.each {
//        k, v -> implementation v
//    }

    implementation project(':common') // 公共基础库
}

组件库person的gradle配置

if (isRelease) { // 如果是发布版本时,各个模块都不能独立运行
    apply plugin: 'com.android.library'
} else {
    apply plugin: 'com.android.application'
}

// 定义变量
def app_android = this.rootProject.ext.app_android;

android {
    compileSdkVersion app_android.compileSdkVersion
    buildToolsVersion app_android.buildToolsVersion

    defaultConfig {
        if (!isRelease) { // 如果是集成化模式,不能有applicationId
            appId.personal // 组件化模式能独立运行才能有applicationId
        }

        minSdkVersion app_android.minSdkVersion
        targetSdkVersion app_android.targetSdkVersion
        versionCode app_android.versionCode
        versionName app_android.versionName
        testInstrumentationRunner app_android.testInstrumentationRunner

        // 这个方法接收三个非空的参数,第一个:确定值的类型,第二个:指定key的名字,第三个:传值(必须是String)
        // 为什么需要定义这个?因为src代码中有可能需要用到跨模块交互,如果是组件化模块显然不行
        // 切记:不能在android根节点,只能在defaultConfig或buildTypes节点下
        buildConfigField("boolean", "isRelease", String.valueOf(isRelease))



        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [AROUTER_MODULE_NAME: project.getName()]
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    // 配置资源路径,方便测试环境,打包不集成到正式环境
    sourceSets {
        main {
            if (!isRelease) {
                // 如果是组件化模式,需要单独运行时
                manifest.srcFile 'src/main/debug/AndroidManifest.xml'
            } else {
                // 集成化模式,整个项目打包apk
                manifest.srcFile 'src/main/AndroidManifest.xml'
                java {
                    // release 时 debug 目录下文件不需要合并到主工程
                    exclude '**/debug/**'
                }
            }
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])

    /*implementation 'androidx.appcompat:appcompat:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'*/

    implementation app_implementation.appcompat
    testImplementation app_implementation.junit
    androidTestImplementation app_implementation.runner
    androidTestImplementation  app_implementation.espresso
    annotationProcessor app_implementation.aroutercompiler


//    app_implementation.each {
//        k, v -> implementation v
//    }

    implementation project(":common") // 公共基础库
}




公用基础库common的gradle的配置

apply plugin: 'com.android.library'

// 定义变量
def app_android = this.rootProject.ext.app_android
def app_implementation = this.rootProject.ext.app_implementation


android {
    compileSdkVersion app_android.compileSdkVersion
    buildToolsVersion app_android.buildToolsVersion




    defaultConfig {
        minSdkVersion app_android.minSdkVersion
        targetSdkVersion app_android.targetSdkVersion
        versionCode app_android.versionCode
        versionName app_android.versionName
        testInstrumentationRunner app_android.testInstrumentationRunner

        javaCompileOptions {
            annotationProcessorOptions {
                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'])

    /*implementation 'androidx.appcompat:appcompat:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'*/

    implementation app_implementation.appcompat
    testImplementation app_implementation.junit
    androidTestImplementation app_implementation.runner
    androidTestImplementation  app_implementation.espresso

    api app_implementation.arouterapi
    annotationProcessor app_implementation.aroutercompiler

//    implementation rootProject.ext.dependencies["arouterapi"]
//    annotationProcessor rootProject.ext.dependencies["aroutercompiler"]

//    app_implementation.each {
//        k, v -> implementation v
//    }
}

阿里路由框架ARouter的使用

一、在宿主app的AppApplication里初始化SDK

public class AppApplication extends BaseApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        ARouter.openLog();     // 打印日志
        ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行,必须开启调试模式!线上版本需要关闭,否则有安全风险)
        ARouter.init( this ); // 尽可能早,推荐在Application中初始化
    }
}

二、宿主app里配置跳转

package com.xiangxue.new_modular_interaction;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xiangxue.common.utils.Config;
import com.xiangxue.personal.Personal_MainActivity;

@Route(path = "/app/MainActivity")
public class MainActivity extends AppCompatActivity {

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

        if (BuildConfig.isRelease) {
            Log.e(Config.TAG, "当前为:集成化模式,除app可运行,其他子模块都是Android Library");
        } else {
            Log.e(Config.TAG, "当前为:组件化模式,app/order/personal子模块都可独立运行");
        }
    }

    public void jumpOrder(View view) {

        ARouter.getInstance().build("/order/Order_MainActivity")
                .withString("userName","张三")
                .withInt("age",123)
                .navigation(this,10);



    }

    public void jumpPersonal(View view) {
        ARouter.getInstance().build("/personal/Personal_MainActivity")
                .withString("userName","李四")
                .withInt("age",456)
                .navigation(this);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 10:
                System.out.println( "receive=" + data.getStringExtra("backKey"));
                break;
            default:
                break;
        }
    }
}

三、组件order里配置跳转和数据接收和数据回传到宿主app

package com.xiangxue.order;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.xiangxue.common.RecordPathManager;

@Route(path = "/order/Order_MainActivity")
public class Order_MainActivity extends AppCompatActivity {
    @Autowired
    public String userName;
    @Autowired
    public int age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_activity_main);
        ARouter.getInstance().inject(this);   //注入
        Log.d("TAG",userName+age);

    }

    public void jumpPersonal(View view) {
        ARouter.getInstance().build("/personal/Personal_MainActivity")
                .withString("userName","李四")
                .withInt("age",456)
                .navigation(this);

    }

    public void back(View view) {
        Intent intent = new Intent();
        intent.putExtra("backKey", "返回数据给首页");
        setResult(10, intent);
        finish();
    }

    
}

四、组件personal里配置数据接收

package com.xiangxue.personal;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

@Route(path = "/personal/Personal_MainActivity")
public class Personal_MainActivity extends AppCompatActivity {
    @Autowired
    public String userName;
    @Autowired
    public int age;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.personal_activity_main);
        ARouter.getInstance().inject(this);   //注入
        Log.d("TAG",userName+age);


    }
}

五、效果演示日志

image.png
image.png
image.png
2020-03-21 15:27:01.484 20251-20251/com.xiaosanye.new_modular_gradle D/TAG: 张三123
2020-03-21 15:27:04.360 20251-20251/com.xiaosanye.new_modular_gradle I/System.out: receive=返回数据给首页
2020-03-21 15:27:05.607 20251-20251/com.xiaosanye.new_modular_gradle D/TAG: 张三123
2020-03-21 15:27:06.498 20251-20251/com.xiaosanye.new_modular_gradle D/TAG: 李四456

至此,gradle文件公用的内容抽取,及其阿里ARouter的基本配置全部完成。

更详细的ARouter的使用可以去看ARouter的github:

https://github.com/alibaba/ARouter/blob/master/README_CN.md

上一篇 下一篇

猜你喜欢

热点阅读