Optimize the speed of building your Android projects

Optimize the speed of building your Android projects

Improving build speed in Android ... to measure the build speed impact of various changes to the project. It seemed like the perfect opportunity to try and fix the build speeds of the project. Android's build system...

Improving build speed in Android ... to measure the build speed impact of various changes to the project. It seemed like the perfect opportunity to try and fix the build speeds of the project. Android's build system...

Recently, I undertook the task of migrating the Android codebase at Kure to AndroidX. It seemed like the perfect opportunity to try and fix the build speeds of the project. Android’s build system, Gradle, has always had a bad rep for being slow and resource intensive, but I was quite surprised at how minor changes to the project’s build configuration could massively improve the build speeds.

To give you a sneak peek of the time I was able to shed from our clean builds, here’s a before and after metric from the build scan.

Going down from 5.5 minutes to 17 seconds?? That’s bonkers

It’s easy to go overboard with optimizations that you can perform to bring down your build time even further. But I am going to intentionally focus on the minor, painless measures I took to come close to this metric for the sake of keeping this post beginner friendly.

But first!

Before starting off with the optimization, it’s important to benchmark our project to see how long it currently takes to build. Gradle has a handy scan option that you can use to analyze the performance of your task. Fire up the terminal on Android Studio and execute the following command:

./gradlew assembleDebug --scan

Once the build completes successfully, it will prompt you to accept the terms of service to upload your build scan results. Type **yes **to proceed. Once it’s done publishing, you will get a link on the terminal to check your build scan. Open the link.

There are quite a few options on the site, but for the sake of brevity, we’re only gonna take a look at what’s most important.
The summary** **view shows you a summary of the tasks that were run and how long it took for them to complete. But what we’re interested in here is the Performance section. It gives you a more detailed breakdown of the total build time as shown below.

Under the performance section, there’s a **Settings and suggestions **tab that gives you suggestions on how you can improve your build speeds. Let’s check that out.

We can find some easy fixes for our build speed in this section. So let’s go ahead and apply these suggestions in our project.

Step #1: Update your tooling

The Android team is constantly improving and evolving the Android build system. So most of the time you can receive significant improvements just by adopting the latest version of the tooling.

At the time of this refactor, our project was on **version 3.2.1 **of the Gradle plugin for Android Studio (which is a few versions older than the latest release).

You can visit **this link **to get the version for the latest release of the Gradle Plugin.

At the time of writing this post, the latest version happens to be version 3.4.0.

But it comes with a gotcha that we need to keep in mind for later:

https://developer.android.com/studio/releases/gradle-plugin

When using Gradle 5.0 and above we will need to explicitly increase the heap size to ensure our build speed doesn’t worsen. We will come back to this in just a minute.
Open the top level** build.gradle **file which you will find in the root of your project and add the following line in the dependencies section:

classpath 'com.android.tools.build:gradle:3.4.0'

You will also need to update the **distribution URL **in the gradle wrapper properties file located at ***gradle/wrapper/gradle-wrapper.properties.***Update the URL to the following.

(This link will be available on the Android Gradle plugin release page.)

distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip

If you are using Kotlin in your project, you will run into an error if your Kotlin Gradle plugin’s version is less than 1.3.0. If that’s the case, use the IDE’s prompt to update your Kotlin Gradle plugin to the latest version (which at the time of writing this post happens to be version 1.3.31).

Alright, let’s run the build again from the terminal to see if we achieved any improvements.

Step #2: Update your configurations

So we were able to shed around 2.5 minutes from the build time but it’s still not good enough. Upon investigating the build logs in the terminal, I came across one line which is of interest to us:

Incremental compilation basically prevents wasteful compilation of the entire set of source files and instead compiles only the files that have changed. Looking at the logs, it’s clear that we’re not taking advantage of this feature. It suggests us to use ***android.enableSeparateAnnotationProcessing=true ***but since we’re using Kotlin in our projects, we should not be using the ‘annotationProcessor’ configuration anyways.

Luckily, Kotlin version 1.3.30 added the support for incremental annotation processing.

https://kotlinlang.org/docs/reference/kapt.html

So let’s

  1. Change the **annotationProcessor **configuration to kapt
  2. Enable the incremental annotation processing experimental flag

Open your module level build.gradle file and add the following line to the top of the file:

apply plugin: 'kotlin-kapt'

Next, change all annotationProcessor configurations in the dependencies section to use kapt. Here’s an example:

//Before
annotationProcessor 'com.google.dagger:dagger-compiler:2.9'
//After
kapt 'com.google.dagger:dagger-compiler:2.9'

Now open up your ***gradle.properties ***file located at the root of your project and add the following line:

kapt.incremental.apt=true

Let’s run the build again. 🤞🏼🤞🏼🤞🏼

Alright, looks like we’re getting there.

Step #3: Gradle Properties

We’re in the last stage now. Remember the gotcha we came across while updating our Gradle plugin version? Turns out the newer versions of Gradle reduce the heap size to 512 MB. This is to make sure lower end machines don’t choke up. I am on a 16 gig machine so I can afford to give around 2–3gigs to the Gradle daemon, but your mileage may vary.

Open the ***gradle.properties ***file located at the root of your project and add the following line. Remember to select the size according to your requirements and machine specification.

org.gradle.jvmargs=-Xmx3072m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

While we’re at it, let’s also enable parallel builds and configure on demand in the properties.

Here’s what my final ***gradle.properties ***file looks like:

org.gradle.jvmargs=-Xmx3072m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.configureondemand=true
kapt.incremental.apt=true

  • org.gradle.parallel - This flag allows Gradle to build modules within a project in parallel instead of sequentially. This is only beneficial in a multi-module project.
  • org.gradle.configureondemand - This flag configures only the modules needed by the project, instead of building all of them.

With these, let’s see where we are on our build speed metric:

And there we go.

Closing remarks

This is by no means an extensive coverage of all the ways one can optimize the build speed of their project. There are tons of other things which I did not go over in this post like using minSdk 21 when using MultiDex, pre-dexing your libraries, disabling PNG crunching, and so on — to name a few.

But most of these configurations require a deeper understanding of Android’s build system and experience working on large multi-module projects (which is where the benefits are most apparent). The steps I mentioned above are easy to incorporate in a project even by junior devs and have considerable payoffs. I hope this helps you trim down your build speeds!

Choose Java 11 or the “other” one…Kotlin

Choose Java 11 or the “other” one…Kotlin

Most of the Java applications are written in Java 8 nowadays and people are looking around to upgrade to Java 11 or even migrating to Kotlin. Both are promoted as the new way to go and both have their own strengths and weaknesses. Upgrading to Java 11 might be an obvious next safe step to do. But what if you could migrate to Kotlin with the same effort?

Most of the Java applications are written in Java 8 nowadays and people are looking around to upgrade to Java 11 or even migrating to Kotlin. Both are promoted as the new way to go and both have their own strengths and weaknesses. Upgrading to Java 11 might be an obvious next safe step to do. But what if you could migrate to Kotlin with the same effort?
This would bring you additional advantages like: data classes, very concise list manipulations, extension functions, DSL's and even more to get your code more readable and maintainable.

Considering the Kotlin migration, the first questions that pop up are: What are the wise steps to take? And where to start?
Some experiences and thoughts answering these questions will be shared during this live coding session.

What will the audience learn from this talk?

  • how to migrate a Java service to Kotlin in concrete and independent steps
  • the difference in idioms between the two languages
  • how to use Kotlin in an idiomatic way Finally the audience will have a complete view on how to migrate successfully.

Java Vs. Kotlin: Which One Will Be the Best in 2019?

Java Vs. Kotlin: Which One Will Be the Best in 2019?

Which programming language comes to mind when you hear Android app development? Java or Kotlin? Here is a detailed explanation of the difference between the two programming languages.

Which programming language comes to mind when you hear Android app development? Most probably, you will immediately think of Java. This is because of the vast number of Android apps that are developed in Java.

Developers around the world are still wondering if Kotlin has any future or not. But with the introduction of Kotlin in Google I/O two years back, Kotlin has made its own place in the Android application development market.

Kotlin

Kotlin is the latest statically-typed, open-source programming language that can run effectively on the Java Virtual Machine (JVM). Kotlin is developed by JetBrains and is officially supported by Google.

The recent survey of Jexenter has placed Kotlin as 6th in the top technology trends. To compare Kotlin with Java, we need to understand its benefits and drawbacks. Business leaders like Pivotal, Atlassian, Pinterest, Evernote, and Uber are now using Kotlin for Android app development.

As per the recent statistics by App brain show the Kotlin language holding 25.30 percent of market share among the top apps of 2018, with 40.76 percent of installs of the new apps.

For more on the market share value of Kotlin-based industry, check out this article.

Why Kotlin Is the Leading Programming Language for Android App Development?

Improved Efficiency

With a concise and intuitive syntax, Kotlin provides an increase in the efficiency of the working team. Fewer code lines and less time are required to write and deploy a program. As a result, you will get your app developed quickly.

100 Percent Java-Interoperable Programming Language

In easy terms, Java methods can be called from Kotlin. This feature is beneficial not only for the developers but for the companies that have a large Java code base.

Ease of Maintenance

Kotlin for Android developers is easy to maintain with the support of a large number of IDEs, which includes Android studio and several other SDKs. Additionally, developers can work with any toolkit they are comfortable with.

Reliable

The latest version of Kotlin is reversely compatible with all the previous versions. This resolves the biggest pain point of Android developers: dealing with multiple versions.

Easy to Learn

Aspirants can learn Kotlin much easier, as compared to Java because it doesn’t require any prior mobile app development knowledge.

Android Studio Support

Android Studio provides extended support and adaptation tools. Developers can work simultaneously on both the languages.

Drawbacks of Kotlin

Compilation Speed

Developers have reported about the fluctuation in the compilation speed of Kotlin codes. In some cases, it is very fast, and in other cases, it is significantly slower.

Less Community Support

Kotlin has a small developer community that results in limited resources to learn the language. There will be a lot of queries which will be unanswered.

Scarcity of Developers

There are very limited numbers of developers available for Kotlin. The talent gap in the Android app development market has increased in regards to Kotlin.

Java

Java is considered one of the best programming languages for app development. The object-oriented programming is just a basic feature. It serves a lot more than just Android app development support. Here are few of the pros and cons of java.

The recent TIOBE index of December 2018 shows Java as number one among the top programming languages.

How Java Is Still Better Than Kotlin?

Portable

With the help of the platform-agnostic Java Virtual Machine, Java programs can run on almost any system. As a result, Java has the majority of Android applications.

Large Community

Developers get help on almost any issue, bug, or problem of their Java code with the help of large GitHub and Stack Overflow communities.

Cross-Platform

Java language is not just limited to Android app development. Java supports cross-platform app development as well.

Resources

As Java has developed the Android, it has already existing libraries and SDKs to help in the development process.

Where Does Java Lag behind?

Speed

Java requires more memory and is much slower when compared to other languages.

Type-Heavy Language

Java requires long codes that result in more time consuming with more errors and bugs.

Conclusion

If you are a developer, then you need to upgrade your skills to the latest trends. There is no doubt that Java is still the king of Android programming, but as a developer, you need to be up to date. I am sure the above advantages of Kotlin must have convinced you why you should, at least, learn Kotlin for Android app development.

Thanks for reading ❤

If you liked this post, share it with all of your programming buddies!

Build Spring Boot Apps using the Kotlin Programming

Build Spring Boot Apps using the Kotlin Programming

In this tutorial, you will build a Spring Boot application from scratch, using Kotlin as the main language. You will learn how Kotlin works with Spring and how to integrate the code with other Java libraries.

Java, once considered the coolest kid on the block, is now seen by many as a legacy language. Some developers believe it stopped evolving when it comes to features and many consider it too verbose, claiming it makes code hard to read.

JetBrains, the company behind IntelliJ decided to do something about it and create a modern language that would run inside the Java Virtual Machine. This project became Kotlin, a quickly growing and popular language.

Google then announced official support for Kotlin on Android, further accelerating its adoption. Many companies started to replace Java with Kotlin as their main language to take advantage of the new features it provides. Kotlin is now an increasingly important language for developers inside the JVM ecosystem to know and understand.

In this tutorial, you will build a Spring Boot application from scratch, using Kotlin as the main language. You will learn how Kotlin works with Spring and how to integrate the code with other Java libraries. By the end, you will have a secure Spring application running in Kotlin that authenticates users via OAuth 2.0.

Create the Kotlin Application with Spring Initializr

Let’s start by creating the project using Spring Initializr.

Go to the Spring Initializr website and type in the following information:

  • Project: Gradle Project
  • Language: Kotlin
  • Group: com.okta
  • Artifact: spring-kotlin
  • Options:
  • Package Name: com.okta
  • Dependencies: Spring Web

You can also use the command line to get the same result:

curl https://start.spring.io/starter.zip \
       -d language=kotlin \
       -d style=web \
       -d packageName=com.okta \
       -d name=spring-kotlin \
       -d type=gradle-project \
       -o spring-kotlin.zip

You can choose to use either Maven or Gradle. Since Gradle is the most common build tool to go along with Kotlin, this tutorial will go for it.

Import the project into your favorite IDE. Although you can choose your favorite, I strongly recommend IntelliJ, from the creators of Kotlin.

If you use IntelliJ, you don’t need to download Kotlin since it ships included with the IDE. Otherwise download the latest release.

Once you’ve imported the project, it will have a single file named SpringKotlinApplication.kt. Inside the file, you will find the following code:

@SpringBootApplication
class SpringKotlinApplication

fun main(args: Array<String>) {
   runApplication<SpringKotlinApplication>(*args)
}

This file contains the main function, which bootstraps the application. To declare a function in Kotlin you use the keyword fun, followed by its name, the parameters, and the return type. When there is no return type, you don’t specify anything, which is the case with this function.

Here you also have a class annotated with SpringBootApplication that will behave the same way as in Java. You may also notice that SpringKotlinApplication is not declared as public. The reason is pretty simple: all classes are public in Kotlin by default!

Next, create a REST endpoint. As with Java, you need to create a class and annotate it with RestController.

Inside src/com/okta/controller/, create the class GreetController with the following code:

package com.okta.controller

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class GreetController {

   @GetMapping("/greet")
   fun greet(): String {
       return "Hello, World"
   }
}

As with classes, all functions are public by default so there is no need to add an explicit modifier. The other big difference is the function declaration: the return type goes after the name of the method, separated by a colon.

That’s it! You have created your first application in Spring using Kotlin.

Run the application by executing the class SpringKotlinApplication in your IDE (or with ./gradlew bootRun). After that, go to http://localhost:8080/greet and you should see the following greeting message in your browser:

Hello, World!
Make the Kotlin Application Endpoint Dynamic

You can make the message in your endpoint available to greet any person. Let’s update it to receive a name as the input and display a personalized greeting message:

Inside the GreetController file, make the following changes:

@GetMapping("/greet")
fun greet(@RequestParam("name") name: String): String {
   return "Hello, $name!"
}

The greet function now receives a parameter called name. In Kotlin, you declare parameters by specifying the name first, followed by a colon and its type. This is the same convention used to declare a function. The RequestParam annotation is placed in the same position as you would in Java code.

You might also have noticed that you didn’t have to concatenate Strings to display the input value. Kotlin has a built-in feature called String templates, which allows you to reference a variable by putting the $ sign, followed by the variable name itself.

Run the application again and open http://localhost:8080/greet?name=john. You should see the message below:

Hello, john!

Great! With very little effort, your application can greet any user by name from now on.

Extensions: Say Farewell to Utility Classes

Your endpoint is working, but there is little problem with the current version: the user might input their name in all lowercase characters.

To fix this, you can capitalize the first character of the name before returning it. In Java, you usually achieve this by creating or importing a utility class that you then call to do the action. For instance, you could import StringUtils from Apache Commons to your project and add the following code:

String capitalizedName = StringUtils.capitalize(name);
return "Hello, " + capitalizedName + "!";

In Kotlin, you don’t need to use a utility class. Instead, use a feature called extension functions. This feature allows you to add functions to existing classes, even when they are final or outside your project scope. All you have to do is inform the class you want to extend with the method to make it available:

fun String.capitalize(): String {
   if (this.isEmpty()) {
       return this
   } else if (this.length == 1) {
       return this.toUpperCase()
   } else {
       return this[0].toTitleCase() + this.substring(1).toLowerCase()
   }
}

The function above ensures the first letter of the word is in uppercase and all others are in lowercase.

The extension function is declared in the same way as a regular function. The only difference is you have to specify the class you want to extend before the name of the method. In our case, you want to add a capitalize function in the String class, which means you need to declare the function as String.capitalize.

Go to the greet function and make the following changes:

@GetMapping("/")
fun greet(@RequestParam("name") name: String): String {
   val capitalizedName = name.capitalize()
   return "Hello $capitalizedName!"
}

Although you declared the function in your project, you make the call as it was defined inside the String class! This eliminates the need to create utility classes and concentrates the methods in one place, making it easier to find the function you want to use.

Restart the application and reload http://localhost:8080/greet?name=john you should see the following message:

Hello, John!

There you go! Now your application displays the name with a capitalized first letter :-)

When: An Enhanced Switch Operator

Take a closer look at the capitalize method you created earlier and note that all three if statements are related. This is a common programming pattern the creators of Kotlin decided to handle with a new keyword: when.

You can think of the when as an enhanced switch statement. In Java, you can verify if an enum is of a particular type by using switch:

switch(myEnum) {
   case ENUM_A:
       // code here
   case ENUM_B:
       // code here
   default:
   // code here
}

This is very useful to make cleaner code, but it’s also limited because it can only verify the type of the variable. In Kotlin, when lets you verify any condition. That way you get cleaner code while performing more advanced operations.

Let’s rewrite the previous capitalize method using when.

fun String.capitalize(): String {
   when (this.length) {
       0 -> return this
       1 -> return this.toUpperCase()
       else -> return this[0].toTitleCase() + this.substring(1).toLowerCase()
   }
}

In this new version, you verify the length of the current String and return the result based on its length.

But the power of when doesn’t end there. You can even mix up different types of conditionals in the same clause. For instance, you could write the above method like this:

fun String.capitalize(): String {
   when {
       this.isEmpty() -> return this
       this.length == 1 -> return this.toUpperCase()
       else -> return this[0].toTitleCase() + this.substring(1).toLowerCase()
   }
}

As you can see, one of the conditionals calls isEmpty(), while the other one verifies the length of the String. As long as your expression can be evaluated as a boolean value, you can use it inside of a when expression.

Leverage Java Libraries In Your Kotlin App

Although your application is still very simple, you can make it look like a professional app with just a few small tweaks. For instance, greet the logged-in user by name instead of asking for it as a parameter every time.To make that work of course, you need to implement user authentication first.

Authentication is a vital part of any modern app, but can you incorporate auth into your project without layers of configuration and code? The answer is yes! We’ll use OAuth 2.0 to authenticate users and display a greeting message based on the user’s name with no headache.

Recall how Kotlin can use libraries from the Java ecosystem? Add Okta’s Java library written to handle the OAuth 2.0 flow inside your application.

To start, open the build.gradle.kts file. Inside the dependencies tag, add the following line:

implementation("com.okta.spring:okta-spring-boot-starter:1.2.1")

Your dependencies object should look like this:

dependencies {
   implementation("org.springframework.boot:spring-boot-starter-web")
   implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
   implementation("org.jetbrains.kotlin:kotlin-reflect")
   implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
   implementation("com.okta.spring:okta-spring-boot-starter:1.2.1")
   testImplementation("org.springframework.boot:spring-boot-starter-test")
}

This dependency adds both Okta and Spring Security to your project. They make it simple to ensure only authenticated users can access protected areas of your application.

If you don’t have an Okta account, go ahead and create a free one. After registering, go through the following steps:

  • Log into your account
  • Click Applications
  • Click on Add Application. You will be redirected to the following page:

Now that you have your Okta application, you can use it to authenticate users in your Kotlin app.

Add the following environment variables to your application:

OKTA_OAUTH2_ISSUER=https://{yourOktaDomain}/oauth2/default
OKTA_OAUTH2_CLIENT_ID={CLIENT_ID}
OKTA_OAUTH2_CLIENT_SECRET={CLIENT_SECRET}

You will find {CLIENT_ID} and {CLIENT_SECRET} on the application page in Okta’s dashboard. To find it, follow the steps below:

  • In your Okta Admin Console’s menu, go to Applications
  • Select the “hello-world” application
  • Click on the General tab

You should see both values inside the Client Credentials area.

Your {yourOktaDomain} will be visible in your Okta dashboard, just click on Dashboard in the menu. You will see the Org URL in the right upper corner.

The last step is to modify your greet endpoint to pull the name from the authenticated user. Go to the GreetController class and apply the following changes:

package com.okta.controller

import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.security.web.bind.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.core.oidc.user.OidcUser

@RestController
class GreetController {

   @GetMapping("/greet")
   fun greet(@AuthenticationPrincipal user: OidcUser): String {
       val capitalizedName = user.givenName.capitalize()
       return "Hello, $capitalizedName!"
   }

   fun String.capitalize(): String {
       when {
           this.isEmpty() -> return this
           this.length == 1 -> return this.toUpperCase()
           else -> return this[0].toTitleCase() + this.substring(1).toLowerCase()
       }
   }
}

The main difference here is that you are not receiving the user as a parameter anymore. Since you annotated the function with AuthenticationPrincipal, Spring knows that you want to retrieve the current user and will do it automatically.

That’s it! You now have an application with secure authentication out of the box. Go to http://localhost:8080/greet. and you should be redirected to the Okta’s login page:

Once the user enters their username and password they’ll be redirected to your greeting page again. In my case, I see the following:

 Hello, Daniel!

Congratulations! You just finished your first app written in Kotlin. You also took advantage of the JVM ecosystem by adding authentication in a simple, secure way. Take a look at the final code on GitHub.

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading

☞ Angular 7 + Spring Boot CRUD Example

☞ Angular 8 + Spring Boot 2.2: Build a CRUD App Today! 

☞ Top 5 Kotlin Features That Every Android App Developer Must Know

☞ Java Vs. Kotlin: Which One Will Be the Best in 2019?



Originally published by Daniel Pereira at https://developer.okta.com