Context Is King: Your Guide To Google’s Awareness API

Imagine this scenario: you’re out for a run with just your Android phone and a pair of Airpods, rocking out to Iron Maiden while grabbing some desperately needed cardio. Just as Bruce Dickinson reaches for the epic, operatic conclusion of “Run To The Hills,” you get an incoming phone call with the volume at full blast. Your skull is left splitting like it was cleaved by some frost giant’s ax.

Now imagine the same scenario, but the phone knows you’re listening to music on your headphones. In this scenario, the device anticipates the call and knows to turn down the volume of incoming alerts.

This is one example of contextual awareness, which can be a lifesaver when applied to various user-facing applications. The Google Awareness API is one of the most powerful, popular, and useful context APIs, letting you control your projects using seven different types of contextual data.

Below we’ll delve into the Google Awareness API. We’ll explore what it is, show why it’s useful, and even explain how to integrate the Google Awareness API into your development projects. Read on for our guide to the Google Awareness API.

What Is The Google Awareness API?

Think back to our jogging example up top. Your phone knowing that you’ve got headphones in is one example of ‘contextual awareness.’ Contextual awareness acts as a sensory system for mobile devices, allowing your apps and mobile projects to adapt to the current environment.

The Google Awareness API is Google’s solution for delivering relevant contextual data to your app while still being energy and memory-efficient. That’s Google Awareness’ main selling point as it consolidates seven different contexts into one API. These include:

  • Local time
  • Latitude and Longitude
  • Location
  • User activity
  • Nearby beacons
  • Headphone status
  • Local weather conditions

It doesn’t take much imagination to daydream some scenarios where this contextual data could be helpful. Certain local weather conditions could trigger appropriate playlist recommendations, for instance. Proximity to certain locations could trigger offers for relevant deals or coupons, as another example.

The Google Awareness API is actually two APIs in one: the Fence API and the Snapshot API.

  • The Fence API lets you combine a number of signals, like approaching a location or the onset of rain.
  • The Snapshot API lets your app request any combination of the seven contexts’ current statuses.

None of these concepts, in and of themselves, are exactly revelatory. What is striking about the Google Awareness API is how easy it is to use. Its efficiency is its other main selling point, as the API monitors battery and data usage.

Benefits Of Google Awareness API

The potential benefits of using the Google Awareness API are numerous. On the user’s end, you certainly wouldn’t want your ringer going off at full volume while you were attending a church service or in a business meeting, as just one example. On the other hand, if you were out jogging, maybe you’d want to know that the cafe around the corner is having a deal on lemonade?

For the developers, the potential applications are nearly endless. First of all, you can use the Google Awareness API to create geofencing solutions, which can be useful for everything from local marketing to tracking rich data from participating users.

Just as importantly, Google’s context API lets you add that little something extra to your mobile apps and projects. It helps you deliver the best user experience (UX) to your audience, which can be the make-or-break point between an app being used or discarded.

Google Awareness API’s ease of use is one final selling point. You’ll need to have a Google account to work with the Google Awareness API, but once you’re set-up, it’s easy to pop the API into one of your projects and begin consuming context data immediately.

Getting Started With Google Awareness API

Now we’re going to show you how you can integrate the Google Awareness API into your own Android project.

To start, you need to get an API key.

Next, configure your app to consume the Google Awareness API. Open the project-level build.gradle file in your Android project and insert the following code into the buildscript and allprojects sections.

buildscript {
    repositories {
        google()
    }
}

allprojects {
    repositories {
        google()
    }
}

Next, include the dependencies for the Google Awareness API in the app-level gradle file, which is usually located in the app/build.gradle file.

dependencies {
  implementation 'com.google.android.gms:play-services-awareness:18.0.2'
}

Now, add your API key to the AndroidManifest.xml file. In the AndroidManifest.xml file, insert a tag under the <application> section. Then, define the android:name and android:value.

<manifest>
    <application>
        <meta-data
            android:name="com.google.android.awareness.API_KEY"
            android:value="API_KEY"/>
    </application>
</manifest>

Finally, you need to add the necessary permissions to your AndroidManifest.xml file. These permissions will vary, depending on the API method and the types of fences your app uses.

Example Google Awareness API Call

Here’s an example of the Google Awareness API in action. This example shows how to call getDetectedActivity() using the connectionless Google Play service and the Google Awareness API.

    // Each type of contextual information in the snapshot API has a corresponding "get" method.
    // For instance, this is how to get the user's current Activity.
    Awareness.getSnapshotClient(this).getDetectedActivity()
        .addOnSuccessListener(new OnSuccessListener<DetectedActivityResponse>() {
            @Override
            public void onSuccess(DetectedActivityResponse dar) {
                ActivityRecognitionResult arr = dar.getActivityRecognitionResult();
                // getMostProbableActivity() is good enough for basic Activity detection.
                // To work within a threshold of confidence,
                // use ActivityRecognitionResult.getProbableActivities() to get a list of
                // potential current activities, and check the confidence of each one.
                DetectedActivity probableActivity = arr.getMostProbableActivity();

                int confidence = probableActivity.getConfidence();
                String activityStr = probableActivity.toString();
                mLogFragment.getLogView().println("Activity: " + activityStr
                    + ", Confidence: " + confidence + "/100");
            }
        })

That’s all it takes to get up and running with the Google Awareness API. Remember, the Google Awareness API is actually two APIs — the Fence API and the Snapshot API. Each has its own rules for working them, which you can explore further in the documentation:

Google Awareness API Best Practices

Remember, one of the main reasons to use the Awareness API is to deliver a better UX. Here are a couple of best practices to keep in mind to make the most of the Awareness API.

  • Communicate With Users: Clearly communicating with your users about what your app does and what to expect will smooth over most negative user experiences. Imagine that your app will automatically start playing music when they plug in their headphones. Let your users know this ahead of time so they won’t blow up their eardrums.
  • Message Sparingly: If your app needs to deliver alerts based on contextual data, keep it to a minimum. Message your users as infrequently as possible, especially considering the fact that other apps might be sending alerts to your user at the same time.
  • Use Sparingly: Even though the Awareness API is self-monitoring, it can still consume a lot of battery life if left unchecked. To keep battery usage to a minimum, register as few fences as you can get away with.

Keep your Snapshot calls to a minimum, as well, to avoid draining the battery too quickly. Finally, if your app requires a task that isn’t time or location-dependent, you might use a different API instead to save on resources.

Google Awareness API Final Thoughts

Integrating contextual data into your app takes great strides towards making your app “smart.” It essentially gives your app eyes and ears, making for far more complex and elegant environments. With a bit of finesse, you can create some truly sophisticated, nuanced, reactive apps.

As you’ll notice from our example, the one main downside of the Google Awareness API is it’s only available for Android. If you’re looking for a comparable context data API for iOS, you can try Radar, which also has a free tier for testing.

Considering how many mobile apps are out there, app developers need to do everything they can to stand out from the competition. Delivering a pleasant, efficient user experience is its own reward, as well.

Apps and mobile technology are only going to keep becoming smarter and more aware. If you’re developing mobile tech, you’re going to need to come to grips with contextual data at some point. The Google Awareness API is your best bet to get started with contextual data with minimal effort.