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.

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 logs 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 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 in to the device, call getHeadphoneState(), which creates a HeadphoneStateResponse detect with OnSuccessListener 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 (lat/lng) by calling 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();
        }
    })

Get nearby places

You can get a list of places near the user by calling SnapshotApi.getPlaces(), which returns a PlacesResult. You can then call PlacesResult.getPlaceLikelihoods() to get a list of potential places ranked by likelihood. The place with the highest likelihood is the best guess as to the current place in which the user may currently be located.

To use the SnapshotApi.getPlaces() method, you must:

  • Enable the Google Places API for Android in your Google Developers Console project. For more information, see Signup and API Keys.
  • Add the android.permission.ACCESS_FINE_LOCATION permission to AndroidManifest.xml.

To get the list of nearby places:

  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 SnapshotApi.getPlaces().

  3. Use a ResultCallback to get the PlacesResult.

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

  5. Call PlacesResult.getPlaceLikelihoods() to return a List of PlaceLikelihood instances.

The following example shows getting a list of possible places:

Awareness.SnapshotApi.getPlaces(mGoogleApiClient)
    .setResultCallback(new ResultCallback<PlacesResult>() {
        @Override
        public void onResult(@NonNull PlacesResult placesResult) {
            if (!placesResult.getStatus().isSuccess()) {
                Log.e(TAG, "Could not get places.");
                    return;
                }
                List<PlaceLikelihood> placeLikelihoodList = placesResult.getPlaceLikelihoods();
                // Show the top 5 possible location results.
                for (int i = 0; i < 5; i++) {
                    PlaceLikelihood p = placeLikelihoodList.get(i);
                    Log.i(TAG, p.getPlace().getName().toString() + ", likelihood: " + p.getLikelihood());
                }
        }
    });

Get weather

You can get the weather conditions in the user's current location by calling SnapshotApi.getWeather(), which returns a WeatherResponse. You can then call WeatherResponse.getWeather() to get a Weather instance with the current local weather conditions.

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

To get current weather conditions in the user's 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 SnapshotApi.getWeather().

  3. Use a SuccessListener to get the WeatherResponse.

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

  5. Call WeatherResponse.getWeather().

The following example shows how to get the current weather conditions for the user:

Awareness.getSnapshotClient(this).getWeather()
    .addOnSuccessListener(new OnSuccessListener<WeatherResponse>() {
        @Override
        public void onSuccess(WeatherResponse weatherResponse) {
            Weather weather = weatherResponse.getWeather();
            weather.getConditions();
            mLogFragment.getLogView().println("Weather: " + weather);
        }
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            Log.e(TAG, "Could not get weather: " + e);
        }
    });