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

项目结构图:


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", extras = 10086)
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

五、拦截器的使用

@Interceptor(priority = 1)
public class LoginInterceptor implements IInterceptor {

    private static final String TAG = "LoginInterceptor";

    private Context mContext;

    @Override
    public void process(Postcard postcard, InterceptorCallback callback) {

        Log.i(TAG, "LoginInterceptor 开始执行"+postcard.getExtra());

        //给需要跳转的页面添加值为Constant.LOGIN_NEEDED的extra参数,用来标记是否需要用户先登录才可以访问该页面
        //先判断需不需要

        if(postcard.getExtra() == 10086){
            Log.i(TAG, "LoginInterceptor 开始执行=======10086");

//            boolean isLogin = App.getSharedPreferences().getBoolean(Constant.IS_LOGIN,false);
            boolean isLogin = true;

            Log.i(TAG, "是否已登录: " + isLogin);

            //判断用户的登录情况,可以把值保存在sp中
            if (isLogin) {
                callback.onContinue(postcard);
            }else {//没有登录,注意需要传入context
//                ARouter.getInstance().build(RouterPath.LOGIN_ACTIIVTY).navigation(mContext);
                Log.i(TAG, "跳转到登陆 " + isLogin);

            }
        } else {//没有extra参数时则继续执行,不做拦截
            callback.onContinue(postcard);
        }

    }

    @Override
    public void init(Context context) {

        mContext = context;

        Log.i(TAG, "LoginInterceptor 初始化");

    }
}

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

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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270