ActivityRecognitionClient

public class ActivityRecognitionClient extends GoogleApi<Api.ApiOptions.NoOptions>

The main entry point for interacting with activity recognition.

Activity Recognition provides two APIs: the Activity Recognition Transition API and the Activity Recognition Sampling 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).

Inherited Field Summary

Public Method Summary

Task<Void>
removeActivityTransitionUpdates(PendingIntent pendingIntent)
Removes activity transition updates associated with the given pendingIntent.
Task<Void>
removeActivityUpdates(PendingIntent callbackIntent)
Removes all activity updates for the specified PendingIntent.
Task<Void>
requestActivityTransitionUpdates(ActivityTransitionRequest activityTransitionRequest, PendingIntent pendingIntent)
Activity Recognition Transition API provides an ability for apps to subscribe to activity transitional conditions (enter, exit).
Task<Void>
requestActivityUpdates(long detectionIntervalMillis, PendingIntent callbackIntent)
Register for activity recognition updates.

Inherited Method Summary

Public Methods

public 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
  • a Task for apps to check the status of the call. If the task fails, the status code for the failure can be found by examining getStatusCode().

public 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 equals(Object).
Returns
  • a Task for apps to check the status of the call. If the task fails, the status code for the failure can be found by examining getStatusCode().

public 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 STILL at the traffic signal, or any other transient activities while in vehicle (IN_VEHICLE) i.e 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 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 IN_VEHICLE on ACTIVITY_TRANSITION_ENTER and 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
  • a Task for apps to check the status of the call. If the task fails, the status code for the failure can be found by examining getStatusCode().

public 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 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 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.
callbackIntent a PendingIntent to be sent for each activity detection.
Returns
  • a Task for apps to check the status of the call. If the task fails, the status code for the failure can be found by examining getStatusCode().