Activity Recognition API Tutorial for Android: Getting Started

Learn to track your activities in your Android app by creating a fitness app that uses the Activity Recognition API. By Andrej Vukelic.

4 (4) · 2 Reviews

Download materials
Save for later
Share

Activity tracking is nothing new in the world of apps. While Google created an Activity Recognition API a long time ago, they recently improved its performance with a series of APIs, grouped into the ActivityRecognitionClient.

The APIs contained within ActivityRecognitionClient include:

  1. Activity Recognition Transition API for tracking transitions between activities.
  2. Activity Recognition Sampling API to get more frequent results for potential activities.
  3. Sleep API for detecting a user’s sleep time.

In this tutorial, you’ll learn how to use the Transition and Sampling APIs by creating Pet Buddy, an app that tracks physical activity changes.

Note: This tutorial assumes you know the basics of Android development with Kotlin. If you’re new to Kotlin, check out our Kotlin introduction tutorial. If you’re completely new to Android development, read through our Beginning Android Development tutorials to familiarize yourself with the basics.

Why Use the Activity Recognition Client

Mobile devices have become an indispensable part of life. Your users have their phones with them all day. That helps your app become smarter and better at helping your users in their daily routines.

The Activity Recognition Client collects data from the sensors available in mobile devices. Those sensors help your app better understand a user.

Improved accuracy, lower battery consumption and enhanced engineering productivity are some of the Transition API’s benefits. It tells the app when a user starts or stops an activity, whether it be walking, running or riding in a vehicle.

For more frequent requests or raw activity data, you’ll use the Sampling API. Of course, more frequent requests mean more battery consumption, which, depending on the use case, you’re responsible for managing. While the Transition API manages battery consumption for you, the Sampling API gives you more control over the data.

Last but not least, the Sleep API is a separate API for detecting a user’s sleep routine. To compute sleep confidence, it uses the accelerometer sensor and the ambient light sensor data. It also provides sleep time ranges each day once it detects a high-confidence awakening.

Note: If you want to learn how to use the Sleep API, check out Android Sleep API Tutorial: Getting Started or the official documentation.

Now that you’re familiar with the APIs, you can start working on your first activity recognition app.

Getting Started

Download the starter project by clicking Download Materials at the top or bottom of the tutorial. Then, open the starter project in Android Studio 3.5 or later.

Look at the code. You’ll find the starter project with activities, a layout, a permission helper and a lot of to-dos.

Build and run the starter project. You’ll see buttons to start and stop activity tracking and a label that says tracking hasn’t started yet. There’s also an ImageView holder for an image that represents a current activity.

Starting activity in Pet Buddy

Try using the app. Tap Start and you’ll get a message that tracking has started.

But when you start walking, nothing happens because activity tracking isn’t implemented yet. Don’t worry: It’s easier than you think!

If you’ve developed an app that uses sensors, you know you need to request permission to use them. In the next section, you’ll learn how to request the permission needed to start tracking your activities.

Unleashing the Power of Sensors

All Android developers need to know how to handle permissions. To use Android features like storage, location and camera, you need to request permission.

Yet, not all permissions need explicit requests for all Android versions. Sometimes, all you need to do is add it to the manifest.

You need to request permission to use the Activity Recognition Client on devices running on Android Q, API level 29, or later. For earlier versions, a one-liner in the manifest will do the magic for you.

First, open AndroidManifest.xml. Replace TODO 1 with:

<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />

Devices running below Android Q use the first permission. To enable the Activity Recognition Client for Android Q or later, you’ll need the second permission. But, there’s more work left to enable sensors on devices with Android Q or later.

Note: Use the key combination Option-Return on Mac Alt-Enter on PC to resolve any missing dependencies as you work through your project.

Note: Use the key combination Option-Return on Mac Alt-Enter on PC to resolve any missing dependencies as you work through your project.

Open the ActivityPermissionHelper.kt class. Then replace TODO 2 and with the next block of code:

val isAndroidQOrLater: Boolean =
    android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q

return if (isAndroidQOrLater.not()) {
  true
} else {
  PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(
      this,
      Manifest.permission.ACTIVITY_RECOGNITION
  )
}

Here’s a step-by-step breakdown of this logic:

  1. isAndroidQOrLater gives you the information if you need to request permission.
  2. For devices with a version below Android Q, you don’t have to check permission status. It’s enough to return true.
  3. For devices running on Android Q or later, you’ll need to check the permission.

Now Pet Buddy can check permission status. Next, you’ll request permission if it’s not granted.

In ActivityPermissionHelper.kt, find TODO 3 and replace it with:

if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACTIVITY_RECOGNITION).not()) {
    ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.ACTIVITY_RECOGNITION), PERMISSION_REQUEST_ACTIVITY_RECOGNITION)
  } else {
    showRationalDialog(this)
  }

The Permission rationale check returns on the next check after denying permission. Note that the condition is a negative value from the result.

If that condition is true, the native permission request dialog will show. When the result is false, the user sees a custom rationale dialog.

Build and run. Tap Start and deny the permission. Then tap Start again and your screen will look like this:

Rationale dialog for requesting permission

In the rationale dialog, you explain why the app needs this permission. The Permission rationale check returns false after two permission requests. Next, you need to consume the permission request result.

Open MainActivity.kt. Then find TODO 4 and replace it with:

if (ActivityCompat.shouldShowRequestPermissionRationale(this,
            Manifest.permission.ACTIVITY_RECOGNITION).not() &&
        grantResults.size == 1 &&
        grantResults[0] == PackageManager.PERMISSION_DENIED) {
      showSettingsDialog(this)
    } else if (requestCode == PERMISSION_REQUEST_ACTIVITY_RECOGNITION &&
        permissions.contains(Manifest.permission.ACTIVITY_RECOGNITION) &&
        grantResults.size == 1 &&
        grantResults[0] == PackageManager.PERMISSION_GRANTED) {
      Log.d("permission_result", "permission granted")
      isTrackingStarted = true
    }

The code above grants permission when the following conditions are true:

  • The request code matches one from the request.
  • The permissions contain Manifest.permission.ACTIVITY_RECOGNITION.
  • grantResults contains PackageManager.PERMISSION_GRANTED.

Build and run. First, tap Start. Then deny permission two times and take note of the screen:

Transition between the standing still and walking

After denying permission for the second time, a dialog appears and asks the user to grant permission in the settings.

Now, reinstall the app. Tap Start again, but this time allow the permission. Take a look at the logcat and you’ll see:

com.raywenderlich.android.petbuddy D/permission_result: permission granted

Congratulations! You’re ready to start implementing Activity Recognition Client functionalities.

In the next section, you’ll learn more about the activity types supported by the Activity Recognition Client.