Courtesy: GitHub

Google Play Location Samples

Samples that use Location APIs to help you make your applications location aware.

This repo contains the following samples:

  1. Basic Location Sample: Retrieve the last known location for a device.
  2. Location Updates: Get updates about a device's location.

  3. Location Updates using a PendingIntent: Get updates about a device's location using a PendingIntent. Sample shows implementation using an IntentService as well as a BroadcastReceiver.
  4. Location Updates using a Foreground Service: Get updates about a device's location using a bound and started foreground service.
  5. Location Address: Use the Geocode API to display a device's location as an address.
  6. Creating and Monitoring Geofences: Create geofences and process enter and exit transitions.
  7. Recognizing the User's Current Activity: Use the ActivityRecognitionApi to determine the user's current activity.

Prerequisites

  • Android API Level >v9
  • Android Build Tools >v21
  • Google Support Repository

Getting Started

These samples use the Gradle build system. To build a sample, use the "gradlew build" command or use "Import Project" in Android Studio.

Support

If you've found an error in these samples, please file an issue: https://github.com/googlesamples/android-play-location/issues

Patches are encouraged, and may be submitted according to the instructions in CONTRIBUTING.md.

License

Copyright 2014 Google, Inc.

Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.activityrecognition"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.android.support:design:25.3.1'

compile 'com.google.android.gms:play-services-location:11.4.0'

compile 'com.google.code.gson:gson:2.7'

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.locationupdatespendingintent"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.android.support:design:25.3.1'

compile 'com.google.android.gms:play-services-location:11.0.0'

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.basiclocationsample"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.android.support:design:25.3.1'

compile 'com.google.android.gms:play-services-location:11.0.0'

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.locationupdates"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.android.support:design:25.3.1'

compile 'com.google.android.gms:play-services-location:11.0.0'

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.locationupdatesforegroundservice"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.google.android.gms:play-services-location:11.0.0'

compile 'com.android.support:design:25.3.1'

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.locationaddress"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile fileTree(dir: 'libs', include: ['*.jar'])

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.android.support:design:25.3.1'

compile 'com.google.android.gms:play-services-location:11.0.0'

compileSdkVersion 25

applicationId "com.google.android.gms.location.sample.geofencing"

minSdkVersion 16

targetSdkVersion 25

versionCode 1

versionName "1.0"

compile 'com.android.support:appcompat-v7:25.3.1'

testCompile 'junit:junit:4.12'

compile 'com.android.support:design:25.3.1'

compile 'com.google.android.gms:play-services-location:11.0.0'

compile 'com.google.android.gms:play-services-maps:11.0.0'

package com.google.android.gms.location.sample.activityrecognition

uses-permission

  • com.google.android.gms.permission.ACTIVITY_RECOGNITION

package com.google.android.gms.location.sample.locationupdatespendingintent

uses-permission

  • android.permission.ACCESS_FINE_LOCATION

package com.google.android.gms.location.sample.basiclocationsample

uses-permission

  • android.permission.ACCESS_COARSE_LOCATION

package com.google.android.gms.location.sample.locationupdates

uses-permission

  • android.permission.ACCESS_FINE_LOCATION

package com.google.android.gms.location.sample.locationupdates

uses-permission

  • android.permission.ACCESS_MOCK_LOCATION

package com.google.android.gms.location.sample.locationupdatesforegroundservice

uses-permission

  • android.permission.ACCESS_FINE_LOCATION

package com.google.android.gms.location.sample.locationaddress

uses-permission

  • android.permission.ACCESS_FINE_LOCATION

package com.google.android.gms.location.sample.geofencing

uses-permission

  • android.permission.ACCESS_FINE_LOCATION

MainActivity

The entry point for interacting with activity recognition.

Adapter backed by a list of DetectedActivity objects.

Registers for activity recognition updates using {@link ActivityRecognitionClient#requestActivityUpdates(long, PendingIntent)}. Registers success and failure callbacks.

Removes activity recognition updates using {@link ActivityRecognitionClient#removeActivityUpdates(PendingIntent)}. Registers success and failure callbacks.

Gets a PendingIntent to be sent for each activity detection.

Ensures that only one button is enabled at any time. The Request Activity Updates button is enabled if the user hasn't yet requested activity updates. The Remove Activity Updates button is enabled if the user has requested activity updates.

Retrieves the boolean from SharedPreferences that tracks whether we are requesting activity updates.

Sets the boolean in SharedPreferences that tracks whether we are requesting activity updates.

Processes the list of freshly detected activities. Asks the adapter to update its list of DetectedActivities with new {@code DetectedActivity} objects reflecting the latest detected activities.

MainActivity

Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

The only activity in this sample. Displays UI widgets for requesting and removing location updates, and for the batched location updates that are reported. * Location updates requested through this activity continue even when the activity is not in the foreground. Note: apps running on "O" devices (regardless of targetSdkVersion) may receive updates less frequently than the interval specified in the {@link LocationRequest} when the app is no longer in the foreground.

The desired interval for location updates. Inexact. Updates may be more or less frequent.

The fastest rate for active location updates. Updates will never be more frequent than this value, but they may be less frequent.

The max time before batched results are delivered by location services. Results may be delivered sooner than this interval.

Stores parameters for requests to the FusedLocationProviderApi.

Provides access to the Fused Location Provider API.

Sets up the location request. Android has two location request settings: {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in the AndroidManifest.xml.

When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update interval (5 seconds), the Fused Location Provider API returns location updates that are accurate to within a few feet.

These settings are appropriate for mapping applications that show real-time location updates.

Return the current state of the permissions needed.

Callback received when a permissions request has been completed.

Handles the Request Updates button and requests start of location updates.

Handles the Remove Updates button, and requests removal of location updates.

Ensures that only one button is enabled at any time. The Start Updates button is enabled if the user is not requesting location updates. The Stop Updates button is enabled if the user is requesting location updates.

MainActivity

Location sample.

Demonstrates use of the Location API to retrieve the last known location for a device.

Provides the entry point to the Fused Location Provider API.

Represents a geographical location.

Provides a simple way of getting a device's location and is well suited for applications that do not require a fine-grained location and that do not need location updates. Gets the best and most recent location currently available, which may be null in rare cases when a location is not available.

Note: this method should be called after location permission has been granted.

Shows a {@link Snackbar} using {@code text}. * @param text The Snackbar text.

Shows a {@link Snackbar}. * @param mainTextStringId The id for the string resource for the Snackbar text. @param actionStringId The text of the action item. @param listener The listener associated with the Snackbar action.

Return the current state of the permissions needed.

Callback received when a permissions request has been completed.

MainActivity

Using location settings.

Uses the {@link com.google.android.gms.location.SettingsApi} to ensure that the device's system settings are properly configured for the app's location needs. When making a request to Location services, the device's system settings may be in a state that prevents the app from obtaining the location data that it needs. For example, GPS or Wi-Fi scanning may be switched off. The {@code SettingsApi} makes it possible to determine if a device's system settings are adequate for the location request, and to optionally invoke a dialog that allows the user to enable the necessary settings.

This sample allows the user to request location updates using the ACCESS_FINE_LOCATION setting (as specified in AndroidManifest.xml).

Code used in requesting runtime permissions.

Constant used in the location settings dialog.

The desired interval for location updates. Inexact. Updates may be more or less frequent.

The fastest rate for active location updates. Exact. Updates will never be more frequent than this value.

Provides access to the Fused Location Provider API.

Provides access to the Location Settings API.

Stores parameters for requests to the FusedLocationProviderApi.

Stores the types of location services the client is interested in using. Used for checking settings to determine if the device has optimal location settings.

Callback for Location events.

Represents a geographical location.

Tracks the status of the location updates request. Value changes when the user presses the Start Updates and Stop Updates buttons.

Time when the location was updated represented as a String.

Updates fields based on data stored in the bundle. * @param savedInstanceState The activity state saved in the Bundle.

Sets up the location request. Android has two location request settings: {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in the AndroidManifest.xml.

When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update interval (5 seconds), the Fused Location Provider API returns location updates that are accurate to within a few feet.

These settings are appropriate for mapping applications that show real-time location updates.

Creates a callback for receiving location events.

Uses a {@link com.google.android.gms.location.LocationSettingsRequest.Builder} to build a {@link com.google.android.gms.location.LocationSettingsRequest} that is used for checking if a device has the needed location settings.

Handles the Start Updates button and requests start of location updates. Does nothing if updates have already been requested.

Handles the Stop Updates button, and requests removal of location updates.

Requests location updates from the FusedLocationApi. Note: we don't call this unless location runtime permission has been granted.

Updates all UI fields.

Disables both buttons when functionality is disabled due to insuffucient location settings. Otherwise ensures that only one button is enabled at any time. The Start Updates button is enabled if the user is not requesting location updates. The Stop Updates button is enabled if the user is requesting location updates.

Sets the value of the UI fields for the location latitude, longitude and last update time.

Removes location updates from the FusedLocationApi.

Stores activity data in the Bundle.

Shows a {@link Snackbar}. * @param mainTextStringId The id for the string resource for the Snackbar text. @param actionStringId The text of the action item. @param listener The listener associated with the Snackbar action.

Return the current state of the permissions needed.

Callback received when a permissions request has been completed.

MainActivity

MainActivity

Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

The only activity in this sample. Note: for apps running in the background on "O" devices (regardless of the targetSdkVersion), location may be computed less frequently than requested when the app is not in the foreground. Apps that use a foreground service - which involves displaying a non-dismissable notification - can bypass the background location limits and request location updates as before. This sample uses a long-running bound and started service for location updates. The service is aware of foreground status of this activity, which is the only bound client in this sample. After requesting location updates, when the activity ceases to be in the foreground, the service promotes itself to a foreground service and continues receiving location updates. When the activity comes back to the foreground, the foreground service stops, and the notification associated with that foreground service is removed. * While the foreground service notification is displayed, the user has the option to launch the activity from the notification. The user can also remove location updates directly from the notification. This dismisses the notification and stops the service.

Returns the current state of the permissions needed.

Callback received when a permissions request has been completed.

Receiver for broadcasts sent by {@link LocationUpdatesService}.

MainActivity

Getting the Location Address. Demonstrates how to use the {@link android.location.Geocoder} API and reverse geocoding to display a device's location as an address. Uses an IntentService to fetch the location address, and a ResultReceiver to process results sent by the IntentService. Android has two location request settings: {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in the AndroidManifest.xml. For a starter example that displays the last known location of a device using a longitude and latitude, see https://github.com/googlesamples/android-play-location/tree/master/BasicLocation. For an example that shows location updates using the Fused Location Provider API, see https://github.com/googlesamples/android-play-location/tree/master/LocationUpdates.

Provides access to the Fused Location Provider API.

Represents a geographical location.

Tracks whether the user has requested an address. Becomes true when the user requests an address and false when the address (or an error message) is delivered.

The formatted location address.

Receiver registered with this activity to get the response from FetchAddressIntentService.

Displays the location address.

Visible while the address is being fetched.

Kicks off the request to fetch an address when pressed.

Updates fields based on data stored in the bundle.

Runs when user clicks the Fetch Address button.

Creates an intent, adds location data to it as an extra, and starts the intent service for fetching an address.

Gets the address for the last known location.

Updates the address in the UI.

Toggles the visibility of the progress bar. Enables or disables the Fetch Address button.

Shows a toast with the given text.

Receiver for data sent from FetchAddressIntentService.

Receives data sent from FetchAddressIntentService and updates the UI in MainActivity.

Shows a {@link Snackbar} using {@code text}. * @param text The Snackbar text.

Shows a {@link Snackbar}. * @param mainTextStringId The id for the string resource for the Snackbar text. @param actionStringId The text of the action item. @param listener The listener associated with the Snackbar action.

Return the current state of the permissions needed.

Callback received when a permissions request has been completed.

MainActivity

Demonstrates how to create and remove geofences using the GeofencingApi. Uses an IntentService to monitor geofence transitions and creates notifications whenever a device enters or exits a geofence.

This sample requires a device's Location settings to be turned on. It also requires the ACCESS_FINE_LOCATION permission, as specified in AndroidManifest.xml.

Tracks whether the user requested to add or remove geofences, or to do neither.

Provides access to the Geofencing API.

The list of geofences used in this sample.

Used when requesting to add or remove geofences.

Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored. Also specifies how the geofence notifications are initially triggered.

Adds geofences, which sets alerts to be notified when the device enters or exits one of the specified geofences. Handles the success or failure results returned by addGeofences().

Adds geofences. This method should be called after the user has granted the location permission.

Removes geofences, which stops further notifications when the device enters or exits previously registered geofences.

Removes geofences. This method should be called after the user has granted the location permission.

Runs when the result of calling {@link #addGeofences()} and/or {@link #removeGeofences()} is available. @param task the resulting Task, containing either a result or error.

Gets a PendingIntent to send with the request to add or remove Geofences. Location Services issues the Intent inside this PendingIntent whenever a geofence transition occurs for the current list of geofences. * @return A PendingIntent for the IntentService that handles geofence transitions.

This sample hard codes geofence data. A real app might dynamically create geofences based on the user's location.

Ensures that only one button is enabled at any time. The Add Geofences button is enabled if the user hasn't yet added geofences. The Remove Geofences button is enabled if the user has added geofences.

Shows a {@link Snackbar} using {@code text}. * @param text The Snackbar text.

Shows a {@link Snackbar}. * @param mainTextStringId The id for the string resource for the Snackbar text. @param actionStringId The text of the action item. @param listener The listener associated with the Snackbar action.

Returns true if geofences were added, otherwise false.

Stores whether geofences were added ore removed in {@link SharedPreferences}; * @param added Whether geofences were added or removed.

Performs the geofencing task that was pending until location permission was granted.

Return the current state of the permissions needed.

Callback received when a permissions request has been completed.

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

GeofenceTransitionsIntentService

Listener for geofence transition changes. * Receives geofence transition events from Location Services in the form of an Intent containing the transition type and geofence id(s) that triggered the transition. Creates a notification as the output.

This constructor is required, and calls the super IntentService(String) constructor with the name for a worker thread.

Handles incoming intents. @param intent sent by Location Services. This Intent is provided to Location Services (inside a PendingIntent) when addGeofences() is called.

Gets transition details and returns them as a formatted string. * @param geofenceTransition The ID of the geofence transition. @param triggeringGeofences The geofence(s) triggered. @return The transition details formatted as String.

Posts a notification in the notification bar when a transition is detected. If the user clicks the notification, control goes to the MainActivity.

Maps geofence transition types to their human-readable equivalents. * @param transitionType A transition type constant defined in Geofence @return A String indicating the type of transition