Android life cycle aware components

What is a life cycle aware component?

A life cycle aware component is a component which is aware of the life cycle of other components like activity or fragment and performs some action in response to change in life cycle status of this component.

Why have life cycle aware components?

Let’s say we are developing a simple video player application. Where we have an activity named as VideoActivity which contains the UI to play the video and we have a class named as VideoPlayer which contains all the logic and mechanism to play a video. Our VideoActivity creates an instance of this VideoPlayer class in onCreate() method

 

 

Now as for any video player we would like it to play the video when VideoActivity is in foreground i.e, in resumed state and pause the video when it goes in background i.e when it goes in the paused state. So we will have the following code in our VideoActivity’s onResume() and onPause() methods.

 

 

Also, we would like it to stop playing completely and release the resources when the activity gets destroyed. Thus we will have the following code in VideoActivity’s onDestroy() method

When we analyze this code we can see that even for this simple application our activity has to take a lot of care about calling the play, pause and stop methods of VideoPlayer class. Now imagine if we add separate components for audio, buffering etc, then our VideoActivity has to take care of all these components inside its life cycle callback methods which leads to poor organization of code, prone to errors.

 

Using arch.lifecycle 

With the introduction of life cycle aware components in android.arch.lifecycle library, we can move all this code to the individual components. Our activities or fragments no longer need to play with these component logic and can focus on their own primary job i.e. to maintain UI. Thus, the code becomes clean, maintainable and testable.

The android.arch.lifecycle package provides classes and interfaces that prove helpful to solve such problems in an isolated way.

So let’s dive and see how we can implement the above example using life cycle aware components.

Life cycle aware components way

To keep things simple we can add the below lines to our app gradle file to add life cycle components from android.arch library

 

 

Once we have integrated the arch components we can make our VideoPlayer class implement LifecycleObserver, which is an empty interface with annotations.
Using the specific annotations with the VideoPlayer class methods it will be notified about the life cycle state changes in VideoActivity. So our VideoPlayer class will be like:

We are not done yet. We need some binding between this VideoPlayer class and the VideoActivity so that our VideoPlayer object gets notified about the life cycle state changes in VideoActivity.

Well, this binding is quite easy, VideoActivity is an instance of android.support.v7.app.AppCompatActivity which implements Lifecycleowner interface. Lifecycleowner interface is a single method interface which contains a method, getLifecycle(), to get the Lifecycle object corresponding to its implementing class which keeps track about the life cycle state changes of activity/fragment or any other component having a life cycle. This Lifecycle object is observable and notifies its observers about the change in state.

So we have our VideoPlayer, instance of LifecycleObserver, and we need to add this as an observer to the Lifecycle object of VideoActivity. So we will modify VideoActivity as:

Well it makes things quite resilient and isolated. Our VideoPlayer class logic is separated from VideoActivity. Our VideoActivity no longer needs to bother about calling its dependent components methods to pause or play in its life cycle callback methods which makes the code clean, manageable and testable.

Conclusion

The beauty of such separation of concern can be also felt when we are developing some library and we intend it to be used as a third party library. It should not be a concern for end users of our library i.e. developers who would be using our library, to call life cycle dependent methods of our library. They might miss it or may not be aware at all which methods to call (because developers don’t usually read the documentation completely) leading to memory leaks or worse app crashes.

Another use case can be when an activity depends on some network call handled by a  network manager class. We can make the network manager class life cycle aware so that it tries to supply the data to activity only when it is alive or better to not keep a reference to activity when it is destroyed. Thus, avoiding memory leaks.

We can develop a well managed app using the life cycle aware components provided by android.arch.lifecycle package. The resulting code will be loosely coupled and thus easy for modifications, testing and debugging which makes our life easy as developers.

Kotlin Kronicles for Android developers — part 1

Another blog on“why Kotlin”? cliché? Not really. This is more like a “why not Kotlin?” kind of blog post. This blog is my attempt to convince android app developers to migrate to Kotlin. It doesn’t matter if you have little or no knowledge of Kotlin, or you are an iOS developer who worships swift, read along, I am sure Kotlin will impress you (if not my writing).

I am going to show some of the amazing features of Kotlin programming language that makes development so much easy and fun. And makes the code so readable as if you are reading plain English. I read somewhere that “Programming language isn’t for computers, computers understand only 1s and 0s, it is for humans” I couldn’t agree more. There is a learning curve, sure, where isn’t? It pays off nicely. Kotlin makes us do more with fewer lines of code, kotlin makes us productive.

Lets quickly walk over some of the obvious reasons for migrating to Kotlin:

  • Kotlin is one of the officially supported languages for android app development as announced in Google IO 2017.
  • Kotlin is 100% interoperable with Java. Which basically means Kotlin can use Java classes and methods and vice versa.
  • Kotlin has several modern programming language features like lambdas, higher order functions, null safety, extensions etc.
  • Kotlin is developed and maintained by JetBrains, which is the company behind several integrated development environments that developers use every day (or IDEs like IntelliJ IDEA, PyCharm, PhpStorm, GoLand etc).

This is available all over the internet. This is the content of “Why Kotlin” category of blogs.

Let’s talk about something a little more interesting.

Higher Order Functions:

Kotlin functions are first class citizens. Meaning functions can be stored in variables, passed as arguments or returned from other functions. A higher-order function is a function that takes a function as a parameter or returns a function.

This may sound strange at first. Why in the world would I pass a function to another function? (or return a function from another function) It is very common in various programming languages including javascript, swift, python (and Kotlin apparently). An excellent example of a higher function is the map. The map is a higher order function that takes in a function as a parameter and returns a list of results of applying the given function in each item of the original list or array.

checkout the map function above in line 3. It applies the stringStrirrer() function to each item of x. The result of the map operation is in line 4 above.

Data classes:

Java POJOs or Plain Old Java Objects or simply classes that store some data require a lot of boilerplate code most of the times, like getters, setters, equals, hashCode, toString etc. Kotlin data class derives these properties and functions automatically from properties defined in the primary constructor.

Just one line of code to replace the several lines of java POJO. For custom behavior we can override functions in data classes. Other than this Kotlin data classes are also bundled with copy, components etc which allows copying object and de-structuring respectively.

Dealing With Strings:

Kotlin standard library makes dealing with strings so much easier. Here is a sample:

No helper classes, public static methods or StringUtils is required. We can invoke these functions as if they belong to String class itself.

Dealing with Collections:

Same as String, the helper methods in “java.util.Collections” class are no longer required. We can directly call “sort, max, min, reverse, swap etc” on collections.

Consider a bank use case. A bank has many customers, a customer does several transactions every month. Think in terms of objects:

As it is clear from the picture above, a bank has many customers, a customer has some properties (name, list of transactions etc) and several transactions, a transaction has properties like amount, type etc. It will look something like this in Java:

Find the customer with minimum balance:

I don’t know about you but I think the Kotlin way is much more clean, simple and readable. And we didn’t import any helper class for that (Java way needed Collections class). I can read it as plain English, which is more than what I can say for the Java counterpart. The motive here is not to compare Java with Kotlin, but to appreciate the Kotlin Kronicles.

There are several functions like map, filter, reduce, flatmap, fold, partition etc. Here is how we can simplify our tasks by combining these standard functions (for each problem statement below, imagine doing it in Java):

As it is clear from the above gist, we can solve mundane problems with much fewer lines of code. Readability wise I just love it. Above code explanation here:

  1. FlatMap: Returns a single list of all elements yielded from results of transform function being invoked on each element of the original array (in above cases the transform function returned list of transactions by each individual user)
  2. Filter and SumBy: Here we combined filter and sum by operations to write a one-liner code to find the total amount deposited and withdrawn from the bank considering all customers.
  3. Fold: Accumulates value starting with the initial value (0.0 in our case) and applying operation (when statement above) from left to right to current accumulator value and each element. Here we used fold and when to find the net amount deposited in the bank considering all deposits and withdrawals.
  4. Partition: Splits the original array into a pair of lists, where the first list contains elements for which predicate (the separation function in this case) yielded true, while the 2nd where it yielded false. Of course, we can filter twice, but this is so much easier.

So many complex operations simplified by the Kotlin standard library.

Extensions:

One of my favourite features. Kotlin extensions let us add functionality to a class without modifying the original class. Just like in Swift and C#. This can be very handy if used properly. Check this out:

In the above code, we just added a new function called “toINR()” to Kotlin’s Double type. So we basically added a new function in Kotlin’s primitive type, how about that 😎. And it is a one-liner function, no curly braces, return type, return statement whatsoever. Noticed that conciseness did you?.

Since Kotlin supports higher order functions we can combine this with extension functions to solidify our code. One very common problem with android development involving SQLite is, developers often forget to end the transaction. Then we waste hours debugging it. Here is how we can avoid it:

We added an extension function called “performDBTransaction” in SQLiteDatabaseThis function takes a parameter that is a function with no input and no output, and this parameter function is whatever we want executed in between begin and end transactions. This function calls beginTransaction() then the passed operation and then calls endTransaction(). We can use this function wherever required without having to double check if we called endTransaction or not.

I always forget to call commit() or apply() when storing data in Shared Preferences. Similar approach:

extension function persist() (line 9 above) takes care of it. We are calling persist() as if it is a part of SharedPreferences.Editor.

Smart Casts:

Going back to our bank example. Let’s say the transaction can be of three types as explained in below figure:

NEFT transaction has fixed charges, IMPS has some bank-related charges. Now we deal with a transaction object, the super class “Transaction”. We need to identify the type of transaction so that the transaction can be processed accordingly. Here is how this can be handled in Kotlin:

In line 10 and 11 in above code gist, we didn’t cast the Transaction object into NEFT or IMPS, yet we are able to invoke the functions of these classes. This is a smart cast in Kotlin. Kotlin has automatically casted the transaction object into its respective type.

Epilogue:

As developers, we need to focus on stuff that matters, the core part, and boilerplate code isn’t one of them. Kotlin helps in reducing boilerplate code and makes development fun. Kotlin has many amazing features which ease development and testing. Do not let the fear of the unknown dictate your choice of the programming language; migrate your apps to kotlin now. The initial resistance is the only resistance.

I sincerely hope you enjoyed the first article of this Kotlin Kronicles series. We have just tapped the surface. Stay tuned for part 2. Let me know if you want me to cover anything specific.

Got any suggestions? shoot below in comments.

What is your favourite feature of Kotlin?

Keep Developing…

iOS Build Management using Custom Build Scheme

Introduction

One of the best practices in iOS development is to be able to manage multiple environments during the development of a project. Many a time we might have to jump between DEV, QA, STAGE, and Production environments. As the owner of a product, clients request to have both development version of the app and production version of the app i.e. App store released version of the app on the same device.

If you have ever faced or might face this situation, then you need a custom build scheme.

Objective

This blog explains the significance of custom build schemes & build configurations in XCode. We will see how we can leverage these to configure an iOS project to support multiple build environments without the need to duplicate targets and keep the same code base.

Prerequisites

  • XCode 8.0 onwards
  • Mac machine with macOS Sierra version

Advantages of Custom Builds

  • Write code that only runs on a particular environment. For example, on DEV you might want to have different values to constants in the app than on Production.
  • Switch between different environments easily to deliver a build that talks to the production server after testing your app in a development environment.

Difference Between Build Schemes & Build Configurations

Before we start actual changes on XCode, let’s understand the difference between build schemes & build configurations first.

A build scheme is a blueprint for an entire build process. It is a way of telling Xcode what build configurations you want to use to create the development, unit test, and production builds for a given target (framework or app bundle).

A build configuration is a specific group of builds settings that can be applied to any target.

Most app projects come with two build configurations and one build scheme. You get the debug and release build configurations along with a building scheme that runs the debug configuration for debugging purposes and the release configuration for archiving/submission.

For most projects, this is perfectly fine and requires no tweaking. However, if you want to offer both a DEV and a PRODUCTION version of the same app, it’s not quite enough. You must add a new build configuration to achieve this.

Adding a new build configuration

Whenever you wish to support multiple environments in the app, you need to start by adding a new build configuration. There are some important steps involved which sometimes seems confusing at first, so follow every step carefully.

  1. Open Xcode and select the project file.

vj1

2. Go to Editor → Add Configuration → Duplicate Debug Configuration.

vj2

Repeat Steps 1 and 2 for Release configuration.
NOTE: Remember that for every environment you must Duplicate Debug and Release configuration. Thus, if you want to support DEV, QA, STAGE, PRO then you should have the following configuration:

  • DEV-Debug, DEV-Release
  • QA-Debug, QA-Release
  • STAGE-Debug, STAGE-Release
  • PRO-Debug, PRO-Release

vj3

Creating a separate build scheme for every environment

We’re going to take our new build configurations and create a build scheme that runs them.

  1. Tap on the currently active scheme.
  2. In the dropdown, select New Scheme.

vj4

3. Provide a name to the new build scheme. I usually follow <Name of the app>-       <Environment>. For example, MultipleEnvApp-QA.

vj5

Once you’ve done this, notice that your new build scheme is selected.

vj6

We’re not done yet. We have a build scheme, but it isn’t using our new build configurations yet.

4. Click on your build scheme and select Edit Scheme.

vj7

5. Select the appropriate build configuration as per the environment. For example, our selected scheme is MultipleEnvApp-QA, hence choose respective QA build configurations.

vj8

That’s it. In the same way, you can create and configure schemes for STAGE and PRO environment. You can rename the default scheme as MultipleEnvApp-DEV

Writing code that runs on a particular environment of your app

Unfortunately, having separate build schemes isn’t quite enough. We also need a way to selectively run blocks of code on a particular environment. To do that, we are going to add a custom Swift flag that only applies to the particular build configurations we just created.

  1. Select the target and then Go to Build Settings, and scroll down to Other Swift Flags.
  2. You must add the flags for every configuration. For example, add the flag “-DQA” to both of the QA build configurations.

vj9

-D is the namespace for custom flags that can be passed into a build command.

You can ignore the “-D” for now.

3. Go to any of your source files. For example, AppDelegate and add these lines of code.

https://gist.github.com/vkhemnar/7b4c38bb8f8597f2ac4792208dab3f2c 

We have created a global variable SOME_SERVICE_KEY and used a unique value for each environment. In this way, you can actually use different service keys, constants for different environments.

Different bundle identifiers for different build configurations

Optionally, if you want to use different bundle ID for different configurations, do the following:

  1. Create two app IDs on your Apple Developer portal.
  2. Go to your project settings and set the appropriate bundle identifiers for different build configurations.

vj10

Conclusion

That’s all there is to it. Now you are setup to deliver a configurable app for different environments using the same shared codebase. Here is the GitHub project that contains all the configurations which we followed in this blog.

Happy Coding!

Build an iOS app that connects to IoT device using Bluetooth

You must be aware of term “IoT” Internet of Things, this is one of the hot technology worldwide nowadays, as many products, devices are available in the market.

I won’t say detailed knowledge of IoT, but at the end of this article, you will have a high-level idea of how IoT system works. To understand it, we will create an iOS demo app which will send/receive data from IoT compatible device with the help of Arduino.

In this article, we will cover following points:
– Introduction to IoT
– Arduino Overview
– iOS Demo App to understand end to end flow.

Introduction to IoT
Internet of things is a system of devices connected to the internet with the ability to collect and exchange data. The device or “Thing” in IoT could be any device embedded with electronics, software, and sensors like lights in household, smart air conditioner or person with heart monitor.
Lets see what are the opportunities in IoT, why it became one of the hot technology:
  • The connected world of devices, people and data helps to create numerous business opportunities for many sectors. For example, If I own car parts manufacturing business then I might want to know which parts are most popular. Using IoT, I can use a sensor in a showroom, to detect which areas are more popular or in which area customer spends more time. I will use this data to identify parts and increase production of these parts.
  • Real-time updates offer resources to improve decision making more accurate.
  • Costs of IoT components have significantly gone down, which effectively means that the cost of IoT-linked devices is getting more affordable day by day.

There are many other opportunities which accelerated the market for Internet of Things. It is predicted that by 2020, 25 billion devices will be available in the market.

The network in IoT will be decided on the factors such as range, data, security, and power. These factors will decide the choice of network whether it is the internet, Bluetooth, WiFi or any other. IoT is used for the devices that would not necessary to have an internet connection. It is used for a device that can communicate with the network which can be the internet, Bluetooth, NFC or anything else. For short-range communications technology is of course Bluetooth. It is expected to be key for wearable products. For example, Smartwatch, Fitness band. There are many sources available for IoT, so we will not dig into this.

Arduino Overview

We know how to send or receive data over the internet from an iOS app. But many of us don’t know how this data operate the IoT devices. There are open source hardware and software available in the market which is used to control the IoT devices. One of these is Arduino.

Arduino is an open-source hardware and software. Arduino boards are able to read inputs from the different sensors and turn it into an output like turning on an LED, activating a motor or publishing it over the internet.

These boards can take following inputs and outputs:
Inputs:
  • Temperature, Humidity, Pressure etc
  • Light, Infrared signals
  • Sounds
  • Motion captures
  • Heart rate, muscle movement
  • Electrical current
  • Touch, Fingerprints
Outputs:
  • LEDs
  • LCDs
  • Speakers
  • Motors
  • The internet
There are different types of Arduino boards available depending on features like an ethernet port, wireless or USB device support. Common specification of these hardware boards are:
  • ATmega 328 8bit chip
  • 5-20V power supply
  • 32 KB flash memory
  • 20 I/O pins

You can tell Arduino boards what to do by sending a set of instructions to the microcontroller on the board. For this, we have to use Arduino Software (IDE) and Arduino programming language.

Arduino IDE:

To write code and upload it to the board, Arduino IDE is used. It is available for Mac, Windows, and Linux platform. You can download it at https://www.arduino.cc/en/Main/Software.

Arduino programming language:
The coding language that Arduino uses is very much like C++, which is a common language in the world of computing.
Two important functions in Arduino language are:
  • setup( ) – Every program should have this function. This runs once at the start of the program like main () function. You can do initialisation stuff in this function.
  • loop( ) – Every program should have this function. This gets called repeatedly. You can use it to actively control the Arduino board.
Other Useful Function:
  • pinMode() – Set a pin as input or output
  • digitalWrite() – Set a digital pin high/low
  • digitalRead() – Read a digital pin’s state
  • analogRead() – Read an analog pin
  • analogWrite() – Write an analog value
  • delay() – Wait an amount of time
Example Code:
int ledPin = 3;
// setup initializes serial and the LED pin
void setup(){
     Serial.begin(9600);
     pinMode(ledPin, INPUT);
}

// loop checks the LED pin state each time and broadcast it whether it is high or
// low
void loop(){
    if (digitalRead(ledPin) == HIGH)
         Serial.write('H');
   else
        Serial.write('L');
        delay(1000);
}

 

You will find more details about language at https://www.arduino.cc/reference/en/.

Once you write the code, you can upload it on Arduino board by using Arduino IDE. You can download demo Arduino program to turn LED on-off. This program send/receives data over the Bluetooth and turns on-board LED on-off depending on data received. Also, this will broadcast state of the LED pin. You can use Arduino Leonardo board for this demo.

iOS Demo App 
I have created a sample iOS demo app which will send/receive data over the Bluetooth. For that, I have used Core-Bluetooth framework. You can download it here.
On launch of this app, it will try to connect to a nearby Bluetooth device which is Arduino board in our case. After successful connection, this app can send instructions to the board to turn LED on-off.
Steps To Run:
  • Upload LED demo program on Arduino board. You have to upload it by using Arduino IDE. You will find more details for uploading it in the referenced link above.
  • On successful upload, keep power up Arduino board.
  • Launch iOS demo app. It will connect automatically to the board on which program is uploaded.
  • Once it is connected, red line in the app turns green. Now you can send instructions to turn LED on-off on the board by using this app.
  • Once it is connected, red line in the app turns green. Now you can send instructions to turn LED on-off on the board by using this app.

You can modify this demo program for the internet instead of Bluetooth. For internet network, Arduino board which has a capability of broadcasting data over the internet is required.

Conclusion
This article is a good starting point for anyone who is interested in connecting an iOS app to IoT device using Bluetooth Low Energy. We saw how to hook up an Arduino board with an iOS app. We have a LED on Arduino board, but we can easily connect any other sensor to it. You can find the sample projects on github. I hope you’ll find these projects useful. Good luck and have fun!

Build your own custom Android ROM using Android Open Source Project(AOSP)

Introduction

One of the best things about Android is custom ROMs. A custom Android ROM refers to a phone’s firmware, based on Google’s Android platform. The term ROM, which stands for Read Only Memory, really has very little to do with what a custom Android ROM actually is, can be confusing. Since Android is an open source mobile operating system that means anyone can download the source code, make modification to it, recompile it and release it for a wide variety of devices. Anyone can install ROMs to their device and achieve a modified appearance and behavior. Continue reading Build your own custom Android ROM using Android Open Source Project(AOSP)

Object detection with Turi Create and augmentation using ARKit

Introduction

Over the past few years, the use of Machine Learning to solve complex problems has been increasing. Machine learning (ML) is a field of computer science that gives computer systems the ability to “learn” (i.e. progressively improve performance on a specific task) with data, without being explicitly programmed.

Last year was a good year for the freedom of information, as titans of the industry Google, Microsoft, Facebook, Amazon, Apple and even Baidu open-sourced their ML frameworks. In this blog, let’s explore a framework provided by Apple named Turi Create. Continue reading Object detection with Turi Create and augmentation using ARKit

OCR implementation in Android

What is OCR?

Optical character recognition, Optical character reader or OCR is the process of reading printed or handwritten text and converting them into machine-encoded text. OCR is mainly used in the field of artificial intelligence, pattern recognition, and computer vision.

So how does it work? In simple words, for a computer, an image is nothing but a collection of pixels. In OCR processing, the image is scanned for light and dark areas to identify each character.  Continue reading OCR implementation in Android

Proxy Routing in Angular 4 Applications

This blog intends to deal and simplify routing in Angular 4 applications in both development and production environment. While working on routing in Angular 4 applications, we often face some of the following challenges:

  • Finding a solution to the problem of cross-origin issues in Angular development environment
  • Separating routing configurations and APIs servers URLs from the code, making the application more robust and maintainable
  • Finding a generic solution where frequent changing of API URLs (due to deployment on different servers, let’s say for the purpose of load balancing) do not force you to modify and change the code
  • Servers where the APIs deployed do not appear in your code at all

Continue reading Proxy Routing in Angular 4 Applications