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.
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.
To declare a dependency to the API, add a reference to the Google maven repository and add an implementation entry to com.google.android.gms:play-services-location:12.0.0 to the dependencies section of your app build.gradle file.
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.
Toast.makeText(mContext,"Transition update set up",Toast.LENGTH_LONG).show();
Toast.makeText(mContext,"Transition update Failed to set up",Toast.LENGTH_LONG).show();
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.
House advertise the availability and rates of their driveways, So your phone could scan for them and query all of them and book the one that makes more sense for you in a completely offline fashion.Taking it one step further, if you are late getting back, why can’t these houses then query your car, which will tell them that you are just a block away, so I can avoid being penalized or towed.Because implementing these features entails dealing with the vagaries of Bluetooth and Wi-Fi across the product, the range of Android os version out there and the variety of hardware out there.What these apps back then needed was a reliable performance proximity platform that abstracts away all this complexity and leaves them free so they can focus on just adding the features that matter to their users.
Nearby Connections API
Nearby Connections enables advertising and discovery of nearby devices, as well as high-bandwidth low-latency encrypted data transfers between these devices in a fully-offline P2P manner.It achieves this by using a combination of classic Bluetooth, BLE, and Wi-Fi hotspots.It leverages the strengths of each while supplementing their respective weaknesses.For instance, Bluetooth has low connection latency but also provides low bandwidth Wi-Fi hotspots have slightly higher connection latency, but also provide much higher bandwidth. So what it does is connect over Bluetooth and start transferring data instantly but in the background, it also brings up a Wi-Fi hotspot and when that’s ready, it seamlessly transfers your connection from Bluetooth to WiFi with absolutely no work required by the app developer.
Nearby API Flow
1.An advertiser calls startAdvertising(), and sometime later, a discover calls startDiscovery(). Soon enough, the discovery is alerted to the advertiser’s presence by means of the onEndpointFound() callback. If the discoverer is interested, they can call requestConnection().This is the end of the asymmetric part of the API and from here on everything is completely symmetric.
2.Both sides get an onConnectionInitiated() callback that gives them an authentication token they can use to verify they are indeed talking to each other.Upon out-of-band verification, they can both either call acceptConnection() or rejectConnection().When each side gets the other’s response, it invokes the ConnectionLifecycleCallback.onConnectionResult() callback.At this point, the connection is either established or it’s not.
3.From here, either side can send payload by calling the sendPayload()method.This leads to the other side getting the PayloadCallback.onPayloadReceived()callback, followed by both sides getting a series of PayloadCallback.onPayloadTransferUpdate() callbacks up until the transfer reaches the final state of success or failure.
4.Finally, either side can disconnect at any time, and that leads to the other side getting the ConnectionLifecycleCallback.onDisconnected() callback.
Nearby API support three kinds of payloads 1.Bytes, these are byte arrays of up to 32k, and they are typically used for sending metadata control messages. 2.Files, these represent files of the device’s storage and Nearby API make sure that it transfer from the application to the network interface with a minimal amount of copying across process boundaries. 3.Streams, this is good for when you need to generate data on the fly, and you don’t know the final size up front, as is the case with recorded audio or video.
As I mentioned earlier, Nearby API uses multiple radio techniques to advertise, discover, and establish connections.The combinations of interactions of these techniques are qualified in its strategies.Strategies are named for how far they’ll cause their net to try and find a nearby device and what kind of connection topology they will enable.Right now, it has two of them, P2P_STAR and P2P_CLUSTER.
As the name might suggest, P2P_STAR makes sense for when you want to enforce a star network with a 1-to-N connection topology.And P2P_CLUSTER make sense when you want to allow for slightly looser M-to-M connection topologies.For example, a classroom app where the teacher wants to host a quiz for all the students, that would probably be best mounted over P2P_STAR with the teacher as the one advertiser and the students at the end discovers and the same classroom app could have a mode that allows students to break out into ephemeral project groups.This mode,where students want to drift in and out of multiple groups,would be best served with P2P_CLUSTER.
Now let’s see how all this can be put together in an undoubtedly harmless mock application.
Before you start to code using the Nearby Connections API:
// We successfully requested a connection. Now both sides
// must accept before the connection is established.
// Nearby Connections failed to request the connection.
Depending on your use case, you may wish to instead display a list of discovered devices to the user, allowing them to choose which devices to connect to.
Accept or reject a connection
After the discoverer has requested a connection to an advertiser, both sides are notified of the connection initiation process via the onConnectionInitiated() method of the ConnectionLifecycleCallbackcallback. Note that this callback is passed in to startAdvertising() on the advertiser and requestConnection() on the discoverer, but from this point forward, the API is symmetric.
Now both sides must choose whether to accept or reject the connection via a call to acceptConnection()or rejectConnection(), respectively. The connection is fully established only when both sides have accepted. If one or both reject, the connection is discarded. Either way, the result is delivered toonConnectionResult().
The following code snippet shows how to implement this callback:
// The connection was rejected by one or both sides.
// The connection broke before it was able to be accepted.
// We've been disconnected from this endpoint. No more data can be
// sent or received.
Once connections are established between devices, you can exchange data by sending and receiving Payload objects. A Payload can represent a simple byte array, such as a short text message; a file, such as a photo or video; or a stream, such as the audio stream from the device’s microphone.
Payloads of the same type are guaranteed to arrive in the order they were sent, but there is no guarantee of preserving the ordering amongst payloads of different types. For example, if a sender sends a FILE payload followed by a BYTE payload, the receiver could get the BYTE payload first, followed by the FILE payload.
Send and Receive
To send payloads to a connected endpoint, call sendPayload().To receive payloads, implement the onPayloadReceived() method of the PayloadCallback that was passed to acceptConnection().
Here are the slightly less bone-chilling uses of nearby Connections spotted in the wild.
The Weather channel is using Nearby Connections to build a pretty darn cool offline mesh to help spread urgent weather updates and warnings, especially in the wake of natural disasters.
Sendanywhere is a South Korean app that allows sharing files intelligently in the most efficient manner possible, regardless of whether you’re online or not.They’re using Nearby Connections for their offline modality.
Pocket Casts have been a great partner for Nearby Messages.They now want to enable people sharing and discovering podcasts in a completely offline manner. For example, when you’re stuck in an aircraft and are looking to cloud so what’s your options for entertainment?
GameInsight is a leading game developer, and they’re using Nearby Connections to not only find nearby players but also to run their games completely offline. Again, being stuck in the inside of an aircraft comes to mind.
Hotstar is India’s fastest growing streaming network.They’re using nearby connections to allow offline sharing of downloaded movies and TV shows.So you don’t need to have access to the internet.You only need access to friend who does.
Android TV is about to launch a new remote control app where they use Nearby Connections to not only set up your new Android TV and configure it to be on your Wi-Fi network, but also to serve interactive second stream content in a streaming fashion.
Bluetooth low energy wireless technology gives context to the environment around you.It perfect for devices that run for long periods on power sources, such as coin cell batteries. Native support for Bluetooth technology on every major operating system enables development for a broad range of connected devices.
low power consumption.
connectivity to mobile phones.
global availability, license free.
How low power work?
BLE device remains in sleep mode constantly except for when a connection is initiated. The actual connection times are only afew ms, unlike Bluetooth which would take ~100mS. The reason the connections are so short, is that the data rates are so high at 1 Mb/s.
By keeping the radio off.
Lower standby time, Faster connection, Lower peak power.
BLE technology uses only 3 advertising channels.
Application of BLE
Bluetooth with its LE functionality powers the Internet of Things. You wake up and go for a run with a heart rate monitor that communicates with your smart watch, then listen to music through your shower head.
Transferring small amounts of data between nearby devices.
Interacting with proximity sensors like Google Beacons to give users a customized experience based on their current location.
It can enable proximity detection(I’m in the car).
It can enable presence detection (Turn the lights on when I walk around the house).
It can send data from anything to the Internet (I’ve walked 4,000 steps today)
It can control everything (Unlock doors)
It connects everything to the Internet (check if you switched the lights off)
Key Terms and Concepts
1.Generic Attribute Profile (GATT) : The GATT profile is a general specification for sending and receiving short pieces of data known as “attributes” over a BLE link. All current Low Energy application profiles are based on GATT.
The Bluetooth SIG defines many profiles for Low Energy devices. A profile is a specification for how a device works in a particular application. Device can implement more than one profile. For example, a device could contain a heart rate monitor and a battery level detector
2.Attribute Protocol (ATT)—GATT is built on top of the Attribute Protocol (ATT). This is also referred to as GATT/ATT. ATT is optimized to run on BLE devices. To this end, it uses as few bytes as possible. Each attribute is uniquely identified by a Universally Unique Identifier (UUID), which is a standardized 128-bit format for a string ID used to uniquely identify information. The attributes transported by ATT are formatted as characteristics and services.
3.Characteristic—A characteristic contains a single value and 0-n descriptors that describe the characteristic’s value. A characteristic can be thought of as a type, analogous to a class.
4.Descriptor—Descriptors are definedattributes that describe a characteristic value. For example, a descriptor might specify a human-readable description, an acceptable range for a characteristic’s value, or a unit of measure that is specific to a characteristic’s value.
5.Service—A service is a collection of characteristics. For example, you could have a service called “Heart Rate Monitor” that includes characteristics such as “heart rate measurement”. You can find a list of existing GATT-based profiles and services on bluetooth.org.
6.Central vs. peripheral : The device in the central role scans, looking for advertisement, and the device in the peripheral role makes the advertisement.For example , you have an phone and battery level detector that is a BLE device. The phone supports the central role and the activity tracker supports the peripheral role.
7.GATT server vs. GATT client This determines how two devices talk to each other once they’ve established the connection.For example , App is the GATT client. The app gets data from the GATT server, which is a BLE Battery Level Detector.
Android bluetooth low energy example
In the example, the Android app running on an Android device is the GATT client. The app gets data from the GATT server, which is a BLEBattery Level Detector that supports the Battery Level Service.
BluetoothDevice: Represents a remote Bluetooth device. You create a connection with the respective device or query information about it, such as the name, address, class, and bonding state.
BluetoothAdapter:You perform fundamental Bluetooth tasks, such as initiate device discovery, query a list of paired devices, instantiate a BluetoothDevice using a known MAC address.getRemoteDevice(String) to create one representing a device of a known MAC address or get one from the set of bonded devices returned by getBondedDevices().Use getBluetoothLeScanner() to get an instance of BluetoothLeScanner.
BluetoothGatt: Provides Bluetooth GATT functionality to enable communication with Bluetooth Smart or Smart Ready devices.
BluetoothLeScanner: Class provides methods to perform scan related operations for Bluetooth LE devices. An application can scan for a particular type of Bluetooth LE devices using ScanFilter. It can also request different types of callbacks for delivering the result.
You need BLUETOOTH permission to perform requesting a connection, accepting a connection, and transferring data.You must also declare the BLUETOOTH_ADMIN permission for device discovery or manipulate Bluetooth settings.
The BluetoothAdapter represents the device’s own Bluetooth adapter (the Bluetooth radio). There’s one Bluetooth adapter for the entire system, and your application can interact with it using this object.
The first step in interacting with a BLE device is connecting to it (connecting to the GATT server on the device). To connect to a GATT server on a BLE device, you use the connectGatt() method. This method takes three parameters: a Context object,autoConnect, and a reference to a BluetoothGattCallback
Log.w(TAG,"BluetoothAdapter not initialize or unspecified address");
When a particular callback is triggered, it calls the broadcastUpdate() helper method and passes it an action. Data parsing in this section is performed in accordance with the Bluetooth Battery Service Measurement profile specifications
To enable or disable notifications for a given characteristic setCharacteristicNotification to BluetoothGatt.Reads the requested characteristic from the associated remote device set readCharacteristic.
Message Queue Telemetry Transport(MQTT) is a machine-to-machine (M2M)/Internet of Things connectivity protocol. It was designed as an extremely lightweight publish-subscribe based messaging protocol for use on top of the TCP/IP protocol. It is designed for connections to remote locations where a small code footprint is required or the network bandwidth is limited. The publish-subscribe messaging pattern requires a message broker. The broker is responsible for distributing messages to interested clients based on the topic of a message.
Real world applications
MQTT has been used in sensors communicating to a broker via satellite link, over occasional dial-up connections with healthcare providers, and in a range of home automation and small device scenarios. It is also ideal for mobile applications because of its small size, low power usage, minimized data packets, and efficient distribution of information to one or many receivers.
The broker is primarily responsible for receiving all messages, filtering them, decide who is interested in it and then sending the message to all subscribed clients.It also holds the session of all persisted clients including subscriptions and missed messages.MQTT Mosquitto is a message broker that implements the MQTT 3.1/3.1.1.There is a publically accessible sandbox server for the Eclipse IoT projects available at iot.eclipse.org:1883.
Multiple clients connect to a broker and subscribe to topics that they are interested in. Clients also connect to the broker and publish messages to topics.
Android MQTT client
The Eclipse Paho project provides open-source client implementations of MQTT.Paho Android Service is an MQTT client library written in Java for developing applications on Android.The MQTT connection is encapsulated within an Android Service that runs in the background of the Android application, keeping it alive when the Android application is switching between different Activities.The Paho Android Service is an interface to the Paho Java MQTT Client library for the Android Platform.
The most convenient way to start a new Android Application is to use Android Studio. Download Paho Android Service and Android MQTT Client library.Go to your libs folder inside app folder and paste all your .jar
To add the Paho Android Service as a dependency to you app add the following parts to your gradle file.
MqttAndroidClient will connect with MQTT 3.1.1 by default. To intentionally connect with MQTT 3.1 MqttConnectOptions object can be supplied to the connect method
On connection, a client sets the “clean session” flag.If the clean session is set to false, then the connection is treated as durable. This means that when the client disconnects, any subscriptions it has will remain and any subsequent QoS 1 or 2 messages will be stored until it connects again in the future. If the clean session is true, then all subscriptions will be removed from the client when it disconnects.
Sets whether the client will automatically attempt to reconnect to the server if the connection is lost.If set to true, in the event that the connection is lost, the client will attempt to reconnect to the server. It will initially wait 1 second before it attempts to reconnect, for every failed to reconnect attempt, the delay will double until it is at 2 minutes at which point the delay will stay at 2 minutes.
When a client connects to a broker, it may inform the broker that it has a will. This is a message that it wishes the broker to send when the client disconnects unexpectedly. The will message has a topic, QoS and retains status just the same as any other message.
Messages published to the topic if the connection is available, but if it disconnects and connects again offline messages send.Holds the set of options that govern the behavior of Offline (or Disconnected) buffering of messages.
Creates an instance of an Android MQTT client, that will bind to the Paho Android Service. By calling the connect method of the MqttAndroidClient the client will asynchronously try to connect to the MQTT broker and return a token. That token can be used to register callbacks, to get notified when either the MQTT-connection gets connected or an error occurs
Messages in MQTT are published on topics. There is no need to configure a topic, publishing on it is enough. Topics are treated as a hierarchy, using a slash (/) as a separator much in the same way as a filesystem.
Clients can receive messages by creating subscriptions. A subscription may be to an explicit topic, in which case only messages to that topic will be received, or it may include wildcards. Two wildcards are available, +or.#
Quality of Service
MQTT defines 3 levels of Quality of Service (QoS). The QoS defines how hard the broker/client will try to ensure that a message is received. Messages may be sent at any QoS level, and clients may attempt to subscribe to topics at any QoS level.
0: The broker/client will deliver the message once, with no confirmation.
1: The broker/client will deliver the message at least once, with confirmation required.
2: The broker/client will deliver the message exactly once by using a 4 step handshake.
The broker will keep the message even after sending it to all current subscribers. If a new subscription is made that matches the topic of the retained message will be sent to the client. This is useful as a “last known good” mechanism. With a retained message, the client will receive an instant update.
The MqttAndroidClient allows messages to be published via its publish method.