SlideShare a Scribd company logo
1 of 53
Download to read offline
Plugin for plugin,
or extending
Android New Build System
Anton Rutkevich
About me
›  4+ years of Android development
›  Mobile game-dev experience
›  At Yandex:
1.  Mobile Yandex.Metrica
2.  Continuous Integration
The image cannot be displayed. Your computer may not have
enough memory to open the image, or the image may have
been corrupted. Restart your computer, and then open the file
again. If the red x still appears, you may have to delete the
image and then insert it again.
Intro
Why do I need this?
What can be done?
›  Additional resources/code/manifest processing
›  Output processing (apk, aar, jar)
›  Other things
Flavors
2 Flavors!
Story
Prod / test serversLogs on/offTest / prod analyticsAds on/off
Unique build number!...
I want to configure it
myself!
3 Flavors?Hmm…
Story
Prod / test
servers
Flavors!
Logs on/offTest / prod
analyticsAds on/offUnique build
number!...
I want to
configure it
myself!
2 Flavors!3
Flavors?Hmm...
Android devManager
How should it work
Java code build.gradle Teamcity
Actual value:
"https://my.server.com"
CI server can do it
Our job
Insert CI value into BuildConfig.java
// app/build.gradle

apply plugin: 'com.android.application'
android {
defaultConfig {
buildConfigField "String", "URL", ""${teamcity['server-url']}""
buildConfigField "String", "URL", ""#server-url""
}
}
project.teamcity = [

"server-url" : "https://my.server.com"
// ...
]
buildConfigField "String", "URL", ""${teamcity['server-url']}"".
Use BuildConfig.java from Java
public class SomeJavaClass {
// ...
public static final String SERVER_URL = "https://my.server.com";

public static final String SERVER_URL = BuildConfig.URL;
// ...

}
public static final String SERVER_URL = "https://my.server.com";
BuildConfig placeholder plugin
›  Replaces placeholder values with values from some map
›  Map can come from anywhere
Goal
// app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'placeholder'
placeholder {
replacements = project.teamcity
}

android {
defaultConfig {
buildConfigField "String", "URL", ""#server-url""
}
}
Table of contents
›  Gradle basics
›  New Build System workflow
›  Hello, Gradle plugin!
›  Extending Android New Build System
The image cannot be displayed. Your computer may not have
enough memory to open the image, or the image may have
been corrupted. Restart your computer, and then open the file
again. If the red x still appears, you may have to delete the
image and then insert it again.
Gradle basics
Tools we will use
Plugins everywhere
NBS
Tasks
›  Can be configured with { }
›  Consist of actions
›  Can depend on other tasks
›  Can have inputs / outputs
Task consists of actions
Action Action
Action Action
doFirst() doLast(), or <<
Task
Tasks execution order
Task 2
Task 3
Task 4
Execution order
dependsOn
Task 1
Task 2 Task 3 Task 4 Task 1
dependsOn
dependsOn
Outputs
Task inputs / outputs
TaskInputs
Inputs & outputs did not change
=>
UP-TO-DATE
Task example
task myTask {
ext.myMessage = "hello"
}

myTask << {
println myMessage
}

task otherTask(dependsOn: myTask)
Task example output
>> gradle otherTask
:app:myTask
hello
:app:otherTask
Build lifecycle
Initialization Configuration Execution
settings.gradle
Projects creation
Projects
configuration
Tasks creation
Tasks configuration
project.afterEvaluate { }
Task graph execution
Task graph
build.gradle
Build initialization
The image cannot be displayed. Your computer may not have
enough memory to open the image, or the image may have
been corrupted. Restart your computer, and then open the file
again. If the red x still appears, you may have to delete the
image and then insert it again.
The New Build System
workflow
What's so special?
What tasks will be launched?
build
check assemble
assembleDebug assembleRelease
assemble<VariantName>Guaranteed
Android project build overview
Tasks we will need
assemble<VariantName>
generate<VariantName>BuildConfig
compile<VariantName>Java
....
....
....
Variant API
Source code
is your documentation!
›  Access to most variant's tasks
›  Variant output related properties
›  Different for apps & libraries
The image cannot be displayed. Your computer may not have
enough memory to open the image, or the image may have
been corrupted. Restart your computer, and then open the file
again. If the red x still appears, you may have to delete the
image and then insert it again.
Hello, Gradle plugin!
The first steps
The very basic one
src/main/groovy/com/example/gradle/PlaceholderPlugin.gradle 
public class PlaceholderPlugin implements Plugin<Project> {
@Override
void apply(Project project) {
project.task('hello') << {
println "Hello Gradle plugin!"
}
}
}
Bind plugin class to plugin name
src/main/resources/META-INF/gradle-plugins/placeholder.properties
implementation-class=com.example.gradle.PlaceholderPlugin
Extension
Extension
Add extension
src/main/groovy/com/example/gradle/PlaceholderExtension.gradle 
class PlaceholderExtension {
def replacements = [:]
}
Add extension
@Override
void apply(Project project) {




project.task('hello') << {
println "Hello Gradle plugin!"
println "Hi, ${project.placeholder.replacements}"
}
}


PlaceholderExtension extension = project.extensions.create(
"placeholder", PlaceholderExtension
);
println "Hello Gradle plugin!"
Use extension
// app/build.gradle
apply plugin: 'placeholder'
placeholder {
replacements = ["server-url" : "https://my.server.com"]
}
---------------------------------------------
>> gradle hello
:app:hello
Hi, [server-url:https://my.server.com]
The image cannot be displayed. Your computer may not have
enough memory to open the image, or the image may have
been corrupted. Restart your computer, and then open the file
again. If the red x still appears, you may have to delete the
image and then insert it again.
Extending
The New Build System
Let's do it!
Check for New Build System
// PlaceholderPlugin.groovy

@Override
void apply(Project project) {
if (project.hasProperty("android")) {
PlaceholderExtension extension = project.extensions.create(
"placeholder", PlaceholderExtension
);

def android = project.android
// all code goes here
}
}
Let the New Build System do its job
// PlaceholderPlugin.apply()

if (project.hasProperty("android")) {
PlaceholderExtension extension = project.extensions.create(
"placeholder", PlaceholderExtension
);
def android = project.android

project.afterEvaluate {
// at this point we have all 
// tasks from New Build System
}
}
Process every variant
// PlaceholderPlugin.apply()

project.afterEvaluate {
if (android.hasProperty('applicationVariants')) {
android.applicationVariants.all { variant ->
addActions(project, variant, extension)
}
} else if (android.hasProperty('libraryVariants')) {
android.libraryVariants.all { variant ->
addActions(project, variant, extension)
}
}
}
Add task
// PlaceholderPlugin.groovy

def addActions(Project project, variant, 
PlaceholderExtension extension) {
Task processPlaceholders = project.task(


"process${variant.name.capitalize()}Placeholders"
)

processPlaceholders << {
println "I will replace ${variant.name}!"
}
}
Insert task into build process
assemble<VariantName>
generate<VariantName>BuildConfig
compile<VariantName>Java
....
....
....
process<VariantName>Placeholders
Insert task into build process
// PlaceholderPlugin.groovy

def addActions(Project project, variant, 
PlaceholderExtension extension) {

Task processPlaceholders = ... 
...

variant.javaCompile.dependsOn processPlaceholders
processPlaceholders.dependsOn variant.generateBuildConfig

}
Does it really work?
>> gradle assembleDebug
:app:preBuild
...
:app:generateDebugBuildConfig
...
:app:processDebugPlaceholders
I will replace debug!
:app:compileDebugJava
...
Actual work. Perform replacements
// PlaceholderPlugin.addActions()

processPlaceholders << {
def buildConfigFile = getBuildConfig(variant)
extension.replacements.each { replacement ->
project.ant.replace(
file: buildConfigFile,
token: "#${replacement.key}",
value: replacement.value
)
}
}
Handling inputs / outputs
process
Placeholders
BuildConfig.java
BuildConfig.java
replacements
generate
BuildConfig
...
replacements
<< Action
BuildConfig.java
Replace task with 'doLast'
// PlaceholderPlugin.addActions()

processPlaceholders << {
variant.generateBuildConfig << {
def buildConfigFile = ...
extension.replacements.each { ... }
}

variant.generateBuildConfig.inputs.property(
"replacements", extension.replacements 
)
processPlaceholders << {
│ We've done it!
Remember how to use it?
// app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'placeholder'
placeholder {
replacements = project.teamcity
}
android {
defaultConfig {
buildConfigField "String", "URL", ""#server-url""
}
}
Does it work?
app/build/generated/source/buildConfig/debug/com/example/
sample/BuildConfig.java
public final class BuildConfig {

// Fields from default config.
public static final String URL = "https://my.server.com";

}
The image cannot be displayed. Your computer may not have
enough memory to open the image, or the image may have
been corrupted. Restart your computer, and then open the file
again. If the red x still appears, you may have to delete the
image and then insert it again.
To summarize
Key steps
›  Create Gradle plugin
›  Inside afterEvaluate { }
›  Process every variant
›  Add action to generateBuildConfig
›  Handle inputs / outputs
What's next?
›  Default values support
›  Errors handling
›  Publish ( jcenter / mavenCentral / other )
Links
Gradle
http://www.gradle.org/
The New Build System
http://tools.android.com/tech-docs/new-build-system
http://tools.android.com/tech-docs/new-build-system/build-workflow
Github sample
https://github.com/roottony/android-placeholder-plugin
Thank you for your attention!
anton.rutkevich@gmail.com
Anton Rutkevich
Senior software engineer
antonrut@yandex-team.ru

More Related Content

What's hot

Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You TestSchalk Cronjé
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionSchalk Cronjé
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
B-Translator as a Software Engineering Project
B-Translator as a Software Engineering ProjectB-Translator as a Software Engineering Project
B-Translator as a Software Engineering ProjectDashamir Hoxha
 
Development Setup of B-Translator
Development Setup of B-TranslatorDevelopment Setup of B-Translator
Development Setup of B-TranslatorDashamir Hoxha
 
Using Drupal Features in B-Translator
Using Drupal Features in B-TranslatorUsing Drupal Features in B-Translator
Using Drupal Features in B-TranslatorDashamir Hoxha
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Codescidept
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 

What's hot (8)

Cool JVM Tools to Help You Test
Cool JVM Tools to Help You TestCool JVM Tools to Help You Test
Cool JVM Tools to Help You Test
 
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers VersionCool Jvm Tools to Help you Test - Aylesbury Testers Version
Cool Jvm Tools to Help you Test - Aylesbury Testers Version
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
B-Translator as a Software Engineering Project
B-Translator as a Software Engineering ProjectB-Translator as a Software Engineering Project
B-Translator as a Software Engineering Project
 
Development Setup of B-Translator
Development Setup of B-TranslatorDevelopment Setup of B-Translator
Development Setup of B-Translator
 
Using Drupal Features in B-Translator
Using Drupal Features in B-TranslatorUsing Drupal Features in B-Translator
Using Drupal Features in B-Translator
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 

Similar to Plugin for Plugin, или расширяем Android New Build System. Антон Руткевич

Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsTobias Oetiker
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsMike Wilcox
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webpjcozzi
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebJames Rakich
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_jsMicroPyramid .
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleSkills Matter
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
Lessons from a year of building apps with React Native
Lessons from a year of building apps with React NativeLessons from a year of building apps with React Native
Lessons from a year of building apps with React NativeRyan Boland
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacriptLei Kang
 
Reactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJSReactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJSMartin Hochel
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesPVS-Studio
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratiehcderaad
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 
Real world scala
Real world scalaReal world scala
Real world scalalunfu zhong
 

Similar to Plugin for Plugin, или расширяем Android New Build System. Антон Руткевич (20)

Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
LISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial HandoutsLISA Qooxdoo Tutorial Handouts
LISA Qooxdoo Tutorial Handouts
 
Professional JavaScript: AntiPatterns
Professional JavaScript: AntiPatternsProfessional JavaScript: AntiPatterns
Professional JavaScript: AntiPatterns
 
WebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open webWebGL: GPU acceleration for the open web
WebGL: GPU acceleration for the open web
 
Why Gradle?
Why Gradle?Why Gradle?
Why Gradle?
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the Web
 
Having Fun with Play
Having Fun with PlayHaving Fun with Play
Having Fun with Play
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Why gradle
Why gradle Why gradle
Why gradle
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
 
Lessons from a year of building apps with React Native
Lessons from a year of building apps with React NativeLessons from a year of building apps with React Native
Lessons from a year of building apps with React Native
 
Testing of javacript
Testing of javacriptTesting of javacript
Testing of javacript
 
Hands on the Gradle
Hands on the GradleHands on the Gradle
Hands on the Gradle
 
Reactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJSReactive Type safe Webcomponents with skateJS
Reactive Type safe Webcomponents with skateJS
 
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" DependenciesAnalyzing FreeCAD's Source Code and Its "Sick" Dependencies
Analyzing FreeCAD's Source Code and Its "Sick" Dependencies
 
2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie2014 11 20 Drupal 7 -> 8 test migratie
2014 11 20 Drupal 7 -> 8 test migratie
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Real world scala
Real world scalaReal world scala
Real world scala
 

More from Yandex

Предсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of TanksПредсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of TanksYandex
 
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Yandex
 
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаСтруктурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаYandex
 
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаПредставление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаYandex
 
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Yandex
 
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Yandex
 
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Yandex
 
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Yandex
 
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Yandex
 
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Yandex
 
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Yandex
 
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Yandex
 
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровКак защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровYandex
 
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Yandex
 
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Yandex
 
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Yandex
 
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Yandex
 
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Yandex
 
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Yandex
 
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Yandex
 

More from Yandex (20)

Предсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of TanksПредсказание оттока игроков из World of Tanks
Предсказание оттока игроков из World of Tanks
 
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
Как принять/организовать работу по поисковой оптимизации сайта, Сергей Царик,...
 
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров ЯндексаСтруктурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
Структурированные данные, Юлия Тихоход, лекция в Школе вебмастеров Яндекса
 
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров ЯндексаПредставление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
Представление сайта в поиске, Сергей Лысенко, лекция в Школе вебмастеров Яндекса
 
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
Плохие методы продвижения сайта, Екатерины Гладких, лекция в Школе вебмастеро...
 
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
Основные принципы ранжирования, Сергей Царик и Антон Роменский, лекция в Школ...
 
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
Основные принципы индексирования сайта, Александр Смирнов, лекция в Школе веб...
 
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
Мобильное приложение: как и зачем, Александр Лукин, лекция в Школе вебмастеро...
 
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
Сайты на мобильных устройствах, Олег Ножичкин, лекция в Школе вебмастеров Янд...
 
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
Качественная аналитика сайта, Юрий Батиевский, лекция в Школе вебмастеров Янд...
 
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
Что можно и что нужно измерять на сайте, Петр Аброськин, лекция в Школе вебма...
 
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
Как правильно поставить ТЗ на создание сайта, Алексей Бородкин, лекция в Школ...
 
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеровКак защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
Как защитить свой сайт, Пётр Волков, лекция в Школе вебмастеров
 
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
Как правильно составить структуру сайта, Дмитрий Сатин, лекция в Школе вебмас...
 
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
Технические особенности создания сайта, Дмитрий Васильева, лекция в Школе веб...
 
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
Конструкторы для отдельных элементов сайта, Елена Першина, лекция в Школе веб...
 
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
Контент для интернет-магазинов, Катерина Ерошина, лекция в Школе вебмастеров ...
 
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
Как написать хороший текст для сайта, Катерина Ерошина, лекция в Школе вебмас...
 
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
Usability и дизайн - как не помешать пользователю, Алексей Иванов, лекция в Ш...
 
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
Cайт. Зачем он и каким должен быть, Алексей Иванов, лекция в Школе вебмастеро...
 

Recently uploaded

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 

Recently uploaded (20)

Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 

Plugin for Plugin, или расширяем Android New Build System. Антон Руткевич

  • 1.
  • 2. Plugin for plugin, or extending Android New Build System Anton Rutkevich
  • 3. About me ›  4+ years of Android development ›  Mobile game-dev experience ›  At Yandex: 1.  Mobile Yandex.Metrica 2.  Continuous Integration
  • 4. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. Intro Why do I need this?
  • 5. What can be done? ›  Additional resources/code/manifest processing ›  Output processing (apk, aar, jar) ›  Other things
  • 6. Flavors 2 Flavors! Story Prod / test serversLogs on/offTest / prod analyticsAds on/off Unique build number!... I want to configure it myself! 3 Flavors?Hmm…
  • 7. Story Prod / test servers Flavors! Logs on/offTest / prod analyticsAds on/offUnique build number!... I want to configure it myself! 2 Flavors!3 Flavors?Hmm... Android devManager
  • 8. How should it work Java code build.gradle Teamcity Actual value: "https://my.server.com" CI server can do it Our job
  • 9. Insert CI value into BuildConfig.java // app/build.gradle apply plugin: 'com.android.application' android { defaultConfig { buildConfigField "String", "URL", ""${teamcity['server-url']}"" buildConfigField "String", "URL", ""#server-url"" } } project.teamcity = [ "server-url" : "https://my.server.com" // ... ] buildConfigField "String", "URL", ""${teamcity['server-url']}"".
  • 10. Use BuildConfig.java from Java public class SomeJavaClass { // ... public static final String SERVER_URL = "https://my.server.com"; public static final String SERVER_URL = BuildConfig.URL; // ... } public static final String SERVER_URL = "https://my.server.com";
  • 11. BuildConfig placeholder plugin ›  Replaces placeholder values with values from some map ›  Map can come from anywhere
  • 12. Goal // app/build.gradle apply plugin: 'com.android.application' apply plugin: 'placeholder' placeholder { replacements = project.teamcity } android { defaultConfig { buildConfigField "String", "URL", ""#server-url"" } }
  • 13. Table of contents ›  Gradle basics ›  New Build System workflow ›  Hello, Gradle plugin! ›  Extending Android New Build System
  • 14. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. Gradle basics Tools we will use
  • 16. Tasks ›  Can be configured with { } ›  Consist of actions ›  Can depend on other tasks ›  Can have inputs / outputs
  • 17. Task consists of actions Action Action Action Action doFirst() doLast(), or << Task
  • 18. Tasks execution order Task 2 Task 3 Task 4 Execution order dependsOn Task 1 Task 2 Task 3 Task 4 Task 1 dependsOn dependsOn
  • 19. Outputs Task inputs / outputs TaskInputs Inputs & outputs did not change => UP-TO-DATE
  • 20. Task example task myTask { ext.myMessage = "hello" } myTask << { println myMessage } task otherTask(dependsOn: myTask)
  • 21. Task example output >> gradle otherTask :app:myTask hello :app:otherTask
  • 22. Build lifecycle Initialization Configuration Execution settings.gradle Projects creation Projects configuration Tasks creation Tasks configuration project.afterEvaluate { } Task graph execution Task graph build.gradle Build initialization
  • 23. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. The New Build System workflow What's so special?
  • 24. What tasks will be launched? build check assemble assembleDebug assembleRelease assemble<VariantName>Guaranteed
  • 26. Tasks we will need assemble<VariantName> generate<VariantName>BuildConfig compile<VariantName>Java .... .... ....
  • 27. Variant API Source code is your documentation! ›  Access to most variant's tasks ›  Variant output related properties ›  Different for apps & libraries
  • 28. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. Hello, Gradle plugin! The first steps
  • 29. The very basic one src/main/groovy/com/example/gradle/PlaceholderPlugin.gradle public class PlaceholderPlugin implements Plugin<Project> { @Override void apply(Project project) { project.task('hello') << { println "Hello Gradle plugin!" } } }
  • 30. Bind plugin class to plugin name src/main/resources/META-INF/gradle-plugins/placeholder.properties implementation-class=com.example.gradle.PlaceholderPlugin
  • 33. Add extension @Override void apply(Project project) { project.task('hello') << { println "Hello Gradle plugin!" println "Hi, ${project.placeholder.replacements}" } } PlaceholderExtension extension = project.extensions.create( "placeholder", PlaceholderExtension ); println "Hello Gradle plugin!"
  • 34. Use extension // app/build.gradle apply plugin: 'placeholder' placeholder { replacements = ["server-url" : "https://my.server.com"] } --------------------------------------------- >> gradle hello :app:hello Hi, [server-url:https://my.server.com]
  • 35. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. Extending The New Build System Let's do it!
  • 36. Check for New Build System // PlaceholderPlugin.groovy @Override void apply(Project project) { if (project.hasProperty("android")) { PlaceholderExtension extension = project.extensions.create( "placeholder", PlaceholderExtension ); def android = project.android // all code goes here } }
  • 37. Let the New Build System do its job // PlaceholderPlugin.apply() if (project.hasProperty("android")) { PlaceholderExtension extension = project.extensions.create( "placeholder", PlaceholderExtension ); def android = project.android project.afterEvaluate { // at this point we have all // tasks from New Build System } }
  • 38. Process every variant // PlaceholderPlugin.apply() project.afterEvaluate { if (android.hasProperty('applicationVariants')) { android.applicationVariants.all { variant -> addActions(project, variant, extension) } } else if (android.hasProperty('libraryVariants')) { android.libraryVariants.all { variant -> addActions(project, variant, extension) } } }
  • 39. Add task // PlaceholderPlugin.groovy def addActions(Project project, variant, PlaceholderExtension extension) { Task processPlaceholders = project.task( "process${variant.name.capitalize()}Placeholders" ) processPlaceholders << { println "I will replace ${variant.name}!" } }
  • 40. Insert task into build process assemble<VariantName> generate<VariantName>BuildConfig compile<VariantName>Java .... .... .... process<VariantName>Placeholders
  • 41. Insert task into build process // PlaceholderPlugin.groovy def addActions(Project project, variant, PlaceholderExtension extension) { Task processPlaceholders = ... ... variant.javaCompile.dependsOn processPlaceholders processPlaceholders.dependsOn variant.generateBuildConfig }
  • 42. Does it really work? >> gradle assembleDebug :app:preBuild ... :app:generateDebugBuildConfig ... :app:processDebugPlaceholders I will replace debug! :app:compileDebugJava ...
  • 43. Actual work. Perform replacements // PlaceholderPlugin.addActions() processPlaceholders << { def buildConfigFile = getBuildConfig(variant) extension.replacements.each { replacement -> project.ant.replace( file: buildConfigFile, token: "#${replacement.key}", value: replacement.value ) } }
  • 44. Handling inputs / outputs process Placeholders BuildConfig.java BuildConfig.java replacements generate BuildConfig ... replacements << Action BuildConfig.java
  • 45. Replace task with 'doLast' // PlaceholderPlugin.addActions() processPlaceholders << { variant.generateBuildConfig << { def buildConfigFile = ... extension.replacements.each { ... } } variant.generateBuildConfig.inputs.property( "replacements", extension.replacements ) processPlaceholders << {
  • 47. Remember how to use it? // app/build.gradle apply plugin: 'com.android.application' apply plugin: 'placeholder' placeholder { replacements = project.teamcity } android { defaultConfig { buildConfigField "String", "URL", ""#server-url"" } }
  • 48. Does it work? app/build/generated/source/buildConfig/debug/com/example/ sample/BuildConfig.java public final class BuildConfig { // Fields from default config. public static final String URL = "https://my.server.com"; }
  • 49. The image cannot be displayed. Your computer may not have enough memory to open the image, or the image may have been corrupted. Restart your computer, and then open the file again. If the red x still appears, you may have to delete the image and then insert it again. To summarize
  • 50. Key steps ›  Create Gradle plugin ›  Inside afterEvaluate { } ›  Process every variant ›  Add action to generateBuildConfig ›  Handle inputs / outputs
  • 51. What's next? ›  Default values support ›  Errors handling ›  Publish ( jcenter / mavenCentral / other )
  • 52. Links Gradle http://www.gradle.org/ The New Build System http://tools.android.com/tech-docs/new-build-system http://tools.android.com/tech-docs/new-build-system/build-workflow Github sample https://github.com/roottony/android-placeholder-plugin
  • 53. Thank you for your attention! anton.rutkevich@gmail.com Anton Rutkevich Senior software engineer antonrut@yandex-team.ru