ActivityRecognitionClient

public interface ActivityRecognitionClient implements HasApiKey<Api.ApiOptions.NoOptions>

The main entry point for interacting with activity recognition.

Activity Recognition provides the following APIs: the Activity Recognition Transition API, the Activity Recognition Sampling API, and the Activity Recognition Sleep API

Activity Recognition Transition API
The Transition API is the preferred way of using Activity Recognition because it improves accuracy, consumes less power, and enhances engineering productivity. It is suitable for all use cases and developers get notified when a user activity has changed. As an example, you can use the API to detect when the user has entered or exited the vehicle to set the user's status to busy. Similarly, a parking detection app can use the API to detect when the user has exited a vehicle and started walking. For details, refer to requestActivityTransitionUpdates(ActivityTransitionRequest, PendingIntent).

Activity Recognition Sampling API
This may be useful for apps that:

  • need more fine-grained control over the frequency at which activity recognition is running
  • have unique precision and/or recall requirements and therefore want access to unfiltered, raw activity data
When using this API, apps are responsible for managing power consumption via the detectionInterval parameter and writing a filter on top of the raw activity classifications as individual predictions may be noisy. The transition API handles these for you which is why we recommend using the transition API instead of the raw API whenever possible. For details, refer to requestActivityUpdates(long, PendingIntent).

Sleep API
The Sleep API is a separate API for detecting a user's sleep time using the accelerometer sensor and the ambient light sensor. Sleep confidence is computed based on the sensor data, and reported at regular intervals. In addition, any detected sleep time ranges are reported each day after a high-confidence awakening is detected.

Public Method Summary

abstract Task<Void>
removeActivityTransitionUpdates(PendingIntent pendingIntent)
Removes activity transition updates associated with the given pendingIntent.
abstract Task<Void>
removeActivityUpdates(PendingIntent callbackIntent)
Removes all activity updates for the specified PendingIntent.
abstract Task<Void>
removeSleepSegmentUpdates(PendingIntent callbackIntent)
Removes all sleep segment detection updates for the specified PendingIntent.
abstract Task<Void>
requestActivityTransitionUpdates(ActivityTransitionRequest activityTransitionRequest, PendingIntent pendingIntent)
Activity Recognition Transition API provides an ability for apps to subscribe to activity transitional conditions (enter, exit).
abstract Task<Void>
requestActivityUpdates(long detectionIntervalMillis, PendingIntent callbackIntent)
Register for activity recognition updates.
abstract Task<Void>
requestSleepSegmentUpdates(PendingIntent callbackIntent, SleepSegmentRequest sleepSegmentRequest)
Registers for detected user sleep time (SleepSegmentEvent) and/or periodic sleep activity classification results (SleepClassifyEvent) based on the data type specified in SleepSegmentRequest.

Public Methods

public abstract Task<Void> removeActivityTransitionUpdates (PendingIntent pendingIntent)

Removes activity transition updates associated with the given pendingIntent.

To call this function, a different permission is required depending on your Android API level:

  • For Android 10 (API level 29) and later: android.permission.ACTIVITY_RECOGNITION permission
  • For Android 9 (API level 28) and earlier: com.google.android.gms.permission.ACTIVITY_RECOGNITION permission
Parameters
pendingIntent the associated PendingIntent of the activity transition request which is to be removed
Returns

public abstract Task<Void> removeActivityUpdates (PendingIntent callbackIntent)

Removes all activity updates for the specified PendingIntent.

To call this function, a different permission is required depending on your Android API level:

  • For Android 10 (API level 29) and later: android.permission.ACTIVITY_RECOGNITION permission
  • For Android 9 (API level 28) and earlier: com.google.android.gms.permission.ACTIVITY_RECOGNITION permission
Parameters
callbackIntent the PendingIntent that was used in requestActivityUpdates(long, PendingIntent) or is equal as defined by PendingIntent.equals(Object).
Returns

public abstract Task<Void> removeSleepSegmentUpdates (PendingIntent callbackIntent)

Removes all sleep segment detection updates for the specified PendingIntent.

Parameters
callbackIntent the PendingIntent that was used in requestSleepSegmentUpdates(PendingIntent, SleepSegmentRequest) or is equal as defined by PendingIntent.equals(Object).
Returns

public abstract Task<Void> requestActivityTransitionUpdates (ActivityTransitionRequest activityTransitionRequest, PendingIntent pendingIntent)

Activity Recognition Transition API provides an ability for apps to subscribe to activity transitional conditions (enter, exit). For example, a messaging app that wants to build a distraction free driving experiences can ask -- tell me when user has entered the vehicle or exited the vehicle. It doesn't have to worry about user being DetectedActivity.STILL at the traffic signal, or any other transient activities while in vehicle (DetectedActivity.IN_VEHICLE), that is, the API will fence around the activity boundaries using Activity Recognition Filtering.

The activities supported with the Transition API are:

The interested activity transitions are specified by the ActivityTransitionRequest and when such transition happens a callback intent will be generated by the provided PendingIntent.

The transition request is identified by the given PendingIntent which means if this method is called with different ActivityTransitionRequest but same PendingIntent, the ActivityTransitionRequest in the last call overrides any other ActivityTransitionRequests in previous calls

To call this function, a different permission is required depending on your Android API level:

  • For Android 10 (API level 29) and later: android.permission.ACTIVITY_RECOGNITION permission
  • For Android 9 (API level 28) and earlier: com.google.android.gms.permission.ACTIVITY_RECOGNITION permission

When the requested transition event occurs, app will receive a callback intent; The ActivityTransitionResult can be extracted from the intent (use the ActivityTransitionResult.extractResult(Intent) utility method), to get the list of ActivityTransitionEvents. The events are ordered in the chronological order of time. As an example, if an app requests for DetectedActivity.IN_VEHICLE on ActivityTransition.ACTIVITY_TRANSITION_ENTER and ActivityTransition.ACTIVITY_TRANSITION_EXIT events respectively; then it will receive the vehicle enter event, when user starts driving, and the vehicle exit event when user transitions to any other activity;

Example:


    void requestActivityTransitionUpdates(final Context context) {
      ActivityTransitionRequest request = buildTransitionRequest();
      // PendingIntent pendingIntent;  // Your pending intent to receive callbacks.
      Task task = ActivityRecognition.getClient(context)
          .requestActivityTransitionUpdates(request, pendingIntent);
      task.addOnSuccessListener(
          new OnSuccessListener() {
             @Override
             public void onSuccess(Void result) {
               // Handle success...
             }
          });
      task.addOnFailureListener(
          new OnFailureListener() {
             @Override
             public void onFailure(Exception e) {
                // Handle failure...
             }
          });
      ...
    }

    // Example Transition Request....
    ActivityTransitionRequest buildTransitionRequest() {
      List transitions = new ArrayList<>();
      transitions.add(new ActivityTransition.Builder()
         .setActivityType(DetectedActivity.IN_VEHICLE)
         .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
         .build());
      transitions.add(new ActivityTransition.Builder()
         .setActivityType(DetectedActivity.IN_VEHICLE)
         .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
         .build());
      transitions.add(new ActivityTransition.Builder()
         .setActivityType(DetectedActivity.WALKING)
         .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_ENTER)
         .build());
      transitions.add(new ActivityTransition.Builder()
         .setActivityType(DetectedActivity.WALKING)
         .setActivityTransition(ActivityTransition.ACTIVITY_TRANSITION_EXIT)
         .build());
      return new ActivityTransitionRequest(transitions);
    }

    // Handle the callback intent in your service...
    @Override
    protected void onReceive(Context context, Intent intent) {
      if (ActivityTransitionResult.hasResult(intent)) {
        ActivityTransitionResult result = ActivityTransitionResult.extractResult(intent);
        for (ActivityTransitionEvent event : result.getTransitionEvents()) {
          // Do something useful here...
        }
      }
    }

 
Parameters
activityTransitionRequest the interested activity transitions
pendingIntent the PendingIntent used to generate the callback intent when one of the interested transition has happened
Returns

public abstract Task<Void> requestActivityUpdates (long detectionIntervalMillis, PendingIntent callbackIntent)

Register for activity recognition updates.

The activities are detected by periodically waking up the device and reading short bursts of sensor data. It only makes use of low power sensors in order to keep the power usage to a minimum. For example, it can detect if the user is currently on foot, in a car, on a bicycle or still. See DetectedActivity for more details.

The activity detection update interval can be controlled with the detectionIntervalMillis parameter. Larger values will result in fewer activity detections while improving battery life. Smaller values will result in more frequent activity detections but will consume more power since the device must be woken up more frequently. Long.MAX_VALUE means it only monitors the results requested by other clients without consuming additional power.

Activities may be received more frequently than the detectionIntervalMillis parameter if another application has also requested activity updates at a faster rate. It may also receive updates faster when the activity detection service receives a signal that the current activity may change, such as if the device has been still for a long period of time and is then unplugged from a phone charger.

Activities may arrive several seconds after the requested detectionIntervalMillis if the activity detection service requires more samples to make a more accurate prediction.

To conserve battery, activity reporting may stop when the device is 'STILL' for an extended period of time. It will resume once the device moves again. This only happens on devices that support the Sensor.TYPE_SIGNIFICANT_MOTION hardware.

Beginning in API 21, activities may be received less frequently than the detectionIntervalMillis parameter if the device is in power save mode and the screen is off.

A common use case is that an application wants to monitor activities in the background and perform an action when a specific activity is detected. To do this without needing a service that is always on in the background consuming resources, detected activities are delivered via an intent. The application specifies a PendingIntent callback (typically an IntentService) which will be called with an intent when activities are detected. The intent recipient can extract the ActivityRecognitionResult using ActivityRecognitionResult.extractResult(android.content.Intent). See the documentation of PendingIntent for more details.

Any requests previously registered with requestActivityUpdates(long, PendingIntent) that have the same PendingIntent (as defined by PendingIntent.equals(Object)) will be replaced by this request.

This call will keep the Google Play services connection active, so make sure to call removeActivityUpdates(PendingIntent) when you no longer need it, otherwise you lose the benefits of the automatic connection management.

To call this function, a different permission is required depending on your Android API level:

  • For Android 10 (API level 29) and later: android.permission.ACTIVITY_RECOGNITION permission
  • For Android 9 (API level 28) and earlier: com.google.android.gms.permission.ACTIVITY_RECOGNITION permission
Parameters
detectionIntervalMillis the desired time between activity detections. Larger values will result in fewer activity detections while improving battery life. A value of 0 will result in activity detections at the fastest possible rate. Note that a fast rate can result in excessive device wakelocks and power consumption.
callbackIntent a PendingIntent to be sent for each activity detection.
Returns

public abstract Task<Void> requestSleepSegmentUpdates (PendingIntent callbackIntent, SleepSegmentRequest sleepSegmentRequest)

Registers for detected user sleep time (SleepSegmentEvent) and/or periodic sleep activity classification results (SleepClassifyEvent) based on the data type specified in SleepSegmentRequest. It is advised to the apps to re-register after device reboot or app upgrade, from a receiver that handles android.intent.action.BOOT_COMPLETED and android.intent.action.MY_PACKAGE_REPLACED events.

This API is not supported for wearable devices. Devices with the system feature of PackageManager#FEATURE_WATCH don't receive detection callbacks from this API.

Note - Power saving modes may lead to the decreased device performance to save battery. This can affect the quality of sleep detection and intervals at which the sleep events are reported.

If SleepSegmentEvent is requested, the app receives a callback intent that contains a SleepSegmentEvent after a high-confidence awakening is detected each day. Each SleepSegmentEvent includes a status code and the sleep start and end times. On Successful registration this API also returns the previous day's detected sleep segment if available. The receiver should call SleepSegmentEvent.hasEvents(Intent) to check for the presence of SleepSegmentEvent, and call SleepSegmentEvent.extractEvents(Intent) to get the list of SleepSegmentEvents.

Developers can additionally use the SleepClassifyEvent for implementing customized sleep segmentation by combining with additional app data. Example app data may include a user-defined sleep window, in-app alarm, user telling the app they are going to bed now or just woke up, historical sleep pattern, or any other additional clues of user being awake or asleep.

If SleepClassifyEvent is requested, the app receives a callback intent with SleepClassifyEvent at a regular interval, for example, every 10 minutes. Each SleepClassifyEvent includes the classification timestamp, sleep confidence and the supporting data of ambient light level and device motion near the time of classification. The receiver should call SleepClassifyEvent.hasEvents(Intent) to check for the presence of SleepClassifyEvent, and call SleepClassifyEvent.extractEvents(Intent) to get the list of SleepClassifyEvents. This can be useful for apps that apply post processing algorithms on top of the raw sleep classification results.

To call this function, a different permission is required depending on your Android API level:

  • For Android 10 (API level 29) and later: android.permission.ACTIVITY_RECOGNITION permission
  • For Android 9 (API level 28) and earlier: com.google.android.gms.permission.ACTIVITY_RECOGNITION permission
Parameters
callbackIntent a PendingIntent to be sent for each sleep segment or classification result
sleepSegmentRequest a SleepSegmentRequest that specifies whether to receive both SleepSegmentEvents and SleepClassifyEvents, or SleepSegmentEvents only, or SleepClassifyEvents only.
Returns