Android Things - Quick Overview And Getting Started

On December 2016 Google released first Developer Preview of Android Things, their IoT platform, based on the Android operating system. I’m not going to elaborate here on details, you can find all you need on the official website but there are 3 interesting points to make about the fairly new OS:

  1. It’s done by Google. There are dozens of IoT platforms now in the “Linux box” category, but somehow I have a feeling that Google is the most capable entity to provide standard OS for IoT applications.
  2. In 2017 there are two categories of IoT devices. The small, mostly battery powered devices (think smart sensors, beacons etc), based on microcontrollers (right now ARM Cortex-M architecture seems to be dominating that field). Those devices have sub-1MB storage capacity and sub-100KB RAM capacity, running clock speeds below ~100MHz. The second category is “Linux box” devices, which are basically smartphone class right now (think something like mid-end smartphone circa 2013) with the capacity to run sophisticated software (i.e. Convolutional neural network, advanced networking etc.). Android Things is targeting the latter category.
  3. It is basically and Android OS, running ART runtime environment, which means we can leverage all the Android tools, methodologies and libraries we love and use every day. And most importantly, we can write Kotlin for it!

How to get started with Android Things?

First, I recommend watching this presentation from Google I/O 2017 with the current overview of the platform:

Google I/O 2017 Android Things presentation

Second, you need to buy some hardware. But if you don’t have experience with electronics I don’t recommend starting straight from Android Things capable device. I recommend starting with inexpensive Arduino starter kit. There are two reasons why:

  • You will learn all the essentials (basics about electronics engineering, different parts, current, wiring a breadboard) on a cheap device that loads your code and boots in a matter of seconds. If you mess something up you won’t burn fairly expensive device like Raspberry Pi. And all the basics are the same on both platforms.
  • You will be able to use the same parts for Android Things development. Same breadboards, jumper wires, LEDs, resistors, LCDs etc.

Arduino kit by Kuman Arduino kit by Kuman

I recommend cheap Arduino UNO R3 clone starter kit. I bought a starter kit from Kuman for around ~30USD from Amazon, and the quality of the Arduino board was quite nice. In my opinion, the UNO R3 version is best for learning purposes (there are dozens more Arduino boards) cause this one is the “standard”, easy to learn (pins are clearly marked so it is super easy to wire it up) and most of the tutorials use this board. When choosing your Arduino kit, make sure it has some female to male jumper wires included since the Raspberry Pi 3 uses male GPIO ports. Arduino uses custom IDE and the language you program in is based on C and C++. The IDE is very mature and a pleasure to develop in. After getting your starter kit, I would recommend going through this tutorial series by Jeremy Blum. It goes through all the basics of electronics engineering, almost all the knowledge you acquire will be directly transferred to Android Things development.

Arduino wired up with LCD Arduino wired up with the LCD screen

After playing a bit with Arduino and going through the basics you can switch to Android Things. For the first development board, I would recommend Raspberry Pi 3 Model B. It is very popular device, you can get it in any country for about 30-40USD. On a recent Android Developers Backstage podcast, Android Things guys mentioned that this device is by far the most popular now in the community, which makes troubleshooting a lot easier. All the flashing and development instructions are available on the official website. As always, Stack Overflow is very helpful, especially now, during the preview phase were the official docs aren’t mature yet.

Raspberry Pi 3 blinking led Hello world of electronics: a blinking LED

Raspberry Pi 3 with Arduino kit LCD Arduino 1602 LCD screen wired for Raspberry Pi with Android Things

Kotlin null safety explained

In my Java developer’s career, NullPointerException is the single most common runtime error I encounter. And according to this research, I’m not an exception (pun intended!). Even the inventor of null reference, computer science pioneer Tony Hoare called it The Billion Dollar Mistake.

Fortunately, Kotlin introduces the concept of null safety. If you are using pure Kotlin (without mixing it with Java code) you encounter two types of references:

  1. The Non-Null type:
var nonNullReference: String = "I can't be null!"
nonNullReference = null // Compile-time error

The non-null string’s type is written as 'String'

  1. The Nullable type:
var nullableReference: String? = "I'm a nullable string"
nullableReference = null // Compiles just fine

The nullable string’s type is written as 'String?', with question mark suffix

This way we’re sure that the non-null reference will never throw dreaded NullPointerException. But what happens if we try to call some function on the nullable reference? It won’t happen because it will not compile. The compiler doesn’t care if the reference is null or not:

println(nullableReference.length) // Compile-time error

We can’t call functions on nullable references without explicitly handling the nullability. There are 3 basic ways to do that:

  1. “Classic” null check:
if (nullableReference != null) {
println(nullableReference.length)
println(nullableReference.hashCode())
println(nullableReference.capitalize())
}

This is the exact same way as every Java coder did thousands of times. Compiler knows all the uses of our nullableReference inside the if block are safe, cause we checked it’s not null before the calls are being made.

  1. Safe call:
println(nullableReference?.length)

The Kotlin safe calls are being made using the special operator '?.' - in our case, the expression println(nullableReference?.length) will not crash at runtime but instead return null. If the nullableReference wasn’t null it would return the string’s length as 'Int?' (which itself is a nullable integer).

  1. Non-null asserted call:
println(nullableReference!!.length) // NPE thrown at runtime

While using a double exclamation mark (a.k.a “double bang”) we are stating that we’re 100% sure our nullableReference is not null. This is the same behaviour as classic Java call without doing null-check. In our case, the app will crash and the NullPointerException will be thrown! This notation was made ugly on purpose, it is basically an indicator of code smell and should be used only when you want your app crash at runtime whenever there’s null reference. In most cases you should either:

  • Use non-nullable types whenever possible or
  • If you are using nullable type, do a safe call or a null-check

But what if we are mixing Kotlin with Java?

Fortunately, when our Java code is properly annotated it will behave exactly the same as Kotlin code. Kotlin compiler recognizes many popular annotation frameworks, including Android annotations framework. If developer properly annotates the code with '@NotNull' and '@Nullable' annotations, the compiler will see those references as if they were Kotlin types. Fortunately for us mobile developers, Android framework and many popular libraries are already annotated properly.

If for whatever reason the Java code you are using wasn’t annotated, Kotlin introduces the concept of platform types. This means that whenever you are using such code, it will be treated the same as in Java. This was done for convenience (so the code wouldn’t be filled with question marks and double-bangs). The platform type string is marked as 'String!'.

10 reasons why Kotlin will be big

In this post, I’m going to list 10 reasons why in my opinion Kotlin will become a popular programming language. Keep in mind those are my personal views.

  1. The main reason: Java programming language appeared 22 years ago which makes it quite an old technology. Java was improved upon a lot since 1995 but had to maintain most of its core features and syntax. The code written in Java is famous for not being very readable and maintainable. I’m not going to elaborate here, it would require a separate post to list all the issues with Java as a programming language in 2017.

  2. Kotlin is extremely easy to learn for an experienced Java developer. Basically, Kotlin could be called “Java 2.0 without the syntax compatibility”. I’m not the best Java developer out there nor the most experienced, but it took me around 5 days of playing with Kotlin (in the evenings, for about 2-3 hours each session) to be able to write production Kotlin code that was on pair with my Java code in terms of quality. There are a lot of new features and concepts (especially if you come from Java < 1.7-1.8) but you can learn them gradually. Kotlin doesn’t have a steep learning curve similar to Scala. If you’re a decent Java or C# coder you will be able to grasp it really quickly.

  3. Kotlin is developed by very competent people with a lot of support behind them. Four weeks ago at Google I/O 2017 Android Development Tools team announced official Kotlin support for Android. It is well proven that Open Source projects (especially programming languages) have greater success rate with support from big commercial organizations.

  4. One of the main design principles behind Kotlin is Java interoperability. I can tell from my own personal experience that this is not just some marketing BS. It really works well with Java! And by “Java interoperability” guys at JetBrains mean mixing Java and Kotlin in your codebase as well as using Java libraries in your 100% Kotlin app (my experience here is limited to Android development but I have no reasons to doubt it will behave the same in some more “classic” Java uses).

  5. Android OS is HUGE! Right now there are around 2 billion Google Android devices in the wild. Add around 500 to 700 million devices without “Google Experience” package and it is by far most popular computer OS in history. And it will be more popular - install base will probably double by the end of 2021. Google is also developing other platforms based on Android OS, most notable Android Things. And Android development needs a modern programming language. Kotlin is an obvious choice here.

  6. Kotlin is being designed to be ubiquitous and universal. Right now it compiles to Java bytecode and can run on any JVM which supports Java 1.6 or later. It also compiles to JavaScript. Kotlin team is also working with LLVM on Kotlin/Native. All those efforts might in the future result in something that might be called “semi-universal computer language”, meaning it could be used in most development tasks (frontend, backend, high and low-level development).

  7. Kotlin is modern computer language which has all the “cool” features needed in 2017. Java <1.8 is not. Simple as that.

  8. Kotlin is designed with safety as its core principle (similar to Swift). Some people don’t like languages designed to shelter programmers from their own stupidity, but I personally am a big fan of such solutions. We are imperfect people and operate in the imperfect world (limited resources, deadlines, unskilled developers on our teams) and this kind of tradeoff in most cases is an advantage.

  9. Kotlin was designed by a commercial entity with a goal of being an industrial language used for real-life applications. This might sound like something that is a marketing jibberish, but IMO, some of the languages designed by academics have a little bit different DNA and aren’t that suitable for real world applications as Kotlin.

  10. Kotlin is FAR MORE readable than Java code. There are multiple reasons for that - its syntax is more concise, there is a lot of syntactic sugar built in (i.e. Data objects). In my personal experience, when I refactor my Android code using Kotlin I end up trimming around 20 to 40% of my code “volume”, without resolving to any nasty one-liners or ugly hacks.

To sum it all up, there are computer languages which have some of those advantages, but so far there was no single language which combined them all. The rapid and wide Kotlin adoption only proves my thesis - Kotlin WILL be big!

First post - Hello World!

Hi! This is first test post on this blog!

Testing embedded YouTube video:

Code

This is just a sample of some Kotlin code snippet.

// Standard onClickListener

view.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
toast("Hello World!")
}
})

// Proper "Kotlinish" onClickListener (with Anko)
view.setOnClickListener { toast("Hello World!") }

More to come…