Get Snapshot Data

This section shows how to use the Snapshot API to get the current state for each of the supported context types. Before using the Snapshot API, your app must connect to the Google Play Services API client. For more information, see Get Started.

Get the current activity

You can get the user's current activity by calling getDetectedActivity(), which returns an ActivityRecognitionResult containing information about the user's most recent current 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:

  1. Call SnapshotApi.getDetectedActivity(), passing an instance of the Google Play Services client.
  2. Use a ResultCallback to get the DetectedActivityResult.
  3. Call getStatus() to ensure that the result is valid.
  4. Call DetectedActivityResult.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 shows using getMostProbableActivity() to get the most probable detected activity, and logging the result to the console:

Awareness.SnapshotApi.getDetectedActivity(mGoogleApiClient)
        .setResultCallback(new ResultCallback<DetectedActivityResult>() {
            @Override
            public void onResult(@NonNull DetectedActivityResult detectedActivityResult) {
                if (!detectedActivityResult.getStatus().isSuccess()) {
                    Log.e(TAG, "Could not get the current activity.");
                    return;
                }
                ActivityRecognitionResult ar = detectedActivityResult.getActivityRecognitionResult();
                DetectedActivity probableActivity = ar.getMostProbableActivity();
                Log.i(TAG, probableActivity.toString());
            }
        });

Get nearby beacons

You can get information about nearby beacons by calling 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:

  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 has the effect of returning only beacons with attachments that are registered using the specified namespace and type. You can also filter based on a byte-for-byte match on the attachment content. The following example shows creating 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 SnapshotApi.getBeaconState().

  4. Use a ResultCallback to get the BeaconStateResult.
  5. Call getStatus() to ensure that the result is valid.
  6. Call BeaconStateResult.getBeaconState() to return the beacon state.
  7. Call BeaconState.getBeaconInfo() to get a BeaconState.BeaconInfo.

The following example shows getting beacon info:

Awareness.SnapshotApi.getBeaconState(mGoogleApiClient, BEACON_TYPE_FILTERS)
                .setResultCallback(new ResultCallback<BeaconStateResult>() {
                    @Override
                    public void onResult(@NonNull BeaconStateResult beaconStateResult) {
                        if (!beaconStateResult.getStatus().isSuccess()) {
                            Log.e(TAG, "Could not get beacon state.");
                            return;
                        }
                        BeaconState beaconState = beaconStateResult.getBeaconState();
                        // Get info from the BeaconState.
                    }
                });

Get headphone state

You can detect whether headphones are plugged in to the device by calling SnapshotApi.getHeadphoneState(), which returns a HeadphoneStateResult. You can then call HeadphoneStateResult.getHeadphoneState().

To get the current headphone state:

  1. Call SnapshotApi.getHeadphoneState().
  2. Use a ResultCallback to get the HeadphoneStateResult.
  3. Call getStatus() to ensure that the result is valid.
  4. Call HeadphoneStateResult.getHeadphoneState() to return the headphone state.
  5. Call HeadphoneState.getState() to get the HeadphoneState.State. This value will be either PLUGGED_IN or UNPLUGGED.

The following code example shows using getHeadphoneState():

Awareness.SnapshotApi.getHeadphoneState(mGoogleApiClient)
                .setResultCallback(new ResultCallback<HeadphoneStateResult>() {
                    @Override
                    public void onResult(@NonNull HeadphoneStateResult headphoneStateResult) {
                        if (!headphoneStateResult.getStatus().isSuccess()) {
                            Log.e(TAG, "Could not get headphone state.");
                            return;
                        }
                        HeadphoneState headphoneState = headphoneStateResult.getHeadphoneState();
                        if (headphoneState.getState() == HeadphoneState.PLUGGED_IN) {
                            Log.i(TAG, "Headphones are plugged in.\n");
                        } else {
                            Log.i(TAG, "Headphones are NOT plugged in.\n");
                        }
                    }
                });

Get location

You can get the user's current location (lat/lng) by calling SnapshotApi.getLocationSnapshot(), which returns a LocationResult. You can then call getLocation() to get a Location with the current location data.

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

To get the current location:

  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.getLocation().

  3. Use a ResultCallback to get the LocationResult.
  4. Call getStatus() to ensure that the result is valid.
  5. Call LocationResult.getLocation() to return the current Location.

The following example shows getting the current location:

Awareness.SnapshotApi.getLocation(mGoogleApiClient)
                .setResultCallback(new ResultCallback<LocationResult>() {
                    @Override
                    public void onResult(@NonNull LocationResult locationResult) {
                        if (!locationResult.getStatus().isSuccess()) {
                            Log.e(TAG, "Could not get location.");
                            return;
                        }
                        Location location = locationResult.getLocation();
                        Log.i(TAG, "Lat: " + location.getLatitude() + ", Lng: " + location.getLongitude());
                    }
                });

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 WeatherResult. You can then call WeatherResult.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:

  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 ResultCallback to get the WeatherResult.
  4. Call getStatus() to ensure that the result is valid.
  5. Call WeatherResult.getWeather().

The following example shows getting the current weather conditions for the user:

Awareness.SnapshotApi.getWeather(mGoogleApiClient)
                .setResultCallback(new ResultCallback<WeatherResult>() {
                    @Override
                    public void onResult(@NonNull WeatherResult weatherResult) {
                        if (!weatherResult.getStatus().isSuccess()) {
                            Log.e(TAG, "Could not get weather.");
                            return;
                        }
                        Weather weather = weatherResult.getWeather();
                        Log.i(TAG, "Weather: " + weather);
                    }
                });

Send feedback about...

assistant
Google Awareness API