0% found this document useful (0 votes)
53 views57 pages

7.1 Location

The document discusses how to get and use a device's location on Android. It covers setting up Google Play services, requesting location permissions, and using the FusedLocationProviderClient to get the most recent location or request location updates.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views57 pages

7.1 Location

The document discusses how to get and use a device's location on Android. It covers setting up Google Play services, requesting location permissions, and using the FusedLocationProviderClient to get the most recent location or request location updates.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Advanced Android Development

Location

Lesson 7

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 1
License.
7.1 Location services
Using physical location in an app

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 2
License.
Contents
● Overview
● Setting up Google Play services
● Location permissions
● Get device location
● Geocoding and reverse geocoding
● Creating a LocationRequest object
● Working with user settings
● Requesting location updates
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 3
License.
Overview

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 4
License.
Introduction
● Mobile phones – key word is MOBILE
● Users move around and go places
● Your app can detect and use the
device location to customize the
experience for the user

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 5
License.
Using location in your app

● Check if location permission has been granted


● Ask for permission if necessary
● Request most recent location
● Request location updates

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 6
License.
Get the device location
● Use FusedLocationProviderClient
● Makes location requests combining GPS, Wi-Fi, and cell
network
● Balances fast, accurate results with minimal battery drain
● Returns Location object with latitude and longitude

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 7
License.
Get the device location
● Use Geocoder to convert Latitude 51.5
lat/long location to physical Longitude -0.078
address

Tower Bridge,
Tower Bridge Rd,
London SE1 2UP
UK
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 8
License.
Setting up
Google Play
services

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 9
License.
Setting up Google Play services
Location services are provided by Google Play Services
Install Google Repository in Android Studio
1. Select Tools > Android > SDK Manager
2. Select the SDK Tools tab
3. Expand Support Repository
4. Select Google Repository and click OK

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 10
License.
Adding Google Play to your project
Add to dependencies in build.gradle (Module: app):

compile 'com.google.android.gms:play-services:xx.x.x'

● xx.x.x is version number, such as 11.0.2.


● Replace with new version number, if Android Studio suggests it

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 11
License.
Location
permissions

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 12
License.
Users choose to share their location
From Marshmallow onwards:
● Users grant or deny access to their
location for each app
● Users can change access permission at
any time
● Your app can prompt user to grant
permission to use location
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 13
License.
Users choose to share their location

For apps created before Marshmallow:


● users grant permission before
installing
● after installation, user cannot change
access permission
● your app can check if permission has
been granted
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 14
License.
Requesting location permission
Apps must request location permission
● ACCESS_COARSE_LOCATION
for location accurate to within a city block
● ACCESS_FINE_LOCATION
for get precise location

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 15
License.
Request permission in manifest
<uses-permission
android:name=
"android.permission.ACCESS_FINE_LOCATION"
/>

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 16
License.
Requesting permission at run time

● User can revoke permission at any time


● Check for permission each time your app uses location
● Details and examples: Requesting Permissions at Runtime

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 17
License.
Steps to check/request permission

1. Use checkSelfPermission() to see if permission granted


2. Use requestPermissions() to request permission
3. Check user response to see if request was granted

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 18
License.
Check/request permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION_PERMISSION);
} else {
Log.d(TAG, "getLocation: permissions granted");
}
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 19
License.
Get user's response
Override onRequestPermissionsResult() to check if user
granted permission

@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case REQUEST_LOCATION_PERMISSION: {
// Check if the permission is granted.
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 20
License.
Check if request was granted
● Response is returned in permissions array
● Compare grantResults parameter to
PackageManager.PERMISSION_GRANTED
// Check if the permission is granted.
if (grantResults.length > 0) && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
// Permission was granted.
...
} else {// Permission was denied...
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 21
License.
Get device
location

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 22
License.
FusedLocationProviderClient

● Use FusedLocationProviderClient
to request last known location
● Usually, last known location is same
as current location

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 23
License.
Get FusedLocationProviderClient
● To get FusedLocationProviderClient:

FusedLocationProviderClient flpClient =
LocationServices.getFusedLocationProviderClient(
context);

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 24
License.
Requesting last known location
● Call FusedLocationProviderClient getLastLocation()
○ Returns Task object representing async task to fetch
Location object
○ Task supplies methods for adding success and failure
listeners
● Retrieve latitude and longitude from Location object

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 25
License.
getLastLocation() success listener
mFusedLocationClient.getLastLocation().addOnSuccessListener(
new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if (location != null) {
mLastLocation = location;
// Get the lat and long.
} else { // Show "no location" }
}
});
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 26
License.
getLastLocation() failure listener
mFusedLocationClient.getLastLocation().addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "onFailure: ", e.printStackTrace());
}
}
);

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 27
License.
Get latitude and longitude
public void onSuccess(Location location) {
if (location != null) {
// Get the lat and long.
lat = location.getLatitude(),
long = location.getLongitude(),
time = location.getTime()));
} else { // no location}

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 28
License.
Geocoding and
reverse
geocoding

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 29
License.
Geocoding and reverse geocoding
● Geocode: Latitude 51.5
Longitude -0.078
Convert human-readable street
address into latitude/longitude
● Reverse geocode:
Convert lat/long into human- Tower Bridge,
Tower Bridge Rd,
readable street address London SE1 2UP
UK

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 30
License.
Use the Geocoder class

● Use Geocoder for geocoding and reverse geocoding


Geocoder geocoder = new Geocoder(context,
Locale.getDefault());
● Methods make network request—don't call on main thread

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 31
License.
Geocoder backend service

● Geocoder requires backend service that are not included in


core Android framework
● Use isPresent() to check if implementation exists
● Geocoder query methods return empty list if no backend
service exists

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 32
License.
Reverse geocoding coordinates

getFromLocation(
double latitude, double longitude, int maxResults)

Returns list of Address objects:

List<Address> addresses = geocoder.getFromLocation(


location.getLatitude(), location.getLongitude(), 1);

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 33
License.
Geocoding address into coordinates
getFromLocationName(
String locationName, int maxResults)

Returns list of Address objects with latitude/longitude coordinates:

List<Address> addresses = geocoder.getFromLocationName(


"731 Market St, San Francisco, CA 94103", 1)
Address firstAddress = addresses.get(0);
double latitude = firstAddress.getLatitude();
double longitude = firstAddress.getLongitude();
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 34
License.
Creating a
LocationRequest
object

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 35
License.
Getting location updates

● Your app can get the last known location.


● It can also ask for regular updates to
track location
● Use LocationRequest to set parameters
for location update requests

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 36
License.
LocationRequest parameters
Set LocationRequest parameters to control location requests
● setInterval():
Sets how frequently your app needs updates
● setFastestInterval():
Sets limit to the update rate to prevent flicker/data overflow
● setPriority():
Sets request priority and sources
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 37
License.
Request priority values
PRIORITY_BALANCED_POWER Precise to within city block (100 meters);
_ACCURACY uses only Wi-Fi and cell network, to
consume less power

PRIORITY_HIGH_ACCURACY Uses GPS if available

PRIORITY_LOW_POWER City-level precision (10 km)

PRIORITY_NO_POWER Updates when triggered by other apps


(zero additional power)

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 38
License.
Create LocationRequest example
private LocationRequest getLocationRequest() {
LocationRequest locationRequest = new LocationRequest();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(
LocationRequest.PRIORITY_HIGH_ACCURACY);
return locationRequest;
}

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 39
License.
Requesting
location
updates

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 40
License.
Requesting location updates
● Use LocationRequest with
FusedLocationProviderClient
● Accuracy of location determined by:
○ Available location providers (network and GPS)
○ Location permission requested
○ Options set in location request

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 41
License.
Steps to start location updates
1. Create LocationRequest object
2. Override LocationCallback.onLocationResult()
3. Use requestLocationUpdates() on
FusedLocationProviderClient to start regular updates

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 42
License.
Steps to start location updates
Use requestLocationUpdates() to start regular updates
● Pass in LocationRequest and LocationCallback
● Location updates are delivered to onLocationResult()

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 43
License.
Using LocationCallback

mLocationCallback = new LocationCallback() {


@Override
public void onLocationResult(
LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
// Update UI with location data
// ...
}
};

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 44
License.
Working with
user settings

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 45
License.
User settings for location services

● Users can control balance between


accuracy and power consumption
● Your app can:
○ Detect device settings
○ Prompt user to change them

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 46
License.
Steps to check device settings
1. Create a LocationSettingsRequest object
2. Create a SettingsClient object
3. Use checkLocationSettings() to see if device settings
match LocationRequest
4. Use OnFailureListener to catch when settings don't
match LocationRequest

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 47
License.
1. Create a LocationSettingsRequest
Create a LocationSettingsRequest object and add one or
more location requests:

LocationSettingsRequest settingsRequest =
new LocationSettingsRequest.Builder()

.addLocationRequest(mLocationRequest).build(); This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 48
License.
2. Create a SettingsClient
Create a SettingsClient object using
LocationServices.getSettingsClient() and pass in the
context:

SettingsClient client =
LocationServices.getSettingsClient(this);

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 49
License.
3. See if device settings match request
● Use checkLocationSettings() to see if device settings
match LocationRequest:
Task<LocationSettingsResponse> task =
client.checkLocationSettings(settingsRequest);
● Returns a Task object

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 50
License.
4. Catch when settings don't match
● Use OnFailureListener to catch when settings don't
match LocationRequest
● Exception passed into onFailure() contains Status
● If settings don't match, then status is
LocationSettingsStatusCodes.RESOLUTION_REQUIRED
● Show dialog to change settings

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 51
License.
Sample code for user dialog
task.addOnFailureListener(this, new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
int statusCode = ((ApiException) e).getStatusCode();
if (statusCode ==
LocationSettingsStatusCodes.RESOLUTION_REQUIRED) {
// Show the user a dialog.
// ...
}
}
});
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 52
License.
Sample code for user dialog (continued)
// Show the user a dialog.
try {
// Call startResolutionForResult(), check
// result in onActivityResult()
ResolvableApiException resolvable =
(ResolvableApiException) e;
resolvable.startResolutionForResult
(MainActivity.this,REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException sendEx) {
// Ignore the error
}
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 53
License.
Handle the user's decision

● Override onActivityResult() in Activity


● Ensure requestCode matches constant in
startResolutionForResult()

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 54
License.
Sample onActivityResult method
@Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == REQUEST_CHECK_SETTINGS) {
if (resultCode == RESULT_CANCELED) {
stopTrackingLocation();
} else if (resultCode == RESULT_OK) {
startTrackingLocation();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
This work is licensed under a Creative
Advanced Android Development Location Commons Attribution 4.0 International 55
License.
What's next?

● Concept chapter: 7.1 Location services


● Practical: 7.1 Using the device location

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 56
License.
END

This work is licensed under a Creative


Advanced Android Development Location Commons Attribution 4.0 International 57
License.

You might also like