What is Reactive Programming?


Nowadays everybody is talking about Reactive Programming and you’re curious in learning this new thing called Reactive Programming. Maybe you’ve seen it used a few places but you’re still a little confused and would like some clarifications.

In this article, we are going to learn the basic concepts of the Reactive Programming. Starting from the next article we are going to do some real programming and learn how to use RxJava in the Android application development.

So, first let’s understand what are the problem we are facing? Why do we require Reactive Programming? Because if there is no problem, then we don’t need a solution right??

Why do we need Asynchronous work?

The simple answer is we want to improve the user experience. We want to make our application more responsive. We want to deliver a smooth user experience to our users without freezing the main thread, slowing them down and we don’t want to provide the jenky performance to our users.

To keep the main thread free we need to do a lot of heavy and time-consuming work we want to do in the background. We also want to do heavy work and complex calculations on our servers as mobile devices are not very powerful to do the heavy lifting. So we need asynchronous work for network operations.

The evaluation matrix:


Let’s see what do we need from the library that handles all the asynchronous work. You can imagine below 4 points as the evaluation matrix for the asynchronous library.

  • Explicit execution: If we start the execution of a bunch of work on a new thread, we should be able to control it. If you are going to perform some background task, you gather the information and prepare them. As soon as you are ready, you can kick-off the background task.
  • Easy thread managementIn asynchronous work, thread management is the key. We often need to update the UI on the main thread from the background thread in the middle of the task or at the end of the task. For that, we need to pass our work from one thread (background thread) to another thread (here main thread). So you should be able to switch the thread easily and pass the work to another thread when needed.
  • Easily composable: Ideally, It would be great if we can create an asynchronous work and as we start spinning background thread, it just do it’s work without depending any other thread (especially on UI thread) and stays independent from the other thread until it finishes its job. But in the real world, we need to update the UI, make database changes and many more things that make threading interdependent. So the asynchronous library should be easily composable and provide less room for the error.
  • Minimum the side effects: While working with multiple threads, the other thread should experience minimum side effects from the other thread. That makes your code easily readable and understandable to a new person and it also makes error easily traceable.

What is Reactive Programming?

According to wikipedia:

Reactive programming is a programming paradigm oriented around data flows and the propagation of change. This means that it should be possible to express static or dynamic data flows with ease in the programming languages used, and that the underlying execution model will automatically propagate changes through the data flow.

In simple words, In Rx programming data flows emitted by one component and the underlying structure provided by the Rx libraries will propagate those changes to another component those are registered to receive those data changes. Long story short: Rx is made up of three key points.


We are going to discuss these points in detail one by one.

  • Observable: Observable are nothing but the data streams. Observable packs the data that can be passed around from one thread to another thread. They basically emit the data periodically or only once in their life cycle based on their configurations. There are various operators that can help observer to emit some specific data based on certain events, but we will look into them in upcoming parts. For now, you can think observers as suppliers. They process and supply the data to other components.
  • Observers: Observers consumes the data stream emitted by the observable. Observers subscribe to the observable using subscribeOn()method to receive the data emitted by the observable. Whenever the observable emits the data all the registered observer receives the data in onNext() callback. Here they can perform various operations like parsing the JSON response or updating the UI. If there is an error thrown from observable, the observer will receive it in onError().
  • Schedulers: Remember that Rx is for asynchronous programming and we need a thread management. There is where schedules come into the picture. Schedulers are the component in Rx that tells observable and observers, on which thread they should run. You can use observeOn()method to tell observers, on which thread you should observe. Also, you can use scheduleOn() to tell the observable, on which thread you should run. There are main default threads are provided in RxJava like Schedulers.newThread() will create new background that. Schedulers.io() will execute the code on IO thread.

3 simple steps to use Rx in your application


Let’s look into the basic example. This will explain 3 simple steps to use Reactive programming in your application.

Step-1 Create observable that emits the data:

Here database is an observable which emits the data. In our case, it emits the strings. just() is an operator. Which basically emits the data provided in the argument one by one. (We are going to look into the operators in detail in our upcoming articles. So, don’t worry about them.)

Step -2 Create observer that consumes data:

In above code snippet observer is an observer that consumes the data emitted by the database observable. It processes the data received and also handles error inside it.

Step-3 Manage concurrency :

At the last step, we define our schedulers that manage the concurrency. subscribeOn(Schedulers.newThread()) tells database observable to run on background thread. observeOn(AndroidSchedulers.mainThread()) tells observer to run on the main thread. This is basic code for reactive programming.

So by now you should be able to understand, why we need reactive programming, why we need them and how we can implement them. In the upcoming articles, we are going to learn how to use RxJava and it’s operators in detail.

What next? (Part 2)

Now, visit the next part to start some programming example in RxJava and how to use RxJava in your Android/Java project.

If you liked the article, click the 💚 below so more people can see it!

Twitter Follow.png

Why you should learn Go?

Go will be the server language of the future.” — Tobias Lütke, Shopify

In past couple of years, there is a rise of new programming language: Go or GoLang. Nothing makes a developer crazy than a new programming language, right? So, I started learning Go before 4 to 5 months and here I am going to tell you about why you should also learn this new language.

I am not going to teach you, how you can write “Hello World!!” in this article. There are lots of other articles online for that. I am going the explain current stage of computer hardware-software and why we need new language like Go? Because if there is no problems, then we don’t need solution, right?

Hardware limitations:

Moore’s law is failing.

First Pentium 4 processor with 3.0GHz clock speed was introduced back in 2004 by Intel. Today, my Mackbook Pro 2016 has the clock speed of 2.9GHz. So, nearly in one decade, there is no too much gain in the raw processing power. You can see the comparison of increasing the processing power with the time in below chart.


From the above chart yo can see that the single-thread performance and the frequency of the processor remained steady for almost a decade. If you are thinking that adding more transistor is the solution, than you are wrong. This is because at smaller scale some quantum properties starts to emerge (like tunneling and because it actually costs more to put more transistors (why?) and the number of transistors you can add per dollar starts to fall.

So, for the solution of above problem,

  • Manufacturers started adding more and more cores to the processors. Now a days we have quad-core and octa-core CPUs available.
  • We also introduced hyper threading.
  • Added more cache to the processors to increase the performance.

But above solutions has it’s limitations too. We cannot add more and more cache to the processor to increase performance as cache have physical limits: the bigger the cache, the slower it gets. Adding more core to the processor has its cost too. Also, that cannot scale to indefinitely. These multi-core processors can run multiple threads simultaneously and that brings concurrency to the picture. We’ll discuss it later.

So, if we cannot rely on the hardware improvements, the only way to go is more efficient software to increase the performance. But sadly, modern programming language are not much efficient.

“Modern processors are a like nitro fueled funny cars, they excel at the quarter mile. Unfortunately, modern programming languages are like Monte Carlo, they are full of twists and turns.” — David Ungar

Go has goroutines !!

As we discussed above, hardware manufacturers are adding more and more cores to the processors to increase the performance. All the data centers running on those processors and we should expect an increase in the number of cores in upcoming years. More to that, today’s applications using multiple micro-services for maintaining database connections, message queues and maintain caches. So, the software we develop and the programming languages should support concurrency easily and they should be scalable with increased number of cores.

But, most of the modern programming languages(like Java, Python etc.) are from the ’90s single threaded environment. That doesn’t mean they do not support multi-threading. Most of those programming languages supports multi-threading. But the real problem comes with concurrent execution and threading-locking, race conditions and deadlocks. Those things makes it hard to create a multi-threading application on those languages.

For an example, Creating new threads in Java is not memory efficient. As every thread consumes approx 1MB of the memory heap size and eventually if you start spinning thousands of threads, it will put tremendous pressure on the heap and will cause shut down due to out of memory. Also, if you want to communicate between two or more threads, it’s very difficult.

On the other hand, Go was released in 2009 when multi-core processors were already available. That’s why GoLang is built with keeping concurrency in mind. Go has goroutines instead of threads. They consume almost 2KB memory from the heap and you can spin millions of goroutines at any time.


Other benefits are :

  • Goroutines have growable segmented stacks. That means they will use more memory only when needed.
  • Goroutines have a faster startup time than threads.
  • Goroutines come with built-in primitives to communicate safely between themselves (channels).
  • Goroutines allow you to avoid having to resort to mutex locking when sharing data structures.
  • Also, goroutines and OS thread are not 1:1 mapping. A single goroutine can run on multiple threads. Goroutines are multiplexed onto a small number of OS threads.

You can see Rob Pike’s excellent talk concurrency is not parallelism to get more deep understanding on this.

All the above points, make Go very powerful to handle concurrency like Java, C and C++ while keeping concurrency code straight and beautiful like Earlang.


Go runs directly on underlying hardware.

One most considerable benefit of using C, C++ is their performance over other modern higher level languages like Java/Python. Because C/C++ are compiled and not interpreted.

Processors understand binaries. Generally, when you build an application using Java or other JVM-based languages when you compile your project, it compiles the human readable code to byte-code which can be understood by JVM or other virtual machines that run on top of underlying OS. While execution, those VM interprets those bytecodes and convert them to binaries that can be understood by processors.

Execution on VM based languages

While on the other side, C, C++ does not execute on VMs and that removes one step from the execution cycle and increases the performance. It directly compiles the human readable code to binaries.

Execution on non-VM based languages

But, freeing and allocating variable in those languages is a huge pain. While most of the programming languages handle object allocation and removing using Garbage Collector or Reference Counting algorithms.

Go brings best of both the worlds. Unlike lower level languages like C/C++, Go is compiled language. That means performance is almost nearer to lower level languages. It also uses garbage collection to allocation and removal of the object. So, more malloc() and free() statements!!! Cool!!!

Code written in Go is easy to maintain.

Let me tell you one thing. Go does not have crazy programming syntax unlike other languages. It has very neat and clean syntax.

The designers of the Go at google had this thing in mind when creating the language. As google has the very large code base and thousands of developers were working on that same codebase, code should be simple to understand to other developers and one segment of code should have minimum side effects on another segment of the code. That will make code easily maintainable and easy to modify.

Go intentionally leaves out many features of many features of modern OOP languages.

  • No classes. Every thing is divided into packages only. Go has only structs instead of classes.
  • Does not support inheritance. That will make code easy to modify. In other languages like Java/Python, if the class ABC inherits class XYZ and you make some changes in class XYZ, then that may produce some side effects in other classes that inherit XYZ. By removing inheritance, Go makes it easy to understand the code also (as there is no super class to look at while looking at a piece of code).
  • No have constructors.
  • No annotations.
  • No generics.
  • No exceptions.

Above changes make Go very different from other languages and it makes programming in Go different than other. You may not like some of the points from above. But, it is not like you can not code without above features. All you have to do is write 2–3 more lines. But on the positive side, it will make your code cleaner and add more clarity to your code.

Code fun.PNG

Above graph displays that Go is almost as efficient as C/C++, while keeping the code syntax simple as Ruby, Python and other languages. That is a win-win situation for both humans and processors!!!

Unlike other new languages like Swift, it’s syntax of Go is very stable. It remained same since the initial public release 1.0, back in year 2012. That makes it backward compatible.

Go is backed by Google.

  • I know this is not any direct technical advantage. But, Go is designed and supported by Google. Google has one of the largest cloud infrastructures in the world and it is scaled massively. Go is designed by Google to solve their problems of supporting scalability and effectiveness. Those are the same issues you will face while creating your own servers.
  • More to that Go is also used by some big companies like Adobe, BBC, IBM, Intel and even Medium.(Source: https://github.com/golang/go/wiki/GoUsers)


  • Even though Go is very different than other object-oriented languages, but it is still the same beast. Go provides you high performance like C/C++, super efficient concurrency handling like Java and fun to code like Python/Perl.
  • If you don’t have any plans to learn Go, I will still say hardware limit puts pressure to us, software developers to write super efficient code. The developer needs to understand the hardware and make the programs optimize accordingly. The optimized software can run on cheaper and slower hardware (like IOT devices) and overall batter impact on end user experience.

~If you liked the article, click the 💚 below so more people can see it! Also, you can follow me on by clicking follow button below, so you get updates regarding future articles on Go!!~

follow me on twitter.jpg

Digesting Singleton Design Pattern in Java

Design Patterns are very popular among software developers. A design pattern is a well-described solution to a common software problem. The Singleton is one of the Creational Design Patterns in Java.

What is the purpose of Singleton?

The purpose of the singleton class is to control object creation, limiting the number of objects to only one. The singleton allows only one entry point to create the new instance of the class.

Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons are often useful where we have to control the resources, such as database connections or sockets.

It seems to be a very simple design pattern but when it comes to implementation, it comes with a lot of implementation concerns. The implementation of Singleton pattern has always been a controversial topic among developers. Here, we are going to discuss how to create a Singleton class that fulfills its purpose :

Restrict the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.

Let’s create Singleton class in java and test it in different conditions.

Create Singleton class in Java:

To implement the singleton class, the simplest way is to make the constructor of the class as private.

  1. Eager initialization:

In eager initialization, the instance of Singleton Class is created at the time of class loading, this is the easiest method to create a singleton class.

By making the constructor as private we are not allowing other class to create a new instance of the class we want to create the singleton. Instead, we are creating one public static method (commonly name as for getInstance()) to provide the single entry point to create the new instance of the class.

This approach has one drawback. Here instance is created even though client application might not be using it. This might be a considerable issue if your singleton class in creating a database connection or creating a socket. This may cause the memory leak problem. The solution is to create the new instance of the class, when needed. This can be achieved by Lazy Initialization method.

2. Lazy initialization:

Opposite to Eager initialization, here we are going to initialize new instance of the class in getInstance() method it self. This method will check if there is any instance of that class is already created? If yes, then our method (getInstance()) will return that old instance and if not then it creates a new instance of the singleton class in JVM and returns that instance. This approach is called as Lazy initialization.

We all know that in Java if the two objects are same then, their hash key have to be equal. Let’s test that. If the above singleton is correctly implemented than below code should return the same hash key.

Below is the output log with the hash code of both the instances.


We can see that both the instances are having the same hash code. So, that means above code will make the perfect singleton. Right???? No.

What about Java Reflection API?

In above singleton class, by using reflection we can create more than one instance. Those of you don’t know what is the Java Reflection API is, Java Reflection is a process of examining or modifying the run-time behavior of a class at run time.

We can make the new instance of the singleton class by changing the constructor visibility as public in run-time and create new instance using that constructor. Run the below code and see it our singleton survives?

Here is the output of hash codes of both instances.


Both the instances have a different hash code. That clearly indicates that our singleton class failed this test.


To prevent singleton failure while due to reflection we have to throw a run-time exception in constructor, if the constructor is already initialized and some class to initialize it again. Let’s update our SingletonClass.java.

Is our singleton class thread safe?

If two threads try to initialize our singleton class at almost the same time, what happens? Let’s test below code in which two threads are created almost simultaneously and they are calling getInstance().

If you run this code many times, you will see sometimes both the threads creates different instances.


That means our singleton class is not Thread safe. Both the threads calls out getInstance() method at the same time, the sSoleInstance == null condition will return for both the thread. So, two different instances of the same class will be created. That will break the singleton principle.


1. Make getInstance() synchronized:

Let’s make our getInstance() method synchronized.

As we made our getInstance() class synchronized the second thread will have to wait until the getInstance() method is completed for the first thread. This way we can achieve thread safety. But, there are some cons of using this approach:

  • Slow performance because of locking overhead.
  • Unnecessary synchronization that is not required once the instance variable is initialized.

2. Double check locking method:

We can overcome this issue if we use Double check locking method to create the singleton. In this, we make the singleton class in the synchronized block if the instance is null. So, the synchronized block will be executed only when the sSoleInstance is null and prevent unnecessary synchronization once the instance variable is initialized.

3. Use volatile keyword:

On the surface, this method looks perfect, as you only need to pay price for synchronized block one time, but it still was broken, until you make sSoleInstance variable volatile.

Without volatile modifier, it’s possible for another thread in Java to see half initialized state of _instance variable, but with volatile variable guaranteeing happens-before relationship, all the write will happen on volatile sSoleInstance before any read of sSoleInstance variable.

Now, our singleton class is thread safe. Making singleton thread safe is especially required in multi-threaded application environment like in Android Applications.

Make Singleton safe from Serialization:

Sometimes in distributed systems, we need to implement Serializableinterface in Singleton class. By doing that we can store its state in the file system and retrieve it at later point of time. Let’s test our singleton class whether it maintains single instance after serializable and deserializable operations?


We can see that the hash code of both the instances are different. That is clearly violates singleton principle. The problem with above serialized singleton class is that whenever we deserialize it, it will create a new instance of the class.

To prevent creation of another instance we have to provide the implementation of readResolve() method. readResolve() replaces the object read from the stream. This ensures that nobody can create another instance by serializing and deserializing the singleton.


At end of the article, we can make our class a singleton class that is thread and reflection safe. This singleton is still not the perfect singleton. We can violate the singleton principle by creating more than one instance of the singleton class by using cloning or using multiple class loaders. But for the most of the applications, above implementation of singleton will work perfectly.

Create Chat Heads Like Facebook Messenger

We all love the chat heads (or chat bubbles) from the popular Facebook Messenger. This provides very handy and easy access to the chat conversation screen no matter on which screen you are. Chat heads are very convenient for multitasking as a user can work and chat at the same time. That means if you are using the calculator app on your phone and if any new message arrives, you can open the conversation and replay the message without switching app. Pretty cool!!!

In this tutorial, we are going to learn how to create simple chat head and allow user to drag them across the screen. So that user can adjust the position of the floating widget in the screen.

So, let’s get started.

Understanding the basics:

  • Chat heads are nothing but a floating view that is drawn over other application. Android system allows applications to draw over other application if the application has android.permission.SYSTEM_ALERT_WINDOW permission. We are going to use the background service to add the floating widget into the view hierarchy of the current screen. So, this floating view is always on top of application windows.
  • To, drag the chat head across the screen we are going to override OnTouchListener() to listen to drag events and change the position of the chat has in the screen.


Step-1: Add android.permission.SYSTEM_ALERT_WINDOW permission to the AndroidManifest.xml file. This permission allows an app to create windows , shown on top of all other apps.

Step-2: Create the layout of the chat head you want to display.

Step-3: Add music control widget to the window and handle dragging:

  • Now create a service called ChatHeadService. Whenever you want to display a chat head, start the service using startService() command. In onCreate() of the service we will add the layout of the chat head at the top-left corner of the window.
  • To drag the chat head along with the user’s touch, we have to override OnTouchListener(). Whenever the user touches the chat head, we will record the initial x and y coordinates, and when the user moves the finger, the application will calculate the new X and Y coordinate and move the chat head.
  • Also, implement click listener to close the chat head by stopping the service when the user clicks on the close icon at the top-right of the chat head.
  • So finally your ChatService.java will look like below:

Step-4: Handle Overdraw permission:

  • Now one final step is remaining. To add display chat head, you need to start the ChatService.java.
  • Before that, we need to check if the application has android.permission.SYSTEM_ALERT_WINDOW permission or not? For android version <= API22, this permission is granted by default. But for the android versions running API>22 ,we need to check for the permission run-time. If the permission is not available, we will open permission management screen to allow the user to grant permission using Settings.ACTION_MANAGE_OVERLAY_PERMISSION intent action. This will open below screen facilitate user to grant android.permission.SYSTEM_ALERT_WINDOW permission.


  • Here is the code snippet for the MainActivity that will display the chat head when the button is clicked by checking the SYSTEM_ALERT_WINDOWpermission.

That’s it. Now build and run the project to see the results. Here is the sample of how our final application should look like.


Don’t worry if you have any problems while building the project. Full source code is also available on GitHub. Go ahead, download and run it. Still, if you have any queries let me know in comments below or hit me on Twitter . Also, follow me on Github to stay in touch.


Keep your device screen on smartly!!!

Ideally, when you user is looking at the screen, your application should prevent the device screen from turning off.

This is the huge deal for the blogging, messaging applications. These applications display textual content to their user. Reading those textual content takes more time to the user. While reading that content (let say an article) if the user does not interact with the display and the screen turns off because of the screen timeout that is frustrating to the user. It will destroy the concentration of the user and breaks the link.

If you are using Samsung devices you might know there is one feature called “Smart Stay”. When this feature is enabled, the device will prevent your screen from turning off regardless of your screen timeout settings. But, this technology is only available on some Samsung devices. What if we want to use that technology in our application to solve above problem? Today, I am going to present the solution of this problem.

Here is the solution:

Prevent-Screen-Off” library handles screen on/off timing smartly. It prevents device display from turning off when the user is looking at the screen and he/she might be reading some textual content provided by your application. As soon as the user stop looking at the screen it will allow phone screen to turn off.

How this works?

  • This library uses the front camera to sense when you are looking at your device
  • This uses Google Play Services Mobile Vision API to track users eye using the device front camera. This uses the same algorithm to detect user’s eyes used in “UserAwareVideoView”. (I wrote a whole article regarding how UserAwareVideoView works. You can find it from here.)
  • It keeps the screen from turning off regardless of the screen timeout setting if the user is looking at the screen by detecting user’s eyes.

Integrating the library in your application:

Let’s dive into some technical stuff and see how you can integrate this library in your application and use it.

Add Gradle dependency:

  • To start with the integration, first provide the Gradle dependency of the library by entering below lines in your module level build.gradle.

This library adds android.permission.CAMERA and android.permission.WAKE_LOCK permission in your applications AndroidManifest.xml file.

Initialize in your activity:

  • First, you need to inherit AnalyserActivity in the activity which you want to control screen on/off automatically. The library will synchronize with your activity life-cycle and start and stop eye tracking based on your activity state.
  • Library will start tracking user eyes as soon as activity comes into the foreground. If the user is looking at the screen this will prevent the screen from turning off.
  • When library detects that the user is not looking at the screen, this will turn off the screen after some time.
  • It will stop eye tracking when your activity goes into the background to preserve the battery.
  • Implement ScreenListener to receive the callbacks from the library.
  • Handle the callbacks and errors received from ScreenListener.
  • That’s it. You successfully integrated the library. By the way, if you want to try our sample application before integration, you can find it from this link.

This library won’t work if,

  • When camera fails to initialize or your front camera is being used by another application. In that case, you will receive Errors.UNDEFINED error code in onErrorOccured event.
  • When the light source is behind the user or there is low light in the surrounding environment, so that eye tracking is not possible. In that case, you will receive Errors.LOW_LIGHT error code in onErrorOccured event. At this point, you can show a message to your user to go to the place where enough light available.
  • Google Play Service not available. In that case, you will receive Errors.PLAY_SERVICE_NOT_AVAILABLE error code in onErrorOccured event. In this case, the library will automatically display the dialog to install or update Google Play Services application from the play store, if the device supports Google Play Service.
  • If the device does not have the front camera. In that case, you will receive Errors.FRONT_CAMERA_NOT_AVAILABLE error code in onErrorOccured event. In this case, we are helpless. 😦

Where can you use this feature?

  • Tracking user’s eye using device camera consumes more battery. So, it is advisable that you don’t integrate automatic screen control in every screen of your application.
  • You can integrate this features in your application activity, which has more textual content to read. An e.g. activity that shows chat conversation in messaging app or activity that displays full article in your blogging application. (This list can be extended for may other use cases. Let me know if you have more ideas in comments.)

For the full sample application and the source code, visit GitHub.

User Aware Video View

These days all new smartphones are packed with lots of sensors and most of the smartphone contains the front (selfie) camera. So, why don’t we make use of them to improve the user experience? While watching the video on your device is the most important feature for many social sharing, messaging and media applications.

UserAwareVideoView is a customized video viewer that smartly play and pause the video based on your user is looking at the video or not. If the user is not looking at the screen then this will automatically pause the video, so your user does not miss any part of the video.

UserAwareVideoView inherits the android framework’s default VideoViewclass. So, it has all the features that video viewer has. More than that it makes it easy to convert your all the default video views to UserAwareVideoView in your existing application.

How does it work?

At its core UserAwareVideoView uses Google Play Service Mobile Vision API for the image processing. It uses front camera of the device to track user’s eyes.

When VideoView.start() is called, it starts the eye tracking algorithm and starts tracking the user’s eyes. It also starts monitoring surrounding light intensity and if the light intensity is not enough for processing camera output, it stops tracking the user’s eyes.

If the user is not looking at the device screen, UserAwareVideoView will pause the video and it will resume the video as soon as the user starts looking at the screen. Pretty amazing huh!!!

Whenever VideoView.stopPlayback() or VideoView.pause() is called, this will UserAwareVideoView will release the camera and stop eye tracking to consume the battery.

How to integrate?

To start with the integration, first provide the Gradle dependency of the library by entering below lines in your module level build.gradle.


This library automatically adds android.permission.CAMERA permission in your applications AndroidManifest.xml file.

Add the UserAwareVideoView in you xml layout of your activity or fragment. You can use UserAwareVideoView just like you use the default VideoView in your layout.

Initialize the UserAwareVideoView in your activity/fragment by following three steps:

  • Step-1: Check for the Camera permission in run-time.
  • Step-2: Register UserAwarenessListener to get the callbacks from the UserAwareVideoView whenever error occurs in eyes detection or eye detection starts stops.
  • Step-3: Handle errors that may occur while eyes detection. There are main 4 errors. You can detect those errors by error code. Below is the snippet showing how you can handle different errors.

That’s it. You are ready with UserAwareVideoView.


By using the UserAwareVideoView, you can make your application smart that responds to the user’s activity and uses the phone’s sensors to control the video playback so that your user don’t miss any part of the video.

For the full sample application and the source code, visit GitHub.