Get snapshot data

This section shows how to use the Snapshot API to get the current state for each of the supported context types. For more information, see Get started. For details on deprecated contextual signals, open the following expandable notice:

Get the current activity

To get the user's current activity, call getDetectedActivity(), which returns an ActivityRecognitionResult that contains information about the user's most recent activities.

The getDetectedActivity() method requires the com.google.android.gms.permission.ACTIVITY_RECOGNITION permission. Add this permission to AndroidManifest.xml.

To get the user's current activity, perform the following steps:

  1. Call getSnapshotClient() to create an instance of the SnapshotClient.
  2. Use addOnSuccessListener to create an OnSuccessListener that can listen for a DetectedActivityResponse.
  3. Call getStatus() to ensure that the result is valid.
  4. Call DetectedActivityResponse.getActivityRecognitionResult() to return an ActivityRecognitionResult. You can use this to get many aspects of the user's current activity. For example:

The following code example uses getMostProbableActivity() to get the most probable detected activity, and to log the result to the console:

Awareness.getSnapshotClient(this).getDetectedActivity()
    .addOnSuccessListener(new OnSuccessListener<DetectedActivityResponse>() {
        @Override
        public void onSuccess(DetectedActivityResponse dar) {
            ActivityRecognitionResult arr = dar.getActivityRecognitionResult();
            DetectedActivity probableActivity = arr.getMostProbableActivity();

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

Get nearby beacons

To get information about nearby beacons, call getBeaconState(). Beacon data consists of the content, type, and namespace of any attachments.

The getBeaconState() method requires the android.permission.ACCESS_FINE_LOCATION permission. Add this permission to AndroidManifest.xml. In addition, you must activate the Nearby Messages API for your Google Developers Console project. For more information, see Signup and API Keys and Get started.

To get information about nearby beacons, perform the following steps:

  1. Check whether the user has granted the required permissions. The following example checks to see whether the android.permission.ACCESS_FINE_LOCATION permission is granted. If not, the user is prompted for consent.

    if (ContextCompat.checkSelfPermission(
                MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSION_LOCATION
            );
            return;
        }
    
  2. Define a BeaconState.TypeFilter. This returns only beacons with attachments that are registered with the specified namespace and type. You can also filter based on a byte-for-byte match on the attachment content. The following example shows how to create a type filter:

    private static final List<BeaconState.TypeFilter> BEACON_TYPE_FILTERS = Arrays.asList(
            BeaconState.TypeFilter.with(
                "my.beacon.namespace",
                "my-attachment-type"),
            BeaconState.TypeFilter.with(
                "my.other.namespace",
                "my-attachment-type"));
    
  3. Call getSnapshotClient.getBeaconState().

  4. Use addOnSuccessListener to create an OnSuccessListener that can listen for a BeaconStateResponse.

  5. Call getStatus() to ensure that the result is valid.

  6. Call BeaconStateResponse.getBeaconState() to return the beacon state.

  7. Call BeaconState.getBeaconInfo() to get a BeaconState.BeaconInfo.

The following example shows how to get beacon info:

Awareness.getSnapshotClient(this).getBeaconState(BEACON_TYPE_FILTERS)
    .addOnSuccessListener(new OnSuccessListener<BeaconStateResponse>() {
        @Override
        public void onSuccess(BeaconStateResponse beaconStateResponse) {
            BeaconStateResult beaconStateResult = beaconStateResponse.getBeaconState();
            BeaconState.BeaconInfo beaconInfo = beaconStateResponse.getBeaconInfo();
        }
    })

Get headphone state

To detect whether headphones are plugged into the device, call getHeadphoneState(), which creates a HeadphoneStateResponse detect state with OnSuccessListener set to detect. You can then call getHeadphoneState() to get the HeadphoneState.

To get the current headphone state, perform the following steps:

  1. Call getSnapshotClient.getHeadphoneState().
  2. Use addOnSuccessListener to create an OnSuccessListener that can listen for a HeadphoneStateResponse.
  3. Call getStatus() to ensure that the result is valid.
  4. On success, call HeadphoneStateResponse.getHeadphoneState() to return the headphone state. This value is either PLUGGED_IN or UNPLUGGED.

The following code example shows how to use getHeadphoneState():

Awareness.getSnapshotClient(this).getHeadphoneState()
    .addOnSuccessListener(new OnSuccessListener<HeadphoneStateResponse>() {
        @Override
        public void onSuccess(HeadphoneStateResponse headphoneStateResponse) {
            HeadphoneState headphoneState = headphoneStateResponse.getHeadphoneState();
            boolean pluggedIn = headphoneState.getState() == HeadphoneState.PLUGGED_IN;
            String stateStr =
                "Headphones are " + (pluggedIn ? "plugged in" : "unplugged");
            mLogFragment.getLogView().println(stateStr);
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG, "Could not get headphone state: " + e);
        }
    });

Get location

You can get the user's current location (latitude-longitude) with a call to getLocation(), which returns a LocationResponse. You can then call LocationResponse.getLocation() to get a Location with the current location data.

The getLocation() method requires the android.permission.ACCESS_FINE_LOCATION permission. Add this permission to AndroidManifest.xml.

To get the current location, perform the following steps:

  1. Check whether the user has granted the required permissions. The following example checks to see whether the android.permission.ACCESS_FINE_LOCATION permission has been granted. If not, the user is prompted for consent.

    
    if (ContextCompat.checkSelfPermission(
                MainActivity.this,
                Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    MainActivity.this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSION_LOCATION
            );
            return;
        }
    
  2. Call getSnapshotClient.getLocation().

  3. Use addOnSuccessListener to create an OnSuccessListener that can listen for a LocationResponse.

  4. Call getStatus() to ensure that the result is valid.

  5. Call LocationResponse.getLocation() to return the current Location.

The following example shows how to get the current location:

Awareness.getSnapshotClient(this).getLocation()
    .addOnSuccessListener(new OnSuccessListener<LocationResponse>() {
        @Override
        public void onSuccess(LocationResponse locationResponse) {
            Location loc = locationResponse.getLocationResult();
        }
    })