SlideShare a Scribd company logo
1 of 62
Exploring the power of gradle in
Android studio – Basics and beyond
Kaushal Dhruw
@drulabs
Agenda
• Just enough Gradle to get started
• Basic gradle tasks and commands
• How android studio uses gradle
• How to use gradle for our advantage
• Facebook’s stetho debug bridge for android applications
• Demos
Just enough gradle… with android studio demo
wherever possible
• Build automation tools
• Vs Ant and Maven
• Introduction
• Gradle tasks
• Task lifecycle
• Task dependencies
• Gradle wrapper
• Dependency Management
• Gradle plugins
Build automation tools (build tools)
Build tools are programs that automate the creation of executables or binary
code from source code (e.g. apk for android app). Building process
incorporates compiling, linking and packaging the code into a usable or
executable form.
Problems with Ant
• Ant uses XML as build script
• Hard to read
• Difficult to maintain
• Lack of convention -We need to specify everything.
• Source / Build Directories
• Any library dependency path
• Class file path
• Target path
• Basically specify everything that is needed
• This leads to very complicated build files for fairly simple projects
Problems with Maven
• Maven has several advantages over ant
• No need to specify source and output directories
• Also supports dependency management
• No need to carry all the library jar files – download on the go.
• Can be configured with plugins.
• However
• Maven also uses XML (It can be hard to read and maintain)
• Dependency management can be tricky
• Not nearly as customizable as gradle
• No support for Ivy, dynamic tasks and dependencies, dynamic distribution etc.
Gradle basics
• Combines best of Maven and Ant.
• Gradle is an open source build automation system.
• It supports task based build processes like Ant and follows convention over configuration like
Maven
• Declarative build language – Much more readable, maintainable and easy to use
• Gradle uses Groovy DSL.
• Has a great dependency management system.
• Ivy and Maven dependencies.
• Supports multi-project builds.
• Javascript, C++, Scala you name it.
• Easily and Highly customizable.
In a nut shell…
Gradle Dependency Management
Configuring custom project structure
Gradle wrapper
• Provides a specific version of gradle to the project.
• No need to install gradle at all.
• You never have to worry about different versions of gradle in your
co-devs systems.
• This leads to consistent builds
• You can either define the version to use as a gradle task or have a properties
file from where gradle reads version configuration. (like we do in android)
GradleTask
• Everything that and IDE does (that is related to build process) from compiling, to
assembling, to generating binaries, to creating executables is a task in gradle.
• We can create our own to suit our needs
• A task in gradle represents a single atomic piece of work for a build.
• A task has:
• A lifecycle (initialization, configuration…)
• Properties (description, group…)
• Actions (doFirst, doLast…)
• Dependencies (on other tasks - optional)
• In android for example.There is a compile task, build task, assemble task…
Task lifecycle – Build phases
Initialization
Phase
Creates project instances
in multi project builds for
each of the dependent
projects
Configuration
Phase
Executes code in a task
that is not an action
Execution
Phase
Executes task actions
GradleTask Structure
This is not the only way.We will see that in next slide.
Please skip the type parameter for now
Creating simple tasks
Creating gradle tasks in android studio
build.gradle
Studio terminal
Output in terminal
Demo
• Gradle typically runs on build.gradle file of the project
• In this demo:
• Create a build.gradle file with simple tasks (various ways of defining)
• Run basic gradle commands (list, execute tasks etc.)
• See task lifecycle
• Execute simple tasks and view the output
• Execute tasks in android studio (printTest)
TypedTasks in Gradle
• The type attribute in previous slides means typed task.
• All the tasks we have seen till now are ad-hoc tasks.
• Regular straight forward stuff. Nothing complex.
• What about task reusability?
• e.g. copying files, zipping files, deleting files etc.
• When defining a task we specify what type of task this is and configure it as per our
needs.
• A sample copy task next
Typed task – copy task example
Task for uploading apk into archives folder in studio
build.gradle
Studio terminal
Similar task for uploading install ready apks
build.gradle
Studio terminal
Creating your own custom task
More about writing custom classes and actions
https://docs.gradle.org/current/userguide/custom_tasks.html
Another simple task for installing an apk
build.gradle
Task Dependencies
Task A
Task B Task C Task D
Task E Task F
Defining task dependencies ( 1/4)
Using dependsOn:
Task A
Task B
If (TaskA)
dependsOn
(TaskB)
TaskB will be executed
everytime beforeTaskA
Defining task dependencies (2/4)
Using mustRunAfter:
Task A
Task B
If both the tasks are
executedTaskA will be
executed afterTaskB
Time
Defining task dependencies (3/4)
Using shouldRunAfter:
Task A
Task B
Same as mustRunAfter. In addition
skips circular dependencies
Time
Task B
Defining task dependencies (4/4)
Using finalizedBy (Gradle 2.6+):
Task A
Task B
WheneverTaskA is executed,
TaskB is executed at the end.
To finalize actions ofTaskA
Time
Android build process
Android build process
http://developer.android.com/sdk/installing/studi
o-build.html
Tasks in android studio
Automating apkCleanCopier and apkLatestCopier
Demo
• Writing tasks with different types of dependencies
• Checking the execution order.
• Running apkCleanCopier, apkLatestCopier and
freeStethoInstaller task from studio
Gradle plugins
• Gradle by itself provides very basic automation.
• Features like compiling java code, assembling apks etc. are provided by
plugins.
• Applying plugins add new tasks, domain objects, conventions, can alter
build logic etc.
• Plugins can be classified into:
• Script plugins – separate gradle file to define build logic etc. Like “apply from: ‘gradle
file path’”. (Demo in android section)
• Binary plugins – like “apply plugin: ‘java’”
• Both types of plugins can be created (see
https://docs.gradle.org/current/userguide/custom_plugins.html)
Some familiar binary gradle plugins
android
Java and application plugin
Google services plugin in android
Script plugin for renaming the default android apk
Applying this in app build.gradle
apknomenclature
.gradle in root
project directory
Demo
• Execute a multi-project java application using gradle commands
• Applying script plugin in android studio
• Viewing the output apk in build folder
Defining variables and methods
Automatic version generation in android
Manipulating file in gradle (manifest)
Gradle in android studio
• Product flavors and configuration.
• Facebooks stetho debug bridge, its uses and one use case
• Creating all build variant apks.
• Description of elements inside android build.gradle.
Product flavors in android
• Product flavors are very useful when we want to create multiple versions of
an app like demo, free, paid, pro etc. from the same project.
• Each product version can have different features and device requirements.
• Each product flavor can override properties defined in defaultConfig
• BuildType + Product Flavor = BuildVariant
• Each product flavor can have its own specific sourceSet and dependencies.
Product flavor source sets
By default there are two build types debug and
release we can add more. So for two flavors defined
in prev slide there can be four build variants
This creates four sourceSets
Configuring product flavors
Adding flavor specific dependency
Overriding default config values
Few properties in product flavors and default config
http://google.github.io/android-gradle-
dsl/current/com.android.build.gradle.internal.dsl.ProductFlavor.html
Grouping product flavors (Multi-flavor variants)
• Product flavors can be grouped via dimension attribute.
• This can be used when we want to create several version of the same app
based on more than one criteria.
• Say for example you want to create country specific free and pro version of
your app
Filtering product flavors
• We have seen multi-flavor variants. We didn’t have much choice there.
Android creates all possible combinations of all flavors variants and build
type
• What if we want to filter and restrict some flavor combination. For whatever
reason like Russians are rich so I don’t need a Russian-Free variant.
Build config
• All flavor specific code goes in its respective source set folder.
• But sometimes we need:
• Flavor specific conditional coding in the main source.
• Flavor specific constants and resources in main source.
• But in main we don’t know the flavor that is generated.
• We can use BuildConfig class in this case.
• BuildConfig is an auto generated class.
• Flavor specific constants and resources can be added in product flavor
configuration in build gradle
Build config continued…
Build config continued…
BuildConfig generated for Russia-pro-debug variant
Facebook’s stetho debug bridge
• A debug bridge for android applications by facebook.
• Handy tool for debugging.
• Uses chrome dev tools.
• Using stetho you can:
• Perform network inspection (if using okhttp library)
• Database inspection
• View hierarchy
• Use javascript console to interact with app and android sdk
• Create custom dumpapp plugin
Configuring flavors for stetho
Dependency only for the stetho flavor
Filtering flavors for stetho
Now this generates 12 variants
Doesn’t make any sense to keep
release and stetho flavors together
Lets filter it
Generating all apks (for a flavor, buildType etc)
assembleFlavor1 Generate all apk variants of flavor1
assembleDebug Generate all debug apks for all variants
assembleRelease Generate all release apks for all variants
assemble
Depends on assembleDebug, assembleRelease and anyother buildType
Generates apks for all variants
These tasks can be run from android studio terminal or from gradle
tab on the right side of the IDE
Dynamic manifest
Configuration blocks in android closure
http://google.github.io/android-gradle-dsl/current/index.html
Summary
So now we have seen
• Gradle basics, wrapper and plugins
• Tasks, custom tasks, dependency and lifecycle
• Tasks in android studio and automating it
• Automatic version generation and changing default apk name
• Facebook’s stetho debug bridge.
• Android product flavors, configuration and filtering
• Some config blocks in android closure in app level build.gradle
References
• Gradle guide - https://docs.gradle.org/current/userguide/userguide.html
• Android gradle plugin user guide - http://tools.android.com/tech-docs/new-
build-system/user-guide
• DSL Reference - http://google.github.io/android-gradle-
dsl/current/index.html
• Configuring gradle -
http://developer.android.com/tools/building/configuring-gradle.html
Exploring the power of Gradle in android studio - Basics & Beyond

More Related Content

What's hot

Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Javakim.mens
 
Maven Basics - Explained
Maven Basics - ExplainedMaven Basics - Explained
Maven Basics - ExplainedSmita Prasad
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in javakim.mens
 
Hands On with Maven
Hands On with MavenHands On with Maven
Hands On with MavenSid Anand
 
Jenkins Introduction
Jenkins IntroductionJenkins Introduction
Jenkins IntroductionPavan Gupta
 
Secrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesBruno Borges
 
Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)Prashanth Kumar
 
ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsKen Cenerelli
 

What's hot (20)

Introduction to Maven
Introduction to MavenIntroduction to Maven
Introduction to Maven
 
Gradle
GradleGradle
Gradle
 
Advanced Reflection in Java
Advanced Reflection in JavaAdvanced Reflection in Java
Advanced Reflection in Java
 
Understanding Monorepos
Understanding MonoreposUnderstanding Monorepos
Understanding Monorepos
 
Maven Basics - Explained
Maven Basics - ExplainedMaven Basics - Explained
Maven Basics - Explained
 
Basics of reflection in java
Basics of reflection in javaBasics of reflection in java
Basics of reflection in java
 
GraalVM
GraalVMGraalVM
GraalVM
 
Apache Maven
Apache MavenApache Maven
Apache Maven
 
JVM++: The Graal VM
JVM++: The Graal VMJVM++: The Graal VM
JVM++: The Graal VM
 
Maven
MavenMaven
Maven
 
Hands On with Maven
Hands On with MavenHands On with Maven
Hands On with Maven
 
Jenkins Introduction
Jenkins IntroductionJenkins Introduction
Jenkins Introduction
 
Secrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on KubernetesSecrets of Performance Tuning Java on Kubernetes
Secrets of Performance Tuning Java on Kubernetes
 
Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)Memory Management in the Java Virtual Machine(Garbage collection)
Memory Management in the Java Virtual Machine(Garbage collection)
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Monorepo at Pinterest
Monorepo at PinterestMonorepo at Pinterest
Monorepo at Pinterest
 
ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bits
 
GraalVm and Quarkus
GraalVm and QuarkusGraalVm and Quarkus
GraalVm and Quarkus
 
Maven tutorial
Maven tutorialMaven tutorial
Maven tutorial
 
Apache maven 2 overview
Apache maven 2 overviewApache maven 2 overview
Apache maven 2 overview
 

Viewers also liked

Gradle & Android Studio - Introduction
Gradle & Android Studio - IntroductionGradle & Android Studio - Introduction
Gradle & Android Studio - IntroductionKevin Pelgrims
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentalsAmr Salman
 
Android Fundamentals - Day 2
Android Fundamentals - Day 2Android Fundamentals - Day 2
Android Fundamentals - Day 2Mohammad Tarek
 
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...Deepu S Nath
 
Gradle for Android Developers
Gradle for Android DevelopersGradle for Android Developers
Gradle for Android DevelopersJosiah Renaudin
 
Introduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryIntroduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryKaushal Dhruw
 
Android gradle-build-system-overview
Android gradle-build-system-overviewAndroid gradle-build-system-overview
Android gradle-build-system-overviewKevin He
 
Android Application Fundamentals
Android Application FundamentalsAndroid Application Fundamentals
Android Application FundamentalsVikalp Jain
 
New to android studio
New to android studioNew to android studio
New to android studioEngine Bai
 
Gradle 和 Android Studio --- Jason Ko
Gradle 和 Android Studio --- Jason KoGradle 和 Android Studio --- Jason Ko
Gradle 和 Android Studio --- Jason Ko力中 柯
 
A Deep Dive into Open Source Android Development
A Deep Dive into Open Source Android DevelopmentA Deep Dive into Open Source Android Development
A Deep Dive into Open Source Android DevelopmentDavid Wu
 
Gradle,the new build system for android
Gradle,the new build system for androidGradle,the new build system for android
Gradle,the new build system for androidzhang ghui
 
Gradle enabled android project
Gradle enabled android projectGradle enabled android project
Gradle enabled android projectShaka Huang
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAhsanul Karim
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI WidgetsAhsanul Karim
 

Viewers also liked (20)

Gradle & Android Studio - Introduction
Gradle & Android Studio - IntroductionGradle & Android Studio - Introduction
Gradle & Android Studio - Introduction
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Android app fundamentals
Android app fundamentalsAndroid app fundamentals
Android app fundamentals
 
Android Fundamentals - Day 2
Android Fundamentals - Day 2Android Fundamentals - Day 2
Android Fundamentals - Day 2
 
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
What’s new for Android Developers in 2015 - Material Design, Android Studio, ...
 
Gradle for Android Developers
Gradle for Android DevelopersGradle for Android Developers
Gradle for Android Developers
 
Introduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding libraryIntroduction to android studio 2.0 and data binding library
Introduction to android studio 2.0 and data binding library
 
Android gradle-build-system-overview
Android gradle-build-system-overviewAndroid gradle-build-system-overview
Android gradle-build-system-overview
 
Android Fundamentals
Android FundamentalsAndroid Fundamentals
Android Fundamentals
 
Android Application Fundamentals
Android Application FundamentalsAndroid Application Fundamentals
Android Application Fundamentals
 
New to android studio
New to android studioNew to android studio
New to android studio
 
Gradle 和 Android Studio --- Jason Ko
Gradle 和 Android Studio --- Jason KoGradle 和 Android Studio --- Jason Ko
Gradle 和 Android Studio --- Jason Ko
 
AndroidManifest
AndroidManifestAndroidManifest
AndroidManifest
 
A Deep Dive into Open Source Android Development
A Deep Dive into Open Source Android DevelopmentA Deep Dive into Open Source Android Development
A Deep Dive into Open Source Android Development
 
Gradle,the new build system for android
Gradle,the new build system for androidGradle,the new build system for android
Gradle,the new build system for android
 
Gradle enabled android project
Gradle enabled android projectGradle enabled android project
Gradle enabled android project
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & SpinnerAndroid User Interface Tutorial: DatePicker, TimePicker & Spinner
Android User Interface Tutorial: DatePicker, TimePicker & Spinner
 
Day 4: Android: UI Widgets
Day 4: Android: UI WidgetsDay 4: Android: UI Widgets
Day 4: Android: UI Widgets
 

Similar to Exploring the power of Gradle in android studio - Basics & Beyond

Build your android app with gradle
Build your android app with gradleBuild your android app with gradle
Build your android app with gradleSwain Loda
 
Android Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product FlavorsAndroid Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product FlavorsStefan Martynkiw
 
Gradle: One technology to build them all
Gradle: One technology to build them allGradle: One technology to build them all
Gradle: One technology to build them allBonitasoft
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Ryan Cuprak
 
Head first android apps dev tools
Head first android apps dev toolsHead first android apps dev tools
Head first android apps dev toolsShaka Huang
 
Szczepan.faber.gradle
Szczepan.faber.gradleSzczepan.faber.gradle
Szczepan.faber.gradlemagda3695
 
Next Step, Android Studio!
Next Step, Android Studio!Next Step, Android Studio!
Next Step, Android Studio!Édipo Souza
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
Gradle 2.Breaking stereotypes
Gradle 2.Breaking stereotypesGradle 2.Breaking stereotypes
Gradle 2.Breaking stereotypesStrannik_2013
 
Gradle 2.Write once, builde everywhere
Gradle 2.Write once, builde everywhereGradle 2.Write once, builde everywhere
Gradle 2.Write once, builde everywhereStrannik_2013
 
Modern Web-site Development Pipeline
Modern Web-site Development PipelineModern Web-site Development Pipeline
Modern Web-site Development PipelineGlobalLogic Ukraine
 
Javaone 2013 moscow gradle english
Javaone 2013 moscow gradle   englishJavaone 2013 moscow gradle   english
Javaone 2013 moscow gradle englishEvgeny Borisov
 
Gradle.Enemy at the gates
Gradle.Enemy at the gatesGradle.Enemy at the gates
Gradle.Enemy at the gatesStrannik_2013
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with GradleRyan Cuprak
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with GradleRyan Cuprak
 

Similar to Exploring the power of Gradle in android studio - Basics & Beyond (20)

Build your android app with gradle
Build your android app with gradleBuild your android app with gradle
Build your android app with gradle
 
Android Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product FlavorsAndroid Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product Flavors
 
Why Gradle?
Why Gradle?Why Gradle?
Why Gradle?
 
Gradle: One technology to build them all
Gradle: One technology to build them allGradle: One technology to build them all
Gradle: One technology to build them all
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]
 
Head first android apps dev tools
Head first android apps dev toolsHead first android apps dev tools
Head first android apps dev tools
 
Gradle build capabilities
Gradle build capabilities Gradle build capabilities
Gradle build capabilities
 
Szczepan.faber.gradle
Szczepan.faber.gradleSzczepan.faber.gradle
Szczepan.faber.gradle
 
Next Step, Android Studio!
Next Step, Android Studio!Next Step, Android Studio!
Next Step, Android Studio!
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
Gradle - Build System
Gradle - Build SystemGradle - Build System
Gradle - Build System
 
7 maven vsgradle
7 maven vsgradle7 maven vsgradle
7 maven vsgradle
 
Gradle 2.Breaking stereotypes
Gradle 2.Breaking stereotypesGradle 2.Breaking stereotypes
Gradle 2.Breaking stereotypes
 
Android studio
Android studioAndroid studio
Android studio
 
Gradle 2.Write once, builde everywhere
Gradle 2.Write once, builde everywhereGradle 2.Write once, builde everywhere
Gradle 2.Write once, builde everywhere
 
Modern Web-site Development Pipeline
Modern Web-site Development PipelineModern Web-site Development Pipeline
Modern Web-site Development Pipeline
 
Javaone 2013 moscow gradle english
Javaone 2013 moscow gradle   englishJavaone 2013 moscow gradle   english
Javaone 2013 moscow gradle english
 
Gradle.Enemy at the gates
Gradle.Enemy at the gatesGradle.Enemy at the gates
Gradle.Enemy at the gates
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 

Recently uploaded

Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312wphillips114
 
Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesChandrakantDivate1
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsChandrakantDivate1
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...nishasame66
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsChandrakantDivate1
 

Recently uploaded (6)

Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312Mobile App Penetration Testing Bsides312
Mobile App Penetration Testing Bsides312
 
Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 

Exploring the power of Gradle in android studio - Basics & Beyond

  • 1. Exploring the power of gradle in Android studio – Basics and beyond Kaushal Dhruw @drulabs
  • 2. Agenda • Just enough Gradle to get started • Basic gradle tasks and commands • How android studio uses gradle • How to use gradle for our advantage • Facebook’s stetho debug bridge for android applications • Demos
  • 3. Just enough gradle… with android studio demo wherever possible • Build automation tools • Vs Ant and Maven • Introduction • Gradle tasks • Task lifecycle • Task dependencies • Gradle wrapper • Dependency Management • Gradle plugins
  • 4. Build automation tools (build tools) Build tools are programs that automate the creation of executables or binary code from source code (e.g. apk for android app). Building process incorporates compiling, linking and packaging the code into a usable or executable form.
  • 5. Problems with Ant • Ant uses XML as build script • Hard to read • Difficult to maintain • Lack of convention -We need to specify everything. • Source / Build Directories • Any library dependency path • Class file path • Target path • Basically specify everything that is needed • This leads to very complicated build files for fairly simple projects
  • 6. Problems with Maven • Maven has several advantages over ant • No need to specify source and output directories • Also supports dependency management • No need to carry all the library jar files – download on the go. • Can be configured with plugins. • However • Maven also uses XML (It can be hard to read and maintain) • Dependency management can be tricky • Not nearly as customizable as gradle • No support for Ivy, dynamic tasks and dependencies, dynamic distribution etc.
  • 7. Gradle basics • Combines best of Maven and Ant. • Gradle is an open source build automation system. • It supports task based build processes like Ant and follows convention over configuration like Maven • Declarative build language – Much more readable, maintainable and easy to use • Gradle uses Groovy DSL. • Has a great dependency management system. • Ivy and Maven dependencies. • Supports multi-project builds. • Javascript, C++, Scala you name it. • Easily and Highly customizable.
  • 8. In a nut shell…
  • 11. Gradle wrapper • Provides a specific version of gradle to the project. • No need to install gradle at all. • You never have to worry about different versions of gradle in your co-devs systems. • This leads to consistent builds • You can either define the version to use as a gradle task or have a properties file from where gradle reads version configuration. (like we do in android)
  • 12. GradleTask • Everything that and IDE does (that is related to build process) from compiling, to assembling, to generating binaries, to creating executables is a task in gradle. • We can create our own to suit our needs • A task in gradle represents a single atomic piece of work for a build. • A task has: • A lifecycle (initialization, configuration…) • Properties (description, group…) • Actions (doFirst, doLast…) • Dependencies (on other tasks - optional) • In android for example.There is a compile task, build task, assemble task…
  • 13. Task lifecycle – Build phases Initialization Phase Creates project instances in multi project builds for each of the dependent projects Configuration Phase Executes code in a task that is not an action Execution Phase Executes task actions
  • 14. GradleTask Structure This is not the only way.We will see that in next slide. Please skip the type parameter for now
  • 16. Creating gradle tasks in android studio build.gradle Studio terminal Output in terminal
  • 17. Demo • Gradle typically runs on build.gradle file of the project • In this demo: • Create a build.gradle file with simple tasks (various ways of defining) • Run basic gradle commands (list, execute tasks etc.) • See task lifecycle • Execute simple tasks and view the output • Execute tasks in android studio (printTest)
  • 18. TypedTasks in Gradle • The type attribute in previous slides means typed task. • All the tasks we have seen till now are ad-hoc tasks. • Regular straight forward stuff. Nothing complex. • What about task reusability? • e.g. copying files, zipping files, deleting files etc. • When defining a task we specify what type of task this is and configure it as per our needs. • A sample copy task next
  • 19. Typed task – copy task example
  • 20. Task for uploading apk into archives folder in studio build.gradle Studio terminal
  • 21. Similar task for uploading install ready apks build.gradle Studio terminal
  • 22. Creating your own custom task More about writing custom classes and actions https://docs.gradle.org/current/userguide/custom_tasks.html
  • 23. Another simple task for installing an apk build.gradle
  • 24. Task Dependencies Task A Task B Task C Task D Task E Task F
  • 25. Defining task dependencies ( 1/4) Using dependsOn: Task A Task B If (TaskA) dependsOn (TaskB) TaskB will be executed everytime beforeTaskA
  • 26. Defining task dependencies (2/4) Using mustRunAfter: Task A Task B If both the tasks are executedTaskA will be executed afterTaskB Time
  • 27. Defining task dependencies (3/4) Using shouldRunAfter: Task A Task B Same as mustRunAfter. In addition skips circular dependencies Time Task B
  • 28. Defining task dependencies (4/4) Using finalizedBy (Gradle 2.6+): Task A Task B WheneverTaskA is executed, TaskB is executed at the end. To finalize actions ofTaskA Time
  • 29. Android build process Android build process http://developer.android.com/sdk/installing/studi o-build.html
  • 31. Automating apkCleanCopier and apkLatestCopier
  • 32. Demo • Writing tasks with different types of dependencies • Checking the execution order. • Running apkCleanCopier, apkLatestCopier and freeStethoInstaller task from studio
  • 33. Gradle plugins • Gradle by itself provides very basic automation. • Features like compiling java code, assembling apks etc. are provided by plugins. • Applying plugins add new tasks, domain objects, conventions, can alter build logic etc. • Plugins can be classified into: • Script plugins – separate gradle file to define build logic etc. Like “apply from: ‘gradle file path’”. (Demo in android section) • Binary plugins – like “apply plugin: ‘java’” • Both types of plugins can be created (see https://docs.gradle.org/current/userguide/custom_plugins.html)
  • 34. Some familiar binary gradle plugins android Java and application plugin Google services plugin in android
  • 35. Script plugin for renaming the default android apk Applying this in app build.gradle apknomenclature .gradle in root project directory
  • 36. Demo • Execute a multi-project java application using gradle commands • Applying script plugin in android studio • Viewing the output apk in build folder
  • 39. Manipulating file in gradle (manifest)
  • 40. Gradle in android studio • Product flavors and configuration. • Facebooks stetho debug bridge, its uses and one use case • Creating all build variant apks. • Description of elements inside android build.gradle.
  • 41. Product flavors in android • Product flavors are very useful when we want to create multiple versions of an app like demo, free, paid, pro etc. from the same project. • Each product version can have different features and device requirements. • Each product flavor can override properties defined in defaultConfig • BuildType + Product Flavor = BuildVariant • Each product flavor can have its own specific sourceSet and dependencies.
  • 42. Product flavor source sets By default there are two build types debug and release we can add more. So for two flavors defined in prev slide there can be four build variants This creates four sourceSets
  • 43. Configuring product flavors Adding flavor specific dependency Overriding default config values
  • 44. Few properties in product flavors and default config http://google.github.io/android-gradle- dsl/current/com.android.build.gradle.internal.dsl.ProductFlavor.html
  • 45. Grouping product flavors (Multi-flavor variants) • Product flavors can be grouped via dimension attribute. • This can be used when we want to create several version of the same app based on more than one criteria. • Say for example you want to create country specific free and pro version of your app
  • 46. Filtering product flavors • We have seen multi-flavor variants. We didn’t have much choice there. Android creates all possible combinations of all flavors variants and build type • What if we want to filter and restrict some flavor combination. For whatever reason like Russians are rich so I don’t need a Russian-Free variant.
  • 47. Build config • All flavor specific code goes in its respective source set folder. • But sometimes we need: • Flavor specific conditional coding in the main source. • Flavor specific constants and resources in main source. • But in main we don’t know the flavor that is generated. • We can use BuildConfig class in this case. • BuildConfig is an auto generated class. • Flavor specific constants and resources can be added in product flavor configuration in build gradle
  • 49. Build config continued… BuildConfig generated for Russia-pro-debug variant
  • 50. Facebook’s stetho debug bridge • A debug bridge for android applications by facebook. • Handy tool for debugging. • Uses chrome dev tools. • Using stetho you can: • Perform network inspection (if using okhttp library) • Database inspection • View hierarchy • Use javascript console to interact with app and android sdk • Create custom dumpapp plugin
  • 51. Configuring flavors for stetho Dependency only for the stetho flavor
  • 52. Filtering flavors for stetho Now this generates 12 variants Doesn’t make any sense to keep release and stetho flavors together Lets filter it
  • 53. Generating all apks (for a flavor, buildType etc) assembleFlavor1 Generate all apk variants of flavor1 assembleDebug Generate all debug apks for all variants assembleRelease Generate all release apks for all variants assemble Depends on assembleDebug, assembleRelease and anyother buildType Generates apks for all variants These tasks can be run from android studio terminal or from gradle tab on the right side of the IDE
  • 55. Configuration blocks in android closure http://google.github.io/android-gradle-dsl/current/index.html
  • 56.
  • 57.
  • 58.
  • 59.
  • 60. Summary So now we have seen • Gradle basics, wrapper and plugins • Tasks, custom tasks, dependency and lifecycle • Tasks in android studio and automating it • Automatic version generation and changing default apk name • Facebook’s stetho debug bridge. • Android product flavors, configuration and filtering • Some config blocks in android closure in app level build.gradle
  • 61. References • Gradle guide - https://docs.gradle.org/current/userguide/userguide.html • Android gradle plugin user guide - http://tools.android.com/tech-docs/new- build-system/user-guide • DSL Reference - http://google.github.io/android-gradle- dsl/current/index.html • Configuring gradle - http://developer.android.com/tools/building/configuring-gradle.html

Editor's Notes

  1. Welcome!!! Introduction
  2. Before build tools people used things like “Make” in unix and java. Which was tedious. Define build automation tools. Discuss about Ant and Maven. Ant (XML) – James Duncan Davidson
  3. Some of Gradle’s advantages over Ant Ant build files can grow quickly and very difficult to maintain as the project grows Standard slides.
  4. Maven has several advantages over Ant. Standard slides.
  5. Gradle combines best of both Ant and Maven and uses Groovy DSL as build script. Open source – hence good community support Will see benefits of gradle as we go along Will how exactly is Gradle customizable
  6. Gradle combines the best of Ant and Maven, adds Groovy DSL and additionally supports ivy dependencies
  7. 1 - How to add maven, ivy dependencies 2 – Support local project modules 3 – Support local binaries We are all android devs. There is one more addition here, that is the aar files (short for android archive). It is a simple zip file for android library projects. Show the gradletestlib aar files
  8. As you can see here, if you don’t want to follow standard project structure, you can specify your own. This is powerful feature for supporting legacy libraries and project modules. In java the android closure is not there. The snapshot is from android project
  9. You don’t need to have gradle installed when using gradle wrapper. This is very handy. If you fire a gradle command in your android studio terminal, it will say command not found (unless you have installed it). So use gradlew to issue gradle commands. Android has already done this for us, so we don’t need to install gradle. We can fire gradlew command on windows and ./gradlew on *nix and Mac
  10. Gradle tasks are basic building blocks for source compilation. We will see tasks in little bit details in coming slides Why this is needed? Why it is good to know
  11. Say a task depends on another projects task. This class will need an instance of that project to compile. That is initialization phase. Everything inside a task that is not an action is executed in configuration phase. Execution of the task is the final phase.
  12. Here doFirst and doLast are actions. You can create your own custom actions by extending your class from defaultTask class Description and some other statements are executed during configuration phase A task can have multiple doFirsts and doLasts. This is a very powerful features and one of the reasons why Gradle is so damn customizable
  13. A few ways of defining tasks. There are more ways to define a task, look it up if you are interested. The double left shift means next closure is doLast method closure
  14. A simple task to print build directory of the project. This is nothing complex. No configuration and only one action. In android studio terminal - The point to note here is we are issuing gradlew command instead of gradle. We don’t want to download new version of gradle, we want to use the wrapper instead. –q is quite flag The first time you fire this command gradle will automatically download any related dependencies Lets see it in action. Lets see a task that is a little bit complex.
  15. Using this command prompt alternative called cmder, using command prompt will give you same results. So now we know about: Gradle build system, Gradle DSL, Tasks, Task creation and its lifecycle, customizing project structure and creating
  16. Some useful tasks has been defined in gradle we can reuse those as typed tasks. Another weapon in your arsenal
  17. After the copy docs configuration phase, gradle will treat copyDocs task as if it is copy task. For more flexibility use copySpec Copy task can be used to copy and / or rename files Using this in android studio next
  18. This is a copy task and it copies all the files from one folder to another. It has some actions it got from Copy task of gradle and a do Last action. It has some properties (description and group). The srcPath is the output apk path of the demo android project and the destPath is some folder destination to copy files into. So what does it mean and what is it good for? (<<NEXT>>) Whenever we run this task it copies all the files (apks in this case) in a predefined location. Lets run it and see. But for this task to work we need to run the gradlew command. If we can automate this then, it can be used as custom archive uploader
  19. This task is similar to the prev task except the destination folder is different. Discuss how can this be useful. Or you can copy entire source code and resources if you want To reuse the logic you can create custom gradle task
  20. You can define your own custom class and actions like this. But we don’t usually need to do this unless we are creating a plugin or a custom layer for android studio. It’s there if you want to use it. Let’s see how to make tasks dependent on each other
  21. Another example of Typed task If you haven’t done project clean then you have apk of you latest changes residing in build folder. This will install that apk in the connected device. This saves a lot of time when all you need to do is install an apk in an android device..
  22. A task can have multi-level and multiple dependencies. Gradle figures out order of execution itself. For example: apkSigner task has dependency on build task, compile task etc. So how can we make one task dependent on another???? Here we will see the real power of gradle. Why is gradle called easily and highly customizable We will see its usage in android studio
  23. Many ways to enable task dependencies. We are covering 4 of those here. You can see various ways of declaring task dependencies using depends on. Again there can be multiple depends on. We will see its uses in demo but just by looking at it you can see how gradle is so customizable
  24. There are many ways of defining mustRunAfter too. Here is an example (in the slide). Again there can be multiple mustRunAfters. We will see its uses in demo but just by looking at it you can see how gradle is so customizable However there is one issue here. What if TaskA -> after TaskB -> after TaskC -> after TaskA. It can lead to circular dependencies. So please be careful while using this
  25. Same as mustRunAfter but skips any circular dependencies if present
  26. finalizedBy is kind of like inverted dependency. Like we know that taskB must be executed before taskA if taskA dependsOn taskB. finalizedBy tells gradle that this task will be only over after finalizedBy task is executed As usual there will can be many finalized bys gradle keeps appending those here. We will see an example of it in android
  27. All of this is done via gradle tasks. Link for more details about build process. Discuss it. We will see in a few slides how we can make use of customizability and flexibility of gradle in android studio. How to assign more task to the android build process. Lets create a simple task first
  28. If you open the gradle tab on the right hand side of android studio you will see huge number of tasks. All related to build process in android. These are project specific (depends on variants) tasks so don’t worry if you see awkward task names here. This task list can also be seen by issuing gradlew tasks command in studio terminal. Show it in studio. And because of the beauty of gradle these pre-defined tasks can be extended to do more. We will see how in coming slides (append multiple doFirsts and doLasts). All these tasks are related to the build process.
  29. We can use task dependencies to automate tasks. We can make the clean task depend on this task, so whenever we perform a clean project the apks in the output folder are copied to our custom location. And then clean does its stuff and deletes everything from the build folder We want this task to run every time after a particular (or any) apk is generated. We can use finalizedBy here. e.g. assembleDebug.finalizedBy apkLatestCopier. See it in action
  30. So now we know about: Task reusability by Typed tasks, task dependencies, Gradle wrapper, android build process and tasks, and creating our own custom tasks in android studio
  31. One last thing to cover before moving any further is gradle wrapper. We all know the plugin called “'com.android.application'” we use it in app level build.gradle (usually first statement) We will see what tasks are added when we apply java plugin in demo If your build logic is getting complex, it is a recommended practice to separate out common logic into a separate gradle file. There are several other ways to apply a plugin. Like inside buildscript or in plugins block or from libraries. Those are out of scope of this session.
  32. Applying binary plugins in build gradle files. Application plugin gives gradle the ability to run an application. We’ll see in a demo (strictly java). The plugins are picked from jCenter or mavenCentral unless specified otherwise
  33. A simple script plugin for renaming default android apk name. You can create separate task for this or directly loop through the variants in module’s build.gradle. This is just a demo of script plugin and applying it
  34. So now we know about: Gradle plugins, its types, creating and applying script plugin in android studio, running a java application using gradle
  35. We can define methods and variables in gradle like we do in java and we can use that anywhere in the gradle file as long those are in scope. Lets see how we can use this in android studio
  36. One recommended practice with android is upgrading the version of apps everytime before install. But we have do it manually. Using gradle to automate this process. There can be many ways to do this. Lets see using timestamp (we can use svn revision, a separate properties file etc.). <<NEXT>> This is how to define variables and methods in gradle. See the demo
  37. Gradle can treat manifest like a regular file and update it. You can see here the manifest is updated with latest version code Note: Looping through all the build variants Dynamic task creation and dependency Importing and using Pattern --------------------------------------- Like these tasks you can think of and create your own gradle tasks
  38. We have seen android build process and extending the process to suit our needs. Creating standalone and dependent gradle tasks. In this section we will see android specific gradle stuff
  39. We all know about product flavors, we discussed about in prev meetup too. Here is a little recap. We will all of these in a few slides This is how to define product flavors inside android closure
  40. Variants and sourceSets created by two product flavors: flavor1 and flavor2. When product flavors are added android automatically generates gradle tasks related to flavors. e.g. the above flavors will generate tasks like assembleFlavor1Debug, assembleFlavor2 etc. Which finally leads to flavor specific apk generation
  41. Adding flavor specific dependency is useful when we don’t the whole project to depend on something that is not needed in release versions. Like it doesn’t make sense to ship your app with junit, which is only needed for local testing Every product flavor can override default config values. Here versionCode is overridden by flavor1 and minSdkVersion by flavor2. Let’s see what are the other configurable fields in flavor and default config before moving any further.
  42. The default configuration is inherited by all product flavors and has same properties as a product flavor. This means whatever that goes inside default config can go in a product flavor These are few of the properties. Discuss a few of these properties. As you can see there are a lot of properties that can go in default config and can be overridden in product flavors. Back to configuring product flavors
  43. Product flavors can be grouped together via dimension attribute and will result in multi-flavor build variants. Rest is self explanatory. Android creates variants that are all possible combinations of flavors of different dimensions and build types
  44. Variants can be filtered easily. This filtering will be reflected everywhere. Like in build variants tab of left hand side of studio. Variant specific task creation etc. See it in action
  45. Build config is an auto generated field and can be found in generated folder
  46. Adding buildConfigField and resValue to flavors
  47. Prev slide configuration generates something like this Resulting BuildConfig java class. Now you can use these flavor specific constant anywhere in your main source. (BuildConfig.flist, BuildConfig.shortcode, etc.)
  48. Now this is for debug purposes and should not be shipped with release version. To make sure that happens we use flavorCompile syntax. This will enable stetho in a particular flavor of application. Show in code. Filter variant to exclude stetho-release variants. One usecase before demo.
  49. Configuring flavorCompile and product flavor for stetho bridge
  50. Fitering stetho bridge variants to exclude stetho in release builds. That’s it from stetho lets move back to android studio
  51. When you want to generate apks for the build variants, you can either select and run each variant. Or you can save the configuration (for all apk generation) or run gradle task. Lets see that from android studio
  52. Sometime we need to use some properties in manifest that are defined in manifest or are configured based on product flavors like the package name.
  53. As you can see there are many many configuration options available. Lets look at a few of these. We will not spend much time in these configuration options, it is readily available in the mentioned link
  54. We all know about the default config block/closure. Here we specify application ID targetSDKVersion etc. Next we have the data binding block. This is a very useful feature in android that got released in IO15. This is used for declarative layouts creation and minimizes the glue code required. If you don’t know about it is highly recommended that you look it up or you can check out the slides uploaded in one of the old meetups titled “Take a bite of android marshmallow”
  55. Lint is an awesome tool for analysis of error prone areas of our codebase. We can configure it’s properties in this block
  56. Type of encoding of source files. JAVA version compatibility for source code, Java version compatibility for generated bytecode. If you have various versions or newer versions of java you might wanna check out this option. Configurations for packaging options
  57. Aapt – android asset and packaging tool. You can select which assets or asset patterns to ignore. Which extension types to ignore while compressing. Error configurations etc. dexOptions is relatively new. It requires latest gradle plugin, build tools and marshmallow. Supports incremental builds. It is experimental and may not work. Whether to pre dex libraries for faster builds. Number of threads for dexing. By default it is 4 (I think)