FileDocCategorySizeDatePackage
LocationRequest.javaAPI DocAndroid 5.1 API24600Thu Mar 12 22:22:30 GMT 2015android.location

LocationRequest

public final class LocationRequest extends Object implements android.os.Parcelable
A data object that contains quality of service parameters for requests to the {@link LocationManager}.

LocationRequest objects are used to request a quality of service for location updates from the Location Manager.

For example, if your application wants high accuracy location it should create a location request with {@link #setQuality} set to {@link #ACCURACY_FINE} or {@link #POWER_HIGH}, and it should set {@link #setInterval} to less than one second. This would be appropriate for mapping applications that are showing your location in real-time.

At the other extreme, if you want negligible power impact, but to still receive location updates when available, then use {@link #setQuality} with {@link #POWER_NONE}. With this request your application will not trigger (and therefore will not receive any power blame) any location updates, but will receive locations triggered by other applications. This would be appropriate for applications that have no firm requirement for location, but can take advantage when available.

In between these two extremes is a very common use-case, where applications definitely want to receive updates at a specified interval, and can receive them faster when available, but still want a low power impact. These applications should consider {@link #POWER_LOW} combined with a faster {@link #setFastestInterval} (such as 1 minute) and a slower {@link #setInterval} (such as 60 minutes). They will only be assigned power blame for the interval set by {@link #setInterval}, but can still receive locations triggered by other applications at a rate up to {@link #setFastestInterval}. This style of request is appropriate for many location aware applications, including background usage. Do be careful to also throttle {@link #setFastestInterval} if you perform heavy-weight work after receiving an update - such as using the network.

Activities should strongly consider removing all location request when entering the background (for example at {@link android.app.Activity#onPause}), or at least swap the request to a larger interval and lower quality. Future version of the location manager may automatically perform background throttling on behalf of applications.

Applications cannot specify the exact location sources that are used by Android's Fusion Engine. In fact, the system may have multiple location sources (providers) running and may fuse the results from several sources into a single Location object.

Location requests from applications with {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} and not {@link android.Manifest.permission#ACCESS_FINE_LOCATION} will be automatically throttled to a slower interval, and the location object will be obfuscated to only show a coarse level of accuracy.

All location requests are considered hints, and you may receive locations that are more accurate, less accurate, and slower than requested.

hide

Fields Summary
public static final int
ACCURACY_FINE
Used with {@link #setQuality} to request the most accurate locations available.

This may be up to 1 meter accuracy, although this is implementation dependent.

public static final int
ACCURACY_BLOCK
Used with {@link #setQuality} to request "block" level accuracy.

Block level accuracy is considered to be about 100 meter accuracy, although this is implementation dependent. Using a coarse accuracy such as this often consumes less power.

public static final int
ACCURACY_CITY
Used with {@link #setQuality} to request "city" level accuracy.

City level accuracy is considered to be about 10km accuracy, although this is implementation dependent. Using a coarse accuracy such as this often consumes less power.

public static final int
POWER_NONE
Used with {@link #setQuality} to require no direct power impact (passive locations).

This location request will not trigger any active location requests, but will receive locations triggered by other applications. Your application will not receive any direct power blame for location work.

public static final int
POWER_LOW
Used with {@link #setQuality} to request low power impact.

This location request will avoid high power location work where possible.

public static final int
POWER_HIGH
Used with {@link #setQuality} to allow high power consumption for location.

This location request will allow high power location work.

private static final double
FASTEST_INTERVAL_FACTOR
By default, mFastestInterval = FASTEST_INTERVAL_MULTIPLE * mInterval
private int
mQuality
private long
mInterval
private long
mFastestInterval
private boolean
mExplicitFastestInterval
private long
mExpireAt
private int
mNumUpdates
private float
mSmallestDisplacement
private android.os.WorkSource
mWorkSource
private boolean
mHideFromAppOps
private String
mProvider
public static final Parcelable.Creator
CREATOR
Constructors Summary
public LocationRequest()

hide

 
public LocationRequest(LocationRequest src)

hide

        mQuality = src.mQuality;
        mInterval = src.mInterval;
        mFastestInterval = src.mFastestInterval;
        mExplicitFastestInterval = src.mExplicitFastestInterval;
        mExpireAt = src.mExpireAt;
        mNumUpdates = src.mNumUpdates;
        mSmallestDisplacement = src.mSmallestDisplacement;
        mProvider = src.mProvider;
        mWorkSource = src.mWorkSource;
        mHideFromAppOps = src.mHideFromAppOps;
    
Methods Summary
private static voidcheckDisplacement(float meters)

        if (meters < 0.0f) {
            throw new IllegalArgumentException("invalid displacement: " + meters);
        }
    
private static voidcheckInterval(long millis)

        if (millis < 0) {
            throw new IllegalArgumentException("invalid interval: " + millis);
        }
    
private static voidcheckProvider(java.lang.String name)

        if (name == null) {
            throw new IllegalArgumentException("invalid provider: " + name);
        }
    
private static voidcheckQuality(int quality)

        switch (quality) {
            case ACCURACY_FINE:
            case ACCURACY_BLOCK:
            case ACCURACY_CITY:
            case POWER_NONE:
            case POWER_LOW:
            case POWER_HIGH:
                break;
            default:
                throw new IllegalArgumentException("invalid quality: " + quality);
        }
    
public static android.location.LocationRequestcreate()
Create a location request with default parameters.

Default parameters are for a low power, slowly updated location. It can then be adjusted as required by the applications before passing to the {@link LocationManager}

return
a new location request

  // for deprecated APIs that explicitly request a provider

                                               
        
        LocationRequest request = new LocationRequest();
        return request;
    
public static android.location.LocationRequestcreateFromDeprecatedCriteria(Criteria criteria, long minTime, float minDistance, boolean singleShot)

hide

        if (minTime < 0) minTime = 0;
        if (minDistance < 0) minDistance = 0;

        int quality;
        switch (criteria.getAccuracy()) {
            case Criteria.ACCURACY_COARSE:
                quality = ACCURACY_BLOCK;
                break;
            case Criteria.ACCURACY_FINE:
                quality = ACCURACY_FINE;
                break;
            default: {
                switch (criteria.getPowerRequirement()) {
                    case Criteria.POWER_HIGH:
                        quality = POWER_HIGH;
                    default:
                        quality = POWER_LOW;
                }
            }
        }

        LocationRequest request = new LocationRequest()
            .setQuality(quality)
            .setInterval(minTime)
            .setFastestInterval(minTime)
            .setSmallestDisplacement(minDistance);
        if (singleShot) request.setNumUpdates(1);
        return request;
    
public static android.location.LocationRequestcreateFromDeprecatedProvider(java.lang.String provider, long minTime, float minDistance, boolean singleShot)

hide

        if (minTime < 0) minTime = 0;
        if (minDistance < 0) minDistance = 0;

        int quality;
        if (LocationManager.PASSIVE_PROVIDER.equals(provider)) {
            quality = POWER_NONE;
        } else if (LocationManager.GPS_PROVIDER.equals(provider)) {
            quality = ACCURACY_FINE;
        } else {
            quality = POWER_LOW;
        }

        LocationRequest request = new LocationRequest()
            .setProvider(provider)
            .setQuality(quality)
            .setInterval(minTime)
            .setFastestInterval(minTime)
            .setSmallestDisplacement(minDistance);
        if (singleShot) request.setNumUpdates(1);
        return request;
    
public voiddecrementNumUpdates()

hide

        if (mNumUpdates != Integer.MAX_VALUE) {
            mNumUpdates--;
        }
        if (mNumUpdates < 0) {
            mNumUpdates = 0;
        }
    
public intdescribeContents()


    
       
        return 0;
    
public longgetExpireAt()
Get the request expiration time, in milliseconds since boot.

This value can be compared to {@link SystemClock#elapsedRealtime} to determine the time until expiration.

return
expiration time of request, in milliseconds since boot including suspend

        return mExpireAt;
    
public longgetFastestInterval()
Get the fastest interval of this request, in milliseconds.

The system will never provide location updates faster than the minimum of {@link #getFastestInterval} and {@link #getInterval}.

return
fastest interval in milliseconds, exact

        return mFastestInterval;
    
public booleangetHideFromAppOps()

hide

        return mHideFromAppOps;
    
public longgetInterval()
Get the desired interval of this request, in milliseconds.

return
desired interval in milliseconds, inexact

        return mInterval;
    
public intgetNumUpdates()
Get the number of updates requested.

By default this is {@link Integer#MAX_VALUE}, which indicates that locations are updated until the request is explicitly removed.

return
number of updates

        return mNumUpdates;
    
public java.lang.StringgetProvider()

hide

        return mProvider;
    
public intgetQuality()
Get the quality of the request.

return
an accuracy or power constant

        return mQuality;
    
public floatgetSmallestDisplacement()

hide

        return mSmallestDisplacement;
    
public android.os.WorkSourcegetWorkSource()

hide

        return mWorkSource;
    
public static java.lang.StringqualityToString(int quality)

hide

        switch (quality) {
            case ACCURACY_FINE:
                return "ACCURACY_FINE";
            case ACCURACY_BLOCK:
                return "ACCURACY_BLOCK";
            case ACCURACY_CITY:
                return "ACCURACY_CITY";
            case POWER_NONE:
                return "POWER_NONE";
            case POWER_LOW:
                return "POWER_LOW";
            case POWER_HIGH:
                return "POWER_HIGH";
            default:
                return "???";
        }
    
public android.location.LocationRequestsetExpireAt(long millis)
Set the request expiration time, in millisecond since boot.

This expiration time uses the same time base as {@link SystemClock#elapsedRealtime}.

The location manager will automatically stop updates after the request expires.

The duration includes suspend time. Values before {@link SystemClock#elapsedRealtime} are allowed, but indicate that the request has already expired.

param
millis expiration time of request, in milliseconds since boot including suspend
return
the same object, so that setters can be chained

        mExpireAt = millis;
        if (mExpireAt < 0) mExpireAt = 0;
        return this;
    
public android.location.LocationRequestsetExpireIn(long millis)
Set the duration of this request, in milliseconds.

The duration begins immediately (and not when the request is passed to the location manager), so call this method again if the request is re-used at a later time.

The location manager will automatically stop updates after the request expires.

The duration includes suspend time. Values less than 0 are allowed, but indicate that the request has already expired.

param
millis duration of request in milliseconds
return
the same object, so that setters can be chained

        long elapsedRealtime = SystemClock.elapsedRealtime();

        // Check for > Long.MAX_VALUE overflow (elapsedRealtime > 0):
        if (millis > Long.MAX_VALUE - elapsedRealtime) {
          mExpireAt = Long.MAX_VALUE;
        } else {
          mExpireAt = millis + elapsedRealtime;
        }

        if (mExpireAt < 0) mExpireAt = 0;
        return this;
    
public android.location.LocationRequestsetFastestInterval(long millis)
Explicitly set the fastest interval for location updates, in milliseconds.

This controls the fastest rate at which your application will receive location updates, which might be faster than {@link #setInterval} in some situations (for example, if other applications are triggering location updates).

This allows your application to passively acquire locations at a rate faster than it actively acquires locations, saving power.

Unlike {@link #setInterval}, this parameter is exact. Your application will never receive updates faster than this value.

If you don't call this method, a fastest interval will be selected for you. It will be a value faster than your active interval ({@link #setInterval}).

An interval of 0 is allowed, but not recommended, since location updates may be extremely fast on future implementations.

If {@link #setFastestInterval} is set slower than {@link #setInterval}, then your effective fastest interval is {@link #setInterval}.

param
millis fastest interval for updates in milliseconds, exact
throws
InvalidArgumentException if the interval is less than zero
return
the same object, so that setters can be chained

        checkInterval(millis);
        mExplicitFastestInterval = true;
        mFastestInterval = millis;
        return this;
    
public voidsetHideFromAppOps(boolean hideFromAppOps)
Sets whether or not this location request should be hidden from AppOps.

Hiding a location request from AppOps will remove user visibility in the UI as to this request's existence. It does not affect power blaming in the Battery page.

No permissions are required to make this call, however the LocationManager will throw a SecurityException when requesting location updates if the caller doesn't have the {@link android.Manifest.permission#UPDATE_APP_OPS_STATS} permission.

param
hideFromAppOps If true AppOps won't keep track of this location request.
see
android.app.AppOpsManager
hide

        mHideFromAppOps = hideFromAppOps;
    
public android.location.LocationRequestsetInterval(long millis)
Set the desired interval for active location updates, in milliseconds.

The location manager will actively try to obtain location updates for your application at this interval, so it has a direct influence on the amount of power used by your application. Choose your interval wisely.

This interval is inexact. You may not receive updates at all (if no location sources are available), or you may receive them slower than requested. You may also receive them faster than requested (if other applications are requesting location at a faster interval). The fastest rate that that you will receive updates can be controlled with {@link #setFastestInterval}.

Applications with only the coarse location permission may have their interval silently throttled.

An interval of 0 is allowed, but not recommended, since location updates may be extremely fast on future implementations.

{@link #setQuality} and {@link #setInterval} are the most important parameters on a location request.

param
millis desired interval in millisecond, inexact
throws
InvalidArgumentException if the interval is less than zero
return
the same object, so that setters can be chained

        checkInterval(millis);
        mInterval = millis;
        if (!mExplicitFastestInterval) {
            mFastestInterval = (long)(mInterval / FASTEST_INTERVAL_FACTOR);
        }
        return this;
    
public android.location.LocationRequestsetNumUpdates(int numUpdates)
Set the number of location updates.

By default locations are continuously updated until the request is explicitly removed, however you can optionally request a set number of updates. For example, if your application only needs a single fresh location, then call this method with a value of 1 before passing the request to the location manager.

param
numUpdates the number of location updates requested
throws
InvalidArgumentException if numUpdates is 0 or less
return
the same object, so that setters can be chained

        if (numUpdates <= 0) throw new IllegalArgumentException("invalid numUpdates: " + numUpdates);
        mNumUpdates = numUpdates;
        return this;
    
public android.location.LocationRequestsetProvider(java.lang.String provider)

hide

        checkProvider(provider);
        mProvider = provider;
        return this;
    
public android.location.LocationRequestsetQuality(int quality)
Set the quality of the request.

Use with a accuracy constant such as {@link #ACCURACY_FINE}, or a power constant such as {@link #POWER_LOW}. You cannot request both and accuracy and power, only one or the other can be specified. The system will then maximize accuracy or minimize power as appropriate.

The quality of the request is a strong hint to the system for which location sources to use. For example, {@link #ACCURACY_FINE} is more likely to use GPS, and {@link #POWER_LOW} is more likely to use WIFI & Cell tower positioning, but it also depends on many other factors (such as which sources are available) and is implementation dependent.

{@link #setQuality} and {@link #setInterval} are the most important parameters on a location request.

param
quality an accuracy or power constant
throws
InvalidArgumentException if the quality constant is not valid
return
the same object, so that setters can be chained

        checkQuality(quality);
        mQuality = quality;
        return this;
    
public android.location.LocationRequestsetSmallestDisplacement(float meters)

hide

        checkDisplacement(meters);
        mSmallestDisplacement = meters;
        return this;
    
public voidsetWorkSource(android.os.WorkSource workSource)
Sets the WorkSource to use for power blaming of this location request.

No permissions are required to make this call, however the LocationManager will throw a SecurityException when requesting location updates if the caller doesn't have the {@link android.Manifest.permission#UPDATE_DEVICE_STATS} permission.

param
workSource WorkSource defining power blame for this location request.
hide

        mWorkSource = workSource;
    
public java.lang.StringtoString()

        StringBuilder s = new StringBuilder();
        s.append("Request[").append(qualityToString(mQuality));
        if (mProvider != null) s.append(' ").append(mProvider);
        if (mQuality != POWER_NONE) {
            s.append(" requested=");
            TimeUtils.formatDuration(mInterval, s);
        }
        s.append(" fastest=");
        TimeUtils.formatDuration(mFastestInterval, s);
        if (mExpireAt != Long.MAX_VALUE) {
            long expireIn = mExpireAt - SystemClock.elapsedRealtime();
            s.append(" expireIn=");
            TimeUtils.formatDuration(expireIn, s);
        }
        if (mNumUpdates != Integer.MAX_VALUE){
            s.append(" num=").append(mNumUpdates);
        }
        s.append(']");
        return s.toString();
    
public voidwriteToParcel(android.os.Parcel parcel, int flags)

        parcel.writeInt(mQuality);
        parcel.writeLong(mFastestInterval);
        parcel.writeLong(mInterval);
        parcel.writeLong(mExpireAt);
        parcel.writeInt(mNumUpdates);
        parcel.writeFloat(mSmallestDisplacement);
        parcel.writeInt(mHideFromAppOps ? 1 : 0);
        parcel.writeString(mProvider);
        parcel.writeParcelable(mWorkSource, 0);