Detect user’s activity using Activity Recognition Transition API

Understanding what people are doing can help your app better adapt your user’s needs.Transition API can tell if your users are walking, running, cycling, or in a vehicle and you can use it to improve your app experience.Transition API combine various signals like location and sensor data to determine when the user has started or ended an activity like walking or driving.

Since November 2017, the Transition API use to power the Driving Do-Not-Disturb feature launched on the Pixel 2.Now, Activity Recognition Transition API available to all Android developers.Transition API take care of stillness means the user parked their car and ended a drive or simply stopped at a traffic light and will continue on.

Use Case

If a user starts running, you’ll get a callback indicating the most probable activity is running.If the confidence is 75 or higher, you know you can act on it and show notification asking if they want to start tracking their run.

When an app is in use and the user starts driving, you can offer popup switch to car mode dialogue.

You can also use it for historical cases such as showing your users when they parked their car or how long they spent commuting to work each day.

Mileage tracking app could start tracking miles when a user starts driving, or a messaging app could mute all conversations until the user stops driving.

1.Add Dependencies

To declare a dependency to the API, add a reference to the Google maven repository and add an implementation entry to to the dependencies section of your app build.gradle file.

2.Add Permission

Specify the permission in the app manifest.

3.Register for activity transition updates

To start receiving notifications about activity transitions, you must implement, An ActivityTransitionRequest object that specifies the type of activity and transition.PendingIntent callback where your app receives notifications.


You must create a list of ActivityTransition objects, which represent the transition that you want to receive notifications about. An ActivityTransition object includes the 1.An activity type  IN_VEHICLE,ON_BICYCLE,RUNNING,STILL,WALKING

2.A transition type of ACTIVITY_TRANSITION_ENTER or ACTIVITY_TRANSITION_EXIT. For more information, refer to theActivityTransition class.

The following code shows how to create a list of ActivityTransition objects:


Reducing memory consumption is important to keep the phone running smoothly.When using the API, a common use case is that an application wants to monitor activity in the background and perform an action when a specific activity is detected.Typically, when developing for Android, you don’t use a persistent running service to handle this.That consumed a lot of resources.This API removes that burden by delivering the data via an intent.The application specifies a pending intent callback typically an intent service, which will be called with an intent when activities are detected.So there’s no need to keep the service always running in the background.

After successfully registering for activity transition updates, your app receives notifications in the registered PendingIntent.

4.Receive activity transition events

When the requested activity transition occurs, you app receives an Intent callback.The events are ordered in chronological order, for example, if an app requests for the IN_VEHICLE activity type on the ACTIVITY_TRANSITION_ENTER and ACTIVITY_TRANSITION_EXIT transitions, then it receives an ActivityTransitionEvent object when the user starts driving, and another one when the user transitions to any other activity.

Your application will receive callbacks with extras containing an activity recognition result.This contains a list of activities that the user may be doing at the particular time.

5.Deregister for activity transition updates

Deregister for activity transition updates by calling the removeActivityTransitionUpdates() method of the ActivityRecognitionClient and passing your PendingIntent object as a parameter.


Download this project from GitHub



What’s new in MQTT 5

MQTT 5 is pretty new, a lot of things changed.We will walk through the most important changes of MQTT 5 in this blog.

I guess most of you are already familiar with MQTT but for those who are not quite sure what MQTT is, what it’s about and what are the main principles let’s start with a quick refresher this is also important to understand some of the changes in MQTT 5.

MQTT Overview

MQTT is an iot messaging protocol. It gained massive attraction in the last few years.It’s mostly used for device to cloud communication and cloud to device communication sometimes device to device communication directly.It has a lot of features which are good for mobile network use cases.If you have devices out in the field like cars or like gateways or physical hardware which needs to connect via mobile networks to the backend services.


MQTT has 3 different quality of services levels which you can define on the application level.You can send messages with fire and can also make sure that message arrives at least once or exactly once on the backend.

Retained Messages

MQTT has nice features which are unique to the protocol is retained messages which essentially allows you to save messages on your MQTT message broker.

Persistent offline sessions

MQTT has a feature which allows the client to come back and the broker remembers the client and also sends out messages the client did not get at the time.In general, from an application perspective, you can program with MQTT like you never lost the connection.

Binary Protocol

MQTT is a binary protocol with a minimal overhead so it’s really tiny it saves a lot of bandwidth.

MQTT Use Case

MQTT is a very good protocol for constraint devices.If you don’t have too much computing power or a memory then MQTT is a very good protocol choice.This is typically on physical hardware at a few megabytes of memory.

Push Communication

Typical use cases for MQTT is push communication.We have reliable communication of unreliable networks this is mainly mobile networks.

Low Bandwidth and High Latency

It also stays extremely on the backend. Some MQTT brokers allow scaling to more than 10 billions of concurrently connected devices.Typically especially if you’re in a mobile network you offer a very low bandwidth in the high latency and MQTT make sure that you really get the best here so it doesn’t waste any bandwidth and the best at low latency.


publisher subscriber protocol

MQTT uses the publish/subscribe mechanism.we have an MQTT broker which is in middle.MQTT broker is responsible for distributing data across clients.

We have some producing clients like here temperature sensor.It publishes data to MQTT broker and the broker distributes the data to devices which could be in this case a laptop or a mobile device it could be a car it is really anything which can connect to the internet.

This device works by a subscription mechanism.The laptop or the mobile devices subscribes to the MQTT broker it says hey “I’m interested in a particular data set” and the broker make sure that only the data which the client are interested in forward to their clients. You have a decoupling here and what is very important to know about MQTT you have a standing TCP connection here so all of the devices which talk to the MQTT broker are connected all the time so this is different to other protocols like HTTP which typically close the connection after doing stuff.

MQTT 5 Overview

MQTT 5 is the successor of MQTT 3.1.1.It is not backward compatible with the old specification.Officially released in January 2018. It also had a lot of clarifications from the MQTT 3.1.1 specification so to make sure that implementers of the specification get everything right.

MQTT 5 Goals

The goals of MQTT 5 is enhancements scalability and improved error reporting.Error reporting wasn’t most wished features by users because MQTT 3.1.1 has some blind spots when you come to error handling.MQTT 5 did a lot of work here and also formalized common patterns like request response.

One of the most wished features is the extensibility of the protocol because they(MQTT 3)weren’t headers like you know from HTTP. MQTT 3.1.1 wasn’t that flexible this changed.Performance improvement for small clients they’re also a big part.

MQTT is very easy to program on the client side but it’s important to notice that implementing MQTT broker is not as easy as it sounds.

MQTT 5 has some enhancement for the scalability.MQTT free brokers scale up to 10 millions of devices which is already a lot but also we expect that MQTT 5 allows us to scale even beyond the magic 10 million by concurrent connections.

Foundational Changes

Before digging into the specific features let us talk about the foundational changes of the MQTT protocol

Negative acknowledgments

First foundational change is Negative acknowledgments.I already mentioned that the error reporting in MQTT 3.1.1 wasn’t optimum.There was no way for the broker to tell “hey you’re doing something wrong”.So what was defined here was their negative acknowledgments.A broker can actually notify the client that something went wrong and also what went wrong. This is for many use cases this is very important especially for production use cases where it’s it’s hard to debug what happened.The client can react when something weird happens but also the client can send acknowledgments to the broker if something bad happens.

Return Code

Another foundational change is returned codes for unsupported features when a client connects to an MQTT broker if the broker does not allow all MQTT features or doesn’t implement all MQTT features which is pretty common atypical like cloud platforms like AWS.It’s possible to tell the client, ok this feature is not available or this is not available for you.If you haven’t a permission control and you do not allow clients let’s say to subscribe or publish or something like this.

MQTT 5  can restrict the retain message feature so we can turn it off if we want for a specific client.

we can define a maximum quality of service level for the client.

We can restrict the use of wildcard subscriptions.

we can also restrict subscription identifiers share subscriptions.

A client can be notified what is maximum message size to broker support.What deserves a keepalive value is which is also very important because it also changes with MQTT 5.

The broker can tell the client how often it should send ping messages or heartbeat messages in order to recognize it for clients is offline.

Another notable change is MQTT 5 not allowed to send retry for the quality of service 1&2 messages. This is something which may come surprisingly for some people because We noticed that many projects rely on retries which are not allowed with MQTT5. So this is a common pitfall when upgrading to MQTT 5.

Passwords are now allowed to send without having usernames which may be interested in sending tokens.Clients are now allowed to send disconnect packages traditionally. The broker has no way to disconnect the client gracefully with MQTT 3. The client can connect and when it decides okay I want to disconnect now in a graceful then the client sent a disconnect packet to a broker but now it’s also allowed for the broker to say that this connect packet it back to the client and tell the reason why it was disconnected this is always something new and is used heavily for the negative acknowledgments.

New Features in MQTT 5

Let’s talk about some of the features in MQTT 5.We cannot dig into all features because there are more than 25 features available which take a lot of time but what I want to highlight some of the features more detail.

Session & Message Expiry

So one of them from interesting features of MQTT 5 is session and message expiry.
MQTT 3.1.1 allows two kinds of session. We have a clean session which ends when a client disconnects so the broker does not need to remember anything about the client and we have a persistent session which is a session, the broker saves and persists when a client is offline and come back. the client can just resume the session. So essentially what we get here is we have a state on the broker side.

The problem here is if we have some clients which connect to the broker and disconnect and never come back. The broker can have a very hard time because it needs to persist to data until the client reconnects.When a client never reconnects essentially we get a problem here and most brokers like mosquito allow to set that time to live for a session on an administrative level. So the broker can clean up after this time.

In MQTT 5 this feature went back to the specification and now all brokers must implement a cleanup because this is needed on the broker’s side otherwise it would be a problem of denial of services attacks. So the client can say okay when I’m connecting to this broker I want the session expiry interval in let’s say 100 seconds or 10 minutes or one day and then the broker is allowed to delete the session after this time.

The problem here is let’s assume we have a car which often for one week and when it comes back doesn’t really need to get all messages.Perhaps some messages need some messages not and now sending client can send publish expiry to a published message and say to the broker “if time to live message is over do not send out the message anymore”.This allows the broker to clean up messages especially if it’s queue of messages and also it saves a lot of bandwidth.

Negative Acknowledgment

Return code for all acknowledgments is essential.


So now the broker and the client can say sorry we have a problem here and this is the problem there are reasons defined which are humanly readable. Which the broker and the client can send out if they want but they aren’t they don’t need to do this and also send a return code. These return codes are specified most of them are error codes and all client and broker must have the ability to react to this code to the returns code. So if you are a client and the broker disconnects because you were let’s say idle for long then you have the possibility on the client side to adjust the interval for sending heartbeats.

Payload format indication & Content Type

What you get here is a content type this is similar to mime types like this is a JPEG picture or this is a text.This can be sent as a meta information.You can also indicate what kind of content do we have it is also possible for up messages.We get two new headers in MQTT content type which is the mime type and you have a payload format indicator this is more interesting for debugging purposes.

Request and Response

It is possible to send hints like you want to request-response.What you can do here is you can send metadata like request response information. So a publisher can say that can send a message and it can also send a metadata.Request response information can be used that the receiver of the message can send the answer to the topic.

Shared Subscription

Share subscriptions are a very interesting concept for scaling out backend subscribers.
share subscription mqtt 5
Let’s assume we have a publisher which sends a lot of messages.We have a high-frequency topic.The problem which could arise is that the backend clients cannot process data this fast. Because it says it writes to the database which is slow at the moment, what to do how can we scale this? with MQTT 3 you cannot scale this without using shear subscriptions.

MQTT 5 has a logical or mutual shared topic a shared subscription.The client can decide ok I want to share my subscription with others clients and then the broker can send one message to the one client and one message to the other client.If you have a stream of let’s 1,000 messages/second on a topic and you have a share subscription with two clients then each of these clients get 500 messages/seconds and now if you scale out three clients then each of these backend instances get 330 messages/second and so on.This is a way how you can elastically scale up the backend subscribers or client up and down for topics which have a lot of traffic.

User Properties

MQTT 5 has headers and it’s possible to use user-defined properties which is you can just like with HTTP. Add any data you want to your MQTT packet. It can modify the publisher and user properties.Let’s say you have a publisher which has some application specific identifiers which you want to parse in the backend without looking into the whole payload of the packet contrast.the backend applications can just get out there the header without decoding the whole message.You can add unlimited user properties which is a bit controversial.

Other Features

Topic Alias: The client can choose to shrink topics.If you have a very long topic and repeatedly published.They save a lot of bandwidth because they can just use an alias.

MQTT 5 has Flow Control so our client can decide how many messages you can actually receive.

It has maximum message size indication and an authentication flow.

We also get will delay. You can tell the broker, please wait 5 seconds before sending out the last New Testament message.

The broker can tell the client what keep alive. It expects the program also overwrite client identifier.


Unfortunately, I did not find any MQTT5 broker yet expect the eclipse paho test broker.


Related Post

Android MQTT Client


Calling REST API from a Flutter App

Building Flutter applications whose content is static can be a bad idea. Instead, you should consider building applications that can fetch content from the Web server. That might sound hard, but Web server exposing their resources through REST APIs, it’s actually quite easy.

In this tutorial, I’m going to show you how to use the classes and methods available in the Flutter SDK to connect to remote web servers and interact with them using their REST APIs.

Calling REST API from a Flutter App

Creating an HTTP Connection

To create an HTTP Client we need to add an import.

The following code snippet shows you how to setup a connection with the GitHub API endpoint:

Note that the HTTP APIs use Dart Futures in the return values.Flutter recommend using the API calls with the async/await syntax.


Responsive UI

Network calls are slow.It doesn’t matter where you are on your phone.Sometimes, it will just be slow.sometimes, your server might be slow and you just don’t want to show a white page.So you want to show a progress bar.The way you do that currently in Flutter is you have a show loading equals false.If show loading is false in your building function, you show a spinner animation else ,you show your entire widget tree.Now, I didn’t want to write that over and over again, so I started finding a solution for it and so what I came across was this great library called async_loader.Following code snippet show how to use it.


To use this plugin, add async_loader as a dependency in your pubspec.yaml file.

Create instance

You need to create an async loader in your build function.It has a few parameters.It has initState,renderLoad,renderError,and renderSuccess.initState is basically as the widget is floating, what do you want to load?what data do you want to load? As renderLoad is as it’s being loaded, what do you want to show? So in renderLoad, I show a progress bar.renderError is if something went crazy wrong, what do you want to do? So here for the sake of the demo I just have new text error loading you see a boring old error loading conversation on the page.what you typically want is some sort of nice little graphic that says, oh, something went wrong please press back.and then finally when all your data is loaded, renderSuccess is called with your data that you return in your initState. And then you can take that data, and then you can actually render your entire UI.

JSON Parsing

In Android, you can use GSON for JSON parsing.There’s nothing like this on Flutter that I found, mainly because Flutter doesn’t have reflection.I’m a lazy developer. I did not want to write down all these single data types over and over again and build out a fromJSON and to map.There is a great library called json_serializable.

Setting up json_serializable

To include json_serializable, you need one regular and two dev dependencies. dev dependencies are dependencies that are not included in your app source code.

Check the latest versions.


Click “Packages Get” in your editor to make these new dependencies available in your project.

Convert  User class to a json_serializable .


When creating json_serializable classes the first time, you will get errors.Because the generated code for the model class does not exist yet. To resolve this, you must run the code generator that generates the serialization boilerplate for us.

By running (in command prompt)flutter packages pub run build_runner build in our project root, you can generate json serialization code for our models whenever needed.

Consuming json_serializable models

To deserialize a JSON string json_serializable way, we do not have actually to make any changes to our previous code.

Same goes for serialization. The calling API is the same as before.


Download Project from GitHub


Guide to Android Architecture Components

You know that early Android developers or potentially mediate Android developers might find is that they end up putting a bunch of code in their activity class and they know ends up with a very bloated activity class. So what this post suggests to you is how you might be able to divide out that code a little bit more intelligently.

What is Architecture component?

Architecture components are a growing set of libraries.They are meant for creating Android apps and the whole point of these libraries is to simplify things that might have been a little bit challenging with Android development.

Started with two libraries, a library for persistence on android and a library for lifecycle on Android and making lifecycle management easier.

The first is Room the second one is Lifecycle library and both of these libraries reached 1.0 stable in November so they are production ready and you could use them in your app safely. These libraries were built in a way where they can be used alone or they can work together just fine.So if you’re only looking for a solution to make SQLite database you could easily use Room alone without having to use other libraries if you want but they’re also designed in a way to really work well together.There is the third library called Paging library its purpose is to simplify lazily loading large data set for you.

Create an app in a way that it uses a reactive UI which means, in other words, the UI will automatically keep in sync with the database which is what are the powerful things you could do about that connection between Room and the Lifecycle library.

Design Classes

So what is the big principles of the guide is really encouraging you to have a separation of responsibilities for each of your classes.So i’m going to through each of the classes and talk about what their responsibility is.

android architecture components

The first class is the UI controller an activity or fragment.The responsibility of the UI controller is to display data. Basically, it’s telling views what to draw to the screen another responsibility that it has is capturing things like user interactions.Your activity is the one that knows if a user clicks a button.

But as soon as it gets that button click instead of processing itself it will pass on that information to a new class called the ViewModel. The ViewModel will also contain another new class called LiveData that the responsibility of the ViewModel class is to hold all of the UI data that is needed for your UI controller.

The ViewModel class then communicating with a class known as the Repository.Creating a Repository class is a convention and it’s a suggested best practice but it’s not part of the library. It’s not a new architecture component it’s just it’s a best practice and in simply put the Repository class contains the API through which you will get access to all of the apps data.

Room manages all of the local persistence of this the SQLite database.Room contains a bunch of different classes that work together including entities and DAO and database class and it’s built on top of SQLite.

Avoiding Strong References

Another core principle that I want to point out is we have separation responsibilities but we also have the idea that the classes only reference the class directly below them.what I mean is for your UI controller or your activity that class is only going to have a reference to the ViewModel. The ViewModel though will not have a reference back up to the activity and in addition the activity won’t reference the Repository or the database this sort of strict rule of avoiding strong references +like the activity to the database or in different parts of your architecture makes sure that you keep things modular and that your app doesn’t become a tangle of dependencies and what this means is that if at a later point you want to rewrite a portion of your app say that you want to replace the Room database with something else you can easily do that and you would only need to change references in the repository and not your entire app to be able to do that update it also makes thing more tastable.

Observer Pattern

In some cases, you’re going to want to be able to communicate information back from a sort of lower level on this diagram up for example, if some data changes at your database you’re gonna want to be able to communicate that back up to the UI. But the database doesn’t know about the activity. So how do we do that well you will be using the observer pattern and more specifically you will be using LiveData.In the past, you might have used callbacks but LiveData will replace that.


room architecture components

Room is SQLite object mapping library and it takes care of local data persistence for an app and Room has a lot of advantages over using the framework classes for example instead of using SQLite helper use Room you need to write a lot less boilerplate and one of the ways that it does this is that it maps database rows to objects and vice versa. So you don’t have to use intermediate values like cursors or content values you can get rid of all of those from your app. Room also does a handy thing where it validates your SQLite queries at compile time it actually won’t let you compile invalid SQL and it will also give a helpful error message so that if you wrote your SQL incorrectly you’ll know how to fix it finally Room has support to work well together with LiveData and Rxjava for that observability.


Repository class

The Repository class functions as a clean API for handling all data operations.The Repository class functions as a mediator between different data source.You might be able to imagine an example where you’re getting both data from your network server and you’re also getting data from a local data cache the logic about whether to grab new data from the server or use the local cache data and when to do additional fetches all of that complexity would be inside of the Repository class and what this means is that when your UI code needs some data it doesn’t have to worry about all the complexity of life should Repository class get this from the network or should it get this with local data caches or whatever else you might have there. So it hides that complexity of where the data is actually coming from the rest of your app.


Lifecycle Library Classes

There is a couple of core classes and concepts that you’re not going to use directly that you should be generally aware of the.First of those in that in the lifecycle library, it has an object that represents a lifecycle.A Lifecycle in android and it’s just called the lifecycle.Similarly, lifecycle owner is an object that has a lifecycle, for example, an activity or fragment.Finally is the concept of lifecycle observation so you can actually make a lifecycle observer its interface for observing lifecycles so if you’ve ever had listeners or services that require you to write some like cleanup code and onStop those listeners and services could be using lifecycle observation to be doing that clean up for you.


ViewModels provide data for UI while a surviving configuration changes common example of a configuration change is rotated your device or changing languages as well. Because ViewModel survives configuration changes they can replace AsyncTask loaders more importantly though they encourage you to have this separation of responsibilities.

In the ViewModel class, we suggest that you have all of your UI data and then leave the activity class just to be responsible for actually drawing that UI data.

As you can see here my activity data is no longer in my activity I’ve moved it over to the ViewModel and my activity gets the data that it needs to be able to display itself by communicating with the ViewModel. The ViewModel survive rotation or configuration changes.If a configuration change happens is typical activity dies and it’s recreated but importantly that activity UI data did not go with it and all that my newly recreated activity has to do is reestablish a connection with the same ViewModel which continued living through.


ViewModel survive configuration changes but they don’t survive the activity being finished.So they’re not like a permanent thing that stays around forever they’re linked to an activity lifecycle but they’re not linked to like the app lifecycle or anything like that. So when the activity finishes such as if the user presses a back button of they go to their overview screen it actually swipes your activity off the screen the ViewModel also be destroyed as well so a ViewModel does not replace a database or persisting your data.An important thing to realize that ViewModel is not a replacement for onSaveInstanceState even though they seemed similar.So if your device is very stressed out because there’s a lot of like memory constraints going on and your APIs in the background it’s possible that the os will just kill your app onSaveInstanceState is actually useful for surviving this total app destruction ViewModels don’t survive this they they also get destroyed therefore in those cases you still need to use onSaveInstanceState to get your UI data and your UI state back to what it was before.


LiveData is an object that is a data holder class and it’s also a lifecycle aware it also allows for data to be observed.

Observer pattern
Observer patternWith the observer patterns you have an object called a subject and that subject will have a list of associated objects called observers that basically register with the subject and say hey I’m interested in you please tell me when you change so then when the subject’s state changes some of that causes it to change it knows about that list of observers so it’ll notify all of them and it will usually do by calling a method that is inside of that observer object.

So LiveData follows this pattern almost exactly so in our case the LiveData is the subject and you will be creating objects called observers which are the observers.

The other property of LiveData is it is lifecycle aware. LiveData actually uses lifecycle observation it observes a lifecycle to make sure that it only notifies observers when they are in a started or resumed state.

LiveData knows how to clean up observers when they’re no longer needed so if the activity that’s associated with the observer is destroyed the observer will clean itself up which means that you are never in a case where your LiveData is updating a destroyed activity and this makes it so they could not gonna have memory leaks.

LiveData Benefits

  • Reactive UI that update automatically when data changes
  • Only updates UI in started/resumed state
  • LiveData cleans up after itself automatically.
  • Allows for the database to communicate to UI without knowing about it(Testability)



 Related Post

Architecture Components:Paging Library

Room Persistence Library

Lifecycle Aware Components