Publish Android Library with flavor to MavenCentral

Sivakumar Chellamuthu
2 min readMay 1, 2019

Purpose:

Publish android library with multiple flavors to MavenCentral, so that it can be imported on any project like,

implementation 'com.sivakumarc.android:mylibrary:1.0.0:flavor1@aar'
implementation 'com.sivakumarc.android:mylibrary:1.0.0:flavor2@aar'

Background:

We are building a module (as an Android Library) that is shared among different android apps. But each app has it’s own branding and UI, so we wanted to separate resources and classes specific to the app by applying flavors to the library. Each flavor in the library is has specific styles that reflects each app’s UI and branding.

We wanted the apps that are consuming this library to specify appropriate flavor while importing via gradle, so that only app specific resources and classes are imported in the project. If library is not flavored, app that is consuming it might end up importing some additional resources that are irrelevant to it. So we decided to flavor the library and reduce the import size for the apps using it.

mylibrary
--flavor1
--flavor2

project1
implementation 'com.sivakumarc.android:mylibrary:1.0.0:flavor1@aar'
project2
implementation 'com.sivakumarc.android:mylibrary:1.0.0:flavor2@aar'

Let’s see how we achieved it,

Set up these files in your library:

build.gradle (Module: mylibray)

apply from: 'maven-push.gradle'
apply plugin: 'com.android.library'

android {
compileSdkVersion 28

defaultConfig {
....
}
buildTypes {
release {
...
}
}
flavorDimensions("default")
productFlavors {
flavor1 {

}
flavor2 {

}
}
}

dependencies {
...
}

maven-push.gradle (Module: mylibray)

apply plugin: 'maven-publish'

group "com.sivakumarc.android"
version 1.0.0

publishing {
publications {
Production(MavenPublication) {
artifact("$buildDir/outputs/aar/mylibrary-flavor1-release.aar") {
classifier 'flavor1'
extension 'aar'
}
artifact("$buildDir/outputs/aar/mylibrary-flavor2-release.aar") {
classifier 'flavor2'
extension 'aar'
}
}
}
repositories {
maven {
url getSnapshotRepositoryUrl()
credentials {
username = "NEXUS_USER_NAME"
password = "NEXUS_USER_PASSWORD"
}
}
}
}

How to publish:

./gradlew clean build publish

POM Structure (at MavenCentral):

Flavor1:
<dependency>
<groupId>com.sivakumarc.android</groupId>
<artifactId>mylibrary</artifactId>
<version>1.0.1-20190501.044311-1</version>
<classifier>flavor1</classifier>
<type>aar</type>
</dependency>
Flavor2:
<dependency>
<groupId>com.sivakumarc.android</groupId>
<artifactId>mylibrary</artifactId>
<version>1.0.1-20190501.044311-1</version>
<classifier>flavor2</classifier>
<type>aar</type>
</dependency>

After publishing to MavenCentral() use the gradle implementation statements Like mentioned in the top to see if it is successfully imported in your project.

References:

flavors and dimensions:

--

--