google play services – ActivityRecognitionClient no longer exists

do not run!Fiddling with some Activity Recognition code, I realised that the latest versions (I’ve got v22) of the google play services lib doesn’t contain an ActivityRecognitionClient.

Yikes!

Since the Google documentation hasn’t been updated yet – so how are you supposed to connect to Location Services and subscribe to activity recognition updates without an ActivityRecognitionClient?

Turns out you need to use the new GoogleApiClient instead (see the docs for GoogleApiClient and for ActivityRecognitionApi), like this:

private GoogleApiClient mActivityRecognitionClient;
...
private GoogleApiClient getActivityRecognitionClient() 
{
  if (mActivityRecognitionClient == null) 
  {

    mActivityRecognitionClient = new GoogleApiClient.Builder(mContext)
    .addApi(ActivityRecognition.API)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this)
    .build();
   }
   return mActivityRecognitionClient;
 }

Then, once you’ve done .connect() and received an onConnected callback, to actually request activity updates in your onConnected method:

ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(getActivityRecognitionClient(), ActivityUtils.DETECTION_INTERVAL_MILLISECONDS,
 createRequestPendingIntent());

Where your createRequestPendingIntent generates an appropriate PendingIntent to handle ActivityRecognitionResult objects (as in the example).

This also means you need to implement the GoogleApiClient’s ConnectionCallbacks and OnConnectionFailedListener too:

implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

Presumably, this makes Activity Recognition more consistent with the Android style of preferring builders over constructors with multiple parameters – stacking APIs in the “.addApi” part of the builder makes sense (plus gives them room to separate out access to the Wearable API).

See slide 64 onwards from a Google Developer advocate:

Bookmark the permalink.

Comments are closed.