You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按需求重构依赖google.aar的多Demo Android应用架构?

重构Android项目实现按需运行耦合SDK的Demo应用

项目结构梳理

当前项目核心结构:

  • 根目录无src目录,包含CustomerDemoApp(外部演示)、InternalDemoApp(内部演示)两个独立Demo模块
  • lib目录为ModuleSDK主目录,该SDK依赖第三方google.aar文件

核心实现方案

1. 统一SDK依赖配置

先在ModuleSDK的构建脚本中正确引入google.aar,避免重复依赖配置:

// ModuleSDK/build.gradle
repositories {
    flatDir {
        dirs 'libs' // 假设google.aar存放在ModuleSDK的libs子目录下
    }
}

dependencies {
    implementation(name: 'google', ext: 'aar')
}

然后让两个Demo模块直接依赖ModuleSDK:

// CustomerDemoApp/build.gradle
dependencies {
    implementation project(':lib:ModuleSDK')
}

// InternalDemoApp/build.gradle
dependencies {
    implementation project(':lib:ModuleSDK')
}

2. 配置按需运行的构建变体(可选)

如果两个Demo需要区分环境(比如内部Demo带调试工具、外部Demo仅保留正式功能),可以通过构建变体实现隔离:

  • 在ModuleSDK中定义环境标识,供Demo模块调用:
// ModuleSDK/build.gradle
android {
    buildTypes {
        release {
            buildConfigField "boolean", "IS_INTERNAL_DEMO", "false"
        }
        internal {
            initWith debug
            buildConfigField "boolean", "IS_INTERNAL_DEMO", "true"
        }
    }
}
  • 在Demo模块中同步构建类型配置:
// InternalDemoApp/build.gradle
android {
    buildTypes {
        internal {
            initWith debug
        }
    }
}

3. 直接按需运行指定Demo模块

  • Android Studio图形化操作:顶部运行配置下拉菜单中,选择目标Demo模块(CustomerDemoApp或InternalDemoApp)及其对应构建变体,点击运行即可。
  • 命令行操作:通过gradle命令直接指定模块构建运行:
# 安装并运行外部Demo的release版本
./gradlew :CustomerDemoApp:installRelease

# 安装并运行内部Demo的internal版本
./gradlew :InternalDemoApp:installInternal

4. 优化项目结构(可选)

若根目录结构不够清晰,可调整为标准多模块结构:

根目录
├── customer-demo (原CustomerDemoApp)
├── internal-demo (原InternalDemoApp)
├── module-sdk (原lib/ModuleSDK)
│   ├── libs
│   │   └── google.aar
│   └── build.gradle
└── settings.gradle

在settings.gradle中注册所有模块:

// settings.gradle
include ':customer-demo'
include ':internal-demo'
include ':module-sdk'

注意事项

  • 确保google.aar的路径在ModuleSDK的仓库配置中可被识别,避免依赖缺失
  • 两个Demo模块的编译SDK、最小SDK版本需与ModuleSDK保持一致,避免兼容性问题
  • 内部Demo的敏感逻辑可通过构建变体控制编译范围,防止泄露到外部Demo

内容的提问来源于stack exchange,提问作者IamVariable

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 12:07:08