1 /* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.location; 18 19 import android.annotation.SystemApi; 20 import android.annotation.TestApi; 21 import android.compat.annotation.UnsupportedAppUsage; 22 import android.os.Build; 23 import android.os.Bundle; 24 import android.os.Parcel; 25 import android.os.Parcelable; 26 import android.os.SystemClock; 27 import android.util.Printer; 28 import android.util.TimeUtils; 29 30 import java.text.DecimalFormat; 31 import java.util.StringTokenizer; 32 33 /** 34 * A data class representing a geographic location. 35 * 36 * <p>A location can consist of a latitude, longitude, timestamp, 37 * and other information such as bearing, altitude and velocity. 38 * 39 * <p>All locations generated by the {@link LocationManager} are 40 * guaranteed to have a valid latitude, longitude, and timestamp 41 * (both UTC time and elapsed real-time since boot), all other 42 * parameters are optional. 43 */ 44 public class Location implements Parcelable { 45 /** 46 * Constant used to specify formatting of a latitude or longitude 47 * in the form "[+-]DDD.DDDDD where D indicates degrees. 48 */ 49 public static final int FORMAT_DEGREES = 0; 50 51 /** 52 * Constant used to specify formatting of a latitude or longitude 53 * in the form "[+-]DDD:MM.MMMMM" where D indicates degrees and 54 * M indicates minutes of arc (1 minute = 1/60th of a degree). 55 */ 56 public static final int FORMAT_MINUTES = 1; 57 58 /** 59 * Constant used to specify formatting of a latitude or longitude 60 * in the form "DDD:MM:SS.SSSSS" where D indicates degrees, M 61 * indicates minutes of arc, and S indicates seconds of arc (1 62 * minute = 1/60th of a degree, 1 second = 1/3600th of a degree). 63 */ 64 public static final int FORMAT_SECONDS = 2; 65 66 /** 67 * Bundle key for a version of the location that has been fed through 68 * LocationFudger. Allows location providers to flag locations as being 69 * safe for use with ACCESS_COARSE_LOCATION permission. 70 * 71 * @hide 72 */ 73 public static final String EXTRA_COARSE_LOCATION = "coarseLocation"; 74 75 /** 76 * Bundle key for a version of the location containing no GPS data. 77 * Allows location providers to flag locations as being safe to 78 * feed to LocationFudger. 79 * 80 * @hide 81 */ 82 public static final String EXTRA_NO_GPS_LOCATION = "noGPSLocation"; 83 84 /** 85 * Bit mask for mFieldsMask indicating the presence of mAltitude. 86 */ 87 private static final int HAS_ALTITUDE_MASK = 1; 88 /** 89 * Bit mask for mFieldsMask indicating the presence of mSpeed. 90 */ 91 private static final int HAS_SPEED_MASK = 2; 92 /** 93 * Bit mask for mFieldsMask indicating the presence of mBearing. 94 */ 95 private static final int HAS_BEARING_MASK = 4; 96 /** 97 * Bit mask for mFieldsMask indicating the presence of mHorizontalAccuracy. 98 */ 99 private static final int HAS_HORIZONTAL_ACCURACY_MASK = 8; 100 /** 101 * Bit mask for mFieldsMask indicating location is from a mock provider. 102 */ 103 private static final int HAS_MOCK_PROVIDER_MASK = 16; 104 /** 105 * Bit mask for mFieldsMask indicating the presence of mVerticalAccuracy. 106 */ 107 private static final int HAS_VERTICAL_ACCURACY_MASK = 32; 108 /** 109 * Bit mask for mFieldsMask indicating the presence of mSpeedAccuracy. 110 */ 111 private static final int HAS_SPEED_ACCURACY_MASK = 64; 112 /** 113 * Bit mask for mFieldsMask indicating the presence of mBearingAccuracy. 114 */ 115 private static final int HAS_BEARING_ACCURACY_MASK = 128; 116 /** 117 * Bit mask for mFieldsMask indicating the presence of mElapsedRealtimeUncertaintyNanos. 118 */ 119 private static final int HAS_ELAPSED_REALTIME_UNCERTAINTY_MASK = 256; 120 121 // Cached data to make bearing/distance computations more efficient for the case 122 // where distanceTo and bearingTo are called in sequence. Assume this typically happens 123 // on the same thread for caching purposes. 124 private static ThreadLocal<BearingDistanceCache> sBearingDistanceCache 125 = new ThreadLocal<BearingDistanceCache>() { 126 @Override 127 protected BearingDistanceCache initialValue() { 128 return new BearingDistanceCache(); 129 } 130 }; 131 132 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023) 133 private String mProvider; 134 private long mTime = 0; 135 @UnsupportedAppUsage 136 private long mElapsedRealtimeNanos = 0; 137 // Estimate of the relative precision of the alignment of this SystemClock 138 // timestamp, with the reported measurements in nanoseconds (68% confidence). 139 private double mElapsedRealtimeUncertaintyNanos = 0.0f; 140 private double mLatitude = 0.0; 141 private double mLongitude = 0.0; 142 private double mAltitude = 0.0f; 143 private float mSpeed = 0.0f; 144 private float mBearing = 0.0f; 145 private float mHorizontalAccuracyMeters = 0.0f; 146 private float mVerticalAccuracyMeters = 0.0f; 147 private float mSpeedAccuracyMetersPerSecond = 0.0f; 148 private float mBearingAccuracyDegrees = 0.0f; 149 150 private Bundle mExtras = null; 151 152 // A bitmask of fields present in this object (see HAS_* constants defined above). 153 private int mFieldsMask = 0; 154 155 /** 156 * Construct a new Location with a named provider. 157 * 158 * <p>By default time, latitude and longitude are 0, and the location 159 * has no bearing, altitude, speed, accuracy or extras. 160 * 161 * @param provider the source that provides the location. It can be of type 162 * {@link LocationManager#GPS_PROVIDER}, {@link LocationManager#NETWORK_PROVIDER}, 163 * or {@link LocationManager#PASSIVE_PROVIDER}. You can also define your own 164 * provider string, in which case an empty string is a valid provider. 165 */ Location(String provider)166 public Location(String provider) { 167 mProvider = provider; 168 } 169 170 /** 171 * Construct a new Location object that is copied from an existing one. 172 */ Location(Location l)173 public Location(Location l) { 174 set(l); 175 } 176 177 /** 178 * Sets the contents of the location to the values from the given location. 179 */ set(Location l)180 public void set(Location l) { 181 mProvider = l.mProvider; 182 mTime = l.mTime; 183 mElapsedRealtimeNanos = l.mElapsedRealtimeNanos; 184 mElapsedRealtimeUncertaintyNanos = l.mElapsedRealtimeUncertaintyNanos; 185 mFieldsMask = l.mFieldsMask; 186 mLatitude = l.mLatitude; 187 mLongitude = l.mLongitude; 188 mAltitude = l.mAltitude; 189 mSpeed = l.mSpeed; 190 mBearing = l.mBearing; 191 mHorizontalAccuracyMeters = l.mHorizontalAccuracyMeters; 192 mVerticalAccuracyMeters = l.mVerticalAccuracyMeters; 193 mSpeedAccuracyMetersPerSecond = l.mSpeedAccuracyMetersPerSecond; 194 mBearingAccuracyDegrees = l.mBearingAccuracyDegrees; 195 mExtras = (l.mExtras == null) ? null : new Bundle(l.mExtras); 196 } 197 198 /** 199 * Clears the contents of the location. 200 */ reset()201 public void reset() { 202 mProvider = null; 203 mTime = 0; 204 mElapsedRealtimeNanos = 0; 205 mElapsedRealtimeUncertaintyNanos = 0.0; 206 mFieldsMask = 0; 207 mLatitude = 0; 208 mLongitude = 0; 209 mAltitude = 0; 210 mSpeed = 0; 211 mBearing = 0; 212 mHorizontalAccuracyMeters = 0; 213 mVerticalAccuracyMeters = 0; 214 mSpeedAccuracyMetersPerSecond = 0; 215 mBearingAccuracyDegrees = 0; 216 mExtras = null; 217 } 218 219 /** 220 * Converts a coordinate to a String representation. The outputType 221 * may be one of FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS. 222 * The coordinate must be a valid double between -180.0 and 180.0. 223 * This conversion is performed in a method that is dependent on the 224 * default locale, and so is not guaranteed to round-trip with 225 * {@link #convert(String)}. 226 * 227 * @throws IllegalArgumentException if coordinate is less than 228 * -180.0, greater than 180.0, or is not a number. 229 * @throws IllegalArgumentException if outputType is not one of 230 * FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS. 231 */ convert(double coordinate, int outputType)232 public static String convert(double coordinate, int outputType) { 233 if (coordinate < -180.0 || coordinate > 180.0 || 234 Double.isNaN(coordinate)) { 235 throw new IllegalArgumentException("coordinate=" + coordinate); 236 } 237 if ((outputType != FORMAT_DEGREES) && 238 (outputType != FORMAT_MINUTES) && 239 (outputType != FORMAT_SECONDS)) { 240 throw new IllegalArgumentException("outputType=" + outputType); 241 } 242 243 StringBuilder sb = new StringBuilder(); 244 245 // Handle negative values 246 if (coordinate < 0) { 247 sb.append('-'); 248 coordinate = -coordinate; 249 } 250 251 DecimalFormat df = new DecimalFormat("###.#####"); 252 if (outputType == FORMAT_MINUTES || outputType == FORMAT_SECONDS) { 253 int degrees = (int) Math.floor(coordinate); 254 sb.append(degrees); 255 sb.append(':'); 256 coordinate -= degrees; 257 coordinate *= 60.0; 258 if (outputType == FORMAT_SECONDS) { 259 int minutes = (int) Math.floor(coordinate); 260 sb.append(minutes); 261 sb.append(':'); 262 coordinate -= minutes; 263 coordinate *= 60.0; 264 } 265 } 266 sb.append(df.format(coordinate)); 267 return sb.toString(); 268 } 269 270 /** 271 * Converts a String in one of the formats described by 272 * FORMAT_DEGREES, FORMAT_MINUTES, or FORMAT_SECONDS into a 273 * double. This conversion is performed in a locale agnostic 274 * method, and so is not guaranteed to round-trip with 275 * {@link #convert(double, int)}. 276 * 277 * @throws NullPointerException if coordinate is null 278 * @throws IllegalArgumentException if the coordinate is not 279 * in one of the valid formats. 280 */ convert(String coordinate)281 public static double convert(String coordinate) { 282 // IllegalArgumentException if bad syntax 283 if (coordinate == null) { 284 throw new NullPointerException("coordinate"); 285 } 286 287 boolean negative = false; 288 if (coordinate.charAt(0) == '-') { 289 coordinate = coordinate.substring(1); 290 negative = true; 291 } 292 293 StringTokenizer st = new StringTokenizer(coordinate, ":"); 294 int tokens = st.countTokens(); 295 if (tokens < 1) { 296 throw new IllegalArgumentException("coordinate=" + coordinate); 297 } 298 try { 299 String degrees = st.nextToken(); 300 double val; 301 if (tokens == 1) { 302 val = Double.parseDouble(degrees); 303 return negative ? -val : val; 304 } 305 306 String minutes = st.nextToken(); 307 int deg = Integer.parseInt(degrees); 308 double min; 309 double sec = 0.0; 310 boolean secPresent = false; 311 312 if (st.hasMoreTokens()) { 313 min = Integer.parseInt(minutes); 314 String seconds = st.nextToken(); 315 sec = Double.parseDouble(seconds); 316 secPresent = true; 317 } else { 318 min = Double.parseDouble(minutes); 319 } 320 321 boolean isNegative180 = negative && (deg == 180) && 322 (min == 0) && (sec == 0); 323 324 // deg must be in [0, 179] except for the case of -180 degrees 325 if ((deg < 0.0) || (deg > 179 && !isNegative180)) { 326 throw new IllegalArgumentException("coordinate=" + coordinate); 327 } 328 329 // min must be in [0, 59] if seconds are present, otherwise [0.0, 60.0) 330 if (min < 0 || min >= 60 || (secPresent && (min > 59))) { 331 throw new IllegalArgumentException("coordinate=" + 332 coordinate); 333 } 334 335 // sec must be in [0.0, 60.0) 336 if (sec < 0 || sec >= 60) { 337 throw new IllegalArgumentException("coordinate=" + 338 coordinate); 339 } 340 341 val = deg*3600.0 + min*60.0 + sec; 342 val /= 3600.0; 343 return negative ? -val : val; 344 } catch (NumberFormatException nfe) { 345 throw new IllegalArgumentException("coordinate=" + coordinate); 346 } 347 } 348 computeDistanceAndBearing(double lat1, double lon1, double lat2, double lon2, BearingDistanceCache results)349 private static void computeDistanceAndBearing(double lat1, double lon1, 350 double lat2, double lon2, BearingDistanceCache results) { 351 // Based on http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf 352 // using the "Inverse Formula" (section 4) 353 354 int MAXITERS = 20; 355 // Convert lat/long to radians 356 lat1 *= Math.PI / 180.0; 357 lat2 *= Math.PI / 180.0; 358 lon1 *= Math.PI / 180.0; 359 lon2 *= Math.PI / 180.0; 360 361 double a = 6378137.0; // WGS84 major axis 362 double b = 6356752.3142; // WGS84 semi-major axis 363 double f = (a - b) / a; 364 double aSqMinusBSqOverBSq = (a * a - b * b) / (b * b); 365 366 double L = lon2 - lon1; 367 double A = 0.0; 368 double U1 = Math.atan((1.0 - f) * Math.tan(lat1)); 369 double U2 = Math.atan((1.0 - f) * Math.tan(lat2)); 370 371 double cosU1 = Math.cos(U1); 372 double cosU2 = Math.cos(U2); 373 double sinU1 = Math.sin(U1); 374 double sinU2 = Math.sin(U2); 375 double cosU1cosU2 = cosU1 * cosU2; 376 double sinU1sinU2 = sinU1 * sinU2; 377 378 double sigma = 0.0; 379 double deltaSigma = 0.0; 380 double cosSqAlpha = 0.0; 381 double cos2SM = 0.0; 382 double cosSigma = 0.0; 383 double sinSigma = 0.0; 384 double cosLambda = 0.0; 385 double sinLambda = 0.0; 386 387 double lambda = L; // initial guess 388 for (int iter = 0; iter < MAXITERS; iter++) { 389 double lambdaOrig = lambda; 390 cosLambda = Math.cos(lambda); 391 sinLambda = Math.sin(lambda); 392 double t1 = cosU2 * sinLambda; 393 double t2 = cosU1 * sinU2 - sinU1 * cosU2 * cosLambda; 394 double sinSqSigma = t1 * t1 + t2 * t2; // (14) 395 sinSigma = Math.sqrt(sinSqSigma); 396 cosSigma = sinU1sinU2 + cosU1cosU2 * cosLambda; // (15) 397 sigma = Math.atan2(sinSigma, cosSigma); // (16) 398 double sinAlpha = (sinSigma == 0) ? 0.0 : 399 cosU1cosU2 * sinLambda / sinSigma; // (17) 400 cosSqAlpha = 1.0 - sinAlpha * sinAlpha; 401 cos2SM = (cosSqAlpha == 0) ? 0.0 : 402 cosSigma - 2.0 * sinU1sinU2 / cosSqAlpha; // (18) 403 404 double uSquared = cosSqAlpha * aSqMinusBSqOverBSq; // defn 405 A = 1 + (uSquared / 16384.0) * // (3) 406 (4096.0 + uSquared * 407 (-768 + uSquared * (320.0 - 175.0 * uSquared))); 408 double B = (uSquared / 1024.0) * // (4) 409 (256.0 + uSquared * 410 (-128.0 + uSquared * (74.0 - 47.0 * uSquared))); 411 double C = (f / 16.0) * 412 cosSqAlpha * 413 (4.0 + f * (4.0 - 3.0 * cosSqAlpha)); // (10) 414 double cos2SMSq = cos2SM * cos2SM; 415 deltaSigma = B * sinSigma * // (6) 416 (cos2SM + (B / 4.0) * 417 (cosSigma * (-1.0 + 2.0 * cos2SMSq) - 418 (B / 6.0) * cos2SM * 419 (-3.0 + 4.0 * sinSigma * sinSigma) * 420 (-3.0 + 4.0 * cos2SMSq))); 421 422 lambda = L + 423 (1.0 - C) * f * sinAlpha * 424 (sigma + C * sinSigma * 425 (cos2SM + C * cosSigma * 426 (-1.0 + 2.0 * cos2SM * cos2SM))); // (11) 427 428 double delta = (lambda - lambdaOrig) / lambda; 429 if (Math.abs(delta) < 1.0e-12) { 430 break; 431 } 432 } 433 434 float distance = (float) (b * A * (sigma - deltaSigma)); 435 results.mDistance = distance; 436 float initialBearing = (float) Math.atan2(cosU2 * sinLambda, 437 cosU1 * sinU2 - sinU1 * cosU2 * cosLambda); 438 initialBearing *= 180.0 / Math.PI; 439 results.mInitialBearing = initialBearing; 440 float finalBearing = (float) Math.atan2(cosU1 * sinLambda, 441 -sinU1 * cosU2 + cosU1 * sinU2 * cosLambda); 442 finalBearing *= 180.0 / Math.PI; 443 results.mFinalBearing = finalBearing; 444 results.mLat1 = lat1; 445 results.mLat2 = lat2; 446 results.mLon1 = lon1; 447 results.mLon2 = lon2; 448 } 449 450 /** 451 * Computes the approximate distance in meters between two 452 * locations, and optionally the initial and final bearings of the 453 * shortest path between them. Distance and bearing are defined using the 454 * WGS84 ellipsoid. 455 * 456 * <p> The computed distance is stored in results[0]. If results has length 457 * 2 or greater, the initial bearing is stored in results[1]. If results has 458 * length 3 or greater, the final bearing is stored in results[2]. 459 * 460 * @param startLatitude the starting latitude 461 * @param startLongitude the starting longitude 462 * @param endLatitude the ending latitude 463 * @param endLongitude the ending longitude 464 * @param results an array of floats to hold the results 465 * 466 * @throws IllegalArgumentException if results is null or has length < 1 467 */ distanceBetween(double startLatitude, double startLongitude, double endLatitude, double endLongitude, float[] results)468 public static void distanceBetween(double startLatitude, double startLongitude, 469 double endLatitude, double endLongitude, float[] results) { 470 if (results == null || results.length < 1) { 471 throw new IllegalArgumentException("results is null or has length < 1"); 472 } 473 BearingDistanceCache cache = sBearingDistanceCache.get(); 474 computeDistanceAndBearing(startLatitude, startLongitude, 475 endLatitude, endLongitude, cache); 476 results[0] = cache.mDistance; 477 if (results.length > 1) { 478 results[1] = cache.mInitialBearing; 479 if (results.length > 2) { 480 results[2] = cache.mFinalBearing; 481 } 482 } 483 } 484 485 /** 486 * Returns the approximate distance in meters between this 487 * location and the given location. Distance is defined using 488 * the WGS84 ellipsoid. 489 * 490 * @param dest the destination location 491 * @return the approximate distance in meters 492 */ distanceTo(Location dest)493 public float distanceTo(Location dest) { 494 BearingDistanceCache cache = sBearingDistanceCache.get(); 495 // See if we already have the result 496 if (mLatitude != cache.mLat1 || mLongitude != cache.mLon1 || 497 dest.mLatitude != cache.mLat2 || dest.mLongitude != cache.mLon2) { 498 computeDistanceAndBearing(mLatitude, mLongitude, 499 dest.mLatitude, dest.mLongitude, cache); 500 } 501 return cache.mDistance; 502 } 503 504 /** 505 * Returns the approximate initial bearing in degrees East of true 506 * North when traveling along the shortest path between this 507 * location and the given location. The shortest path is defined 508 * using the WGS84 ellipsoid. Locations that are (nearly) 509 * antipodal may produce meaningless results. 510 * 511 * @param dest the destination location 512 * @return the initial bearing in degrees 513 */ bearingTo(Location dest)514 public float bearingTo(Location dest) { 515 BearingDistanceCache cache = sBearingDistanceCache.get(); 516 // See if we already have the result 517 if (mLatitude != cache.mLat1 || mLongitude != cache.mLon1 || 518 dest.mLatitude != cache.mLat2 || dest.mLongitude != cache.mLon2) { 519 computeDistanceAndBearing(mLatitude, mLongitude, 520 dest.mLatitude, dest.mLongitude, cache); 521 } 522 return cache.mInitialBearing; 523 } 524 525 /** 526 * Returns the name of the provider that generated this fix. 527 * 528 * @return the provider, or null if it has not been set 529 */ getProvider()530 public String getProvider() { 531 return mProvider; 532 } 533 534 /** 535 * Sets the name of the provider that generated this fix. 536 */ setProvider(String provider)537 public void setProvider(String provider) { 538 mProvider = provider; 539 } 540 541 /** 542 * Return the UTC time of this fix, in milliseconds since January 1, 1970. 543 * 544 * <p>Note that the UTC time on a device is not monotonic: it 545 * can jump forwards or backwards unpredictably. So always use 546 * {@link #getElapsedRealtimeNanos} when calculating time deltas. 547 * 548 * <p>On the other hand, {@link #getTime} is useful for presenting 549 * a human readable time to the user, or for carefully comparing 550 * location fixes across reboot or across devices. 551 * 552 * <p>All locations generated by the {@link LocationManager} 553 * are guaranteed to have a valid UTC time, however remember that 554 * the system time may have changed since the location was generated. 555 * 556 * @return time of fix, in milliseconds since January 1, 1970. 557 */ getTime()558 public long getTime() { 559 return mTime; 560 } 561 562 /** 563 * Set the UTC time of this fix, in milliseconds since January 1, 564 * 1970. 565 * 566 * @param time UTC time of this fix, in milliseconds since January 1, 1970 567 */ setTime(long time)568 public void setTime(long time) { 569 mTime = time; 570 } 571 572 /** 573 * Return the time of this fix, in elapsed real-time since system boot. 574 * 575 * <p>This value can be reliably compared to 576 * {@link android.os.SystemClock#elapsedRealtimeNanos}, 577 * to calculate the age of a fix and to compare Location fixes. This 578 * is reliable because elapsed real-time is guaranteed monotonic for 579 * each system boot and continues to increment even when the system 580 * is in deep sleep (unlike {@link #getTime}. 581 * 582 * <p>All locations generated by the {@link LocationManager} 583 * are guaranteed to have a valid elapsed real-time. 584 * 585 * @return elapsed real-time of fix, in nanoseconds since system boot. 586 */ getElapsedRealtimeNanos()587 public long getElapsedRealtimeNanos() { 588 return mElapsedRealtimeNanos; 589 } 590 591 /** 592 * Set the time of this fix, in elapsed real-time since system boot. 593 * 594 * @param time elapsed real-time of fix, in nanoseconds since system boot. 595 */ setElapsedRealtimeNanos(long time)596 public void setElapsedRealtimeNanos(long time) { 597 mElapsedRealtimeNanos = time; 598 } 599 600 /** 601 * Get estimate of the relative precision of the alignment of the 602 * ElapsedRealtimeNanos timestamp, with the reported measurements in 603 * nanoseconds (68% confidence). 604 * 605 * This means that we have 68% confidence that the true timestamp of the 606 * event is within ElapsedReatimeNanos +/- uncertainty. 607 * 608 * Example : 609 * - getElapsedRealtimeNanos() returns 10000000 610 * - getElapsedRealtimeUncertaintyNanos() returns 1000000 (equivalent to 1millisecond) 611 * This means that the event most likely happened between 9000000 and 11000000. 612 * 613 * @return uncertainty of elapsed real-time of fix, in nanoseconds. 614 */ getElapsedRealtimeUncertaintyNanos()615 public double getElapsedRealtimeUncertaintyNanos() { 616 return mElapsedRealtimeUncertaintyNanos; 617 } 618 619 /** 620 * Set estimate of the relative precision of the alignment of the 621 * ElapsedRealtimeNanos timestamp, with the reported measurements in 622 * nanoseconds (68% confidence). 623 * 624 * @param time uncertainty of the elapsed real-time of fix, in nanoseconds. 625 */ setElapsedRealtimeUncertaintyNanos(double time)626 public void setElapsedRealtimeUncertaintyNanos(double time) { 627 mElapsedRealtimeUncertaintyNanos = time; 628 mFieldsMask |= HAS_ELAPSED_REALTIME_UNCERTAINTY_MASK; 629 } 630 631 /** 632 * True if this location has a elapsed realtime accuracy. 633 */ hasElapsedRealtimeUncertaintyNanos()634 public boolean hasElapsedRealtimeUncertaintyNanos() { 635 return (mFieldsMask & HAS_ELAPSED_REALTIME_UNCERTAINTY_MASK) != 0; 636 } 637 638 639 /** 640 * Get the latitude, in degrees. 641 * 642 * <p>All locations generated by the {@link LocationManager} 643 * will have a valid latitude. 644 */ getLatitude()645 public double getLatitude() { 646 return mLatitude; 647 } 648 649 /** 650 * Set the latitude, in degrees. 651 */ setLatitude(double latitude)652 public void setLatitude(double latitude) { 653 mLatitude = latitude; 654 } 655 656 /** 657 * Get the longitude, in degrees. 658 * 659 * <p>All locations generated by the {@link LocationManager} 660 * will have a valid longitude. 661 */ getLongitude()662 public double getLongitude() { 663 return mLongitude; 664 } 665 666 /** 667 * Set the longitude, in degrees. 668 */ setLongitude(double longitude)669 public void setLongitude(double longitude) { 670 mLongitude = longitude; 671 } 672 673 /** 674 * True if this location has an altitude. 675 */ hasAltitude()676 public boolean hasAltitude() { 677 return (mFieldsMask & HAS_ALTITUDE_MASK) != 0; 678 } 679 680 /** 681 * Get the altitude if available, in meters above the WGS 84 reference 682 * ellipsoid. 683 * 684 * <p>If this location does not have an altitude then 0.0 is returned. 685 */ getAltitude()686 public double getAltitude() { 687 return mAltitude; 688 } 689 690 /** 691 * Set the altitude, in meters above the WGS 84 reference ellipsoid. 692 * 693 * <p>Following this call {@link #hasAltitude} will return true. 694 */ setAltitude(double altitude)695 public void setAltitude(double altitude) { 696 mAltitude = altitude; 697 mFieldsMask |= HAS_ALTITUDE_MASK; 698 } 699 700 /** 701 * Remove the altitude from this location. 702 * 703 * <p>Following this call {@link #hasAltitude} will return false, 704 * and {@link #getAltitude} will return 0.0. 705 * 706 * @deprecated use a new Location object for location updates. 707 */ 708 @Deprecated removeAltitude()709 public void removeAltitude() { 710 mAltitude = 0.0f; 711 mFieldsMask &= ~HAS_ALTITUDE_MASK; 712 } 713 714 /** 715 * True if this location has a speed. 716 */ hasSpeed()717 public boolean hasSpeed() { 718 return (mFieldsMask & HAS_SPEED_MASK) != 0; 719 } 720 721 /** 722 * Get the speed if it is available, in meters/second over ground. 723 * 724 * <p>If this location does not have a speed then 0.0 is returned. 725 */ getSpeed()726 public float getSpeed() { 727 return mSpeed; 728 } 729 730 /** 731 * Set the speed, in meters/second over ground. 732 * 733 * <p>Following this call {@link #hasSpeed} will return true. 734 */ setSpeed(float speed)735 public void setSpeed(float speed) { 736 mSpeed = speed; 737 mFieldsMask |= HAS_SPEED_MASK; 738 } 739 740 /** 741 * Remove the speed from this location. 742 * 743 * <p>Following this call {@link #hasSpeed} will return false, 744 * and {@link #getSpeed} will return 0.0. 745 * 746 * @deprecated use a new Location object for location updates. 747 */ 748 @Deprecated removeSpeed()749 public void removeSpeed() { 750 mSpeed = 0.0f; 751 mFieldsMask &= ~HAS_SPEED_MASK; 752 } 753 754 /** 755 * True if this location has a bearing. 756 */ hasBearing()757 public boolean hasBearing() { 758 return (mFieldsMask & HAS_BEARING_MASK) != 0; 759 } 760 761 /** 762 * Get the bearing, in degrees. 763 * 764 * <p>Bearing is the horizontal direction of travel of this device, 765 * and is not related to the device orientation. It is guaranteed to 766 * be in the range (0.0, 360.0] if the device has a bearing. 767 * 768 * <p>If this location does not have a bearing then 0.0 is returned. 769 */ getBearing()770 public float getBearing() { 771 return mBearing; 772 } 773 774 /** 775 * Set the bearing, in degrees. 776 * 777 * <p>Bearing is the horizontal direction of travel of this device, 778 * and is not related to the device orientation. 779 * 780 * <p>The input will be wrapped into the range (0.0, 360.0]. 781 */ setBearing(float bearing)782 public void setBearing(float bearing) { 783 while (bearing < 0.0f) { 784 bearing += 360.0f; 785 } 786 while (bearing >= 360.0f) { 787 bearing -= 360.0f; 788 } 789 mBearing = bearing; 790 mFieldsMask |= HAS_BEARING_MASK; 791 } 792 793 /** 794 * Remove the bearing from this location. 795 * 796 * <p>Following this call {@link #hasBearing} will return false, 797 * and {@link #getBearing} will return 0.0. 798 * 799 * @deprecated use a new Location object for location updates. 800 */ 801 @Deprecated removeBearing()802 public void removeBearing() { 803 mBearing = 0.0f; 804 mFieldsMask &= ~HAS_BEARING_MASK; 805 } 806 807 /** 808 * True if this location has a horizontal accuracy. 809 * 810 * <p>All locations generated by the {@link LocationManager} have an horizontal accuracy. 811 */ hasAccuracy()812 public boolean hasAccuracy() { 813 return (mFieldsMask & HAS_HORIZONTAL_ACCURACY_MASK) != 0; 814 } 815 816 /** 817 * Get the estimated horizontal accuracy of this location, radial, in meters. 818 * 819 * <p>We define horizontal accuracy as the radius of 68% confidence. In other 820 * words, if you draw a circle centered at this location's 821 * latitude and longitude, and with a radius equal to the accuracy, 822 * then there is a 68% probability that the true location is inside 823 * the circle. 824 * 825 * <p>This accuracy estimation is only concerned with horizontal 826 * accuracy, and does not indicate the accuracy of bearing, 827 * velocity or altitude if those are included in this Location. 828 * 829 * <p>If this location does not have a horizontal accuracy, then 0.0 is returned. 830 * All locations generated by the {@link LocationManager} include horizontal accuracy. 831 */ getAccuracy()832 public float getAccuracy() { 833 return mHorizontalAccuracyMeters; 834 } 835 836 /** 837 * Set the estimated horizontal accuracy of this location, meters. 838 * 839 * <p>See {@link #getAccuracy} for the definition of horizontal accuracy. 840 * 841 * <p>Following this call {@link #hasAccuracy} will return true. 842 */ setAccuracy(float horizontalAccuracy)843 public void setAccuracy(float horizontalAccuracy) { 844 mHorizontalAccuracyMeters = horizontalAccuracy; 845 mFieldsMask |= HAS_HORIZONTAL_ACCURACY_MASK; 846 } 847 848 /** 849 * Remove the horizontal accuracy from this location. 850 * 851 * <p>Following this call {@link #hasAccuracy} will return false, and 852 * {@link #getAccuracy} will return 0.0. 853 * 854 * @deprecated use a new Location object for location updates. 855 */ 856 @Deprecated removeAccuracy()857 public void removeAccuracy() { 858 mHorizontalAccuracyMeters = 0.0f; 859 mFieldsMask &= ~HAS_HORIZONTAL_ACCURACY_MASK; 860 } 861 862 /** 863 * True if this location has a vertical accuracy. 864 */ hasVerticalAccuracy()865 public boolean hasVerticalAccuracy() { 866 return (mFieldsMask & HAS_VERTICAL_ACCURACY_MASK) != 0; 867 } 868 869 /** 870 * Get the estimated vertical accuracy of this location, in meters. 871 * 872 * <p>We define vertical accuracy at 68% confidence. Specifically, as 1-side of the 873 * 2-sided range above and below the estimated altitude reported by {@link #getAltitude()}, 874 * within which there is a 68% probability of finding the true altitude. 875 * 876 * <p>In the case where the underlying distribution is assumed Gaussian normal, this would be 877 * considered 1 standard deviation. 878 * 879 * <p>For example, if {@link #getAltitude()} returns 150, and 880 * {@link #getVerticalAccuracyMeters()} returns 20 then there is a 68% probability 881 * of the true altitude being between 130 and 170 meters. 882 * 883 * <p>If this location does not have a vertical accuracy, then 0.0 is returned. 884 */ getVerticalAccuracyMeters()885 public float getVerticalAccuracyMeters() { 886 return mVerticalAccuracyMeters; 887 } 888 889 /** 890 * Set the estimated vertical accuracy of this location, meters. 891 * 892 * <p>See {@link #getVerticalAccuracyMeters} for the definition of vertical accuracy. 893 * 894 * <p>Following this call {@link #hasVerticalAccuracy} will return true. 895 */ setVerticalAccuracyMeters(float verticalAccuracyMeters)896 public void setVerticalAccuracyMeters(float verticalAccuracyMeters) { 897 mVerticalAccuracyMeters = verticalAccuracyMeters; 898 mFieldsMask |= HAS_VERTICAL_ACCURACY_MASK; 899 } 900 901 /** 902 * Remove the vertical accuracy from this location. 903 * 904 * <p>Following this call {@link #hasVerticalAccuracy} will return false, and 905 * {@link #getVerticalAccuracyMeters} will return 0.0. 906 * 907 * @deprecated use a new Location object for location updates. 908 * @removed 909 */ 910 @Deprecated removeVerticalAccuracy()911 public void removeVerticalAccuracy() { 912 mVerticalAccuracyMeters = 0.0f; 913 mFieldsMask &= ~HAS_VERTICAL_ACCURACY_MASK; 914 } 915 916 /** 917 * True if this location has a speed accuracy. 918 */ hasSpeedAccuracy()919 public boolean hasSpeedAccuracy() { 920 return (mFieldsMask & HAS_SPEED_ACCURACY_MASK) != 0; 921 } 922 923 /** 924 * Get the estimated speed accuracy of this location, in meters per second. 925 * 926 * <p>We define speed accuracy at 68% confidence. Specifically, as 1-side of the 927 * 2-sided range above and below the estimated speed reported by {@link #getSpeed()}, 928 * within which there is a 68% probability of finding the true speed. 929 * 930 * <p>In the case where the underlying 931 * distribution is assumed Gaussian normal, this would be considered 1 standard deviation. 932 * 933 * <p>For example, if {@link #getSpeed()} returns 5, and 934 * {@link #getSpeedAccuracyMetersPerSecond()} returns 1, then there is a 68% probability of 935 * the true speed being between 4 and 6 meters per second. 936 * 937 * <p>Note that the speed and speed accuracy is often better than would be obtained simply from 938 * differencing sequential positions, such as when the Doppler measurements from GNSS satellites 939 * are used. 940 * 941 * <p>If this location does not have a speed accuracy, then 0.0 is returned. 942 */ getSpeedAccuracyMetersPerSecond()943 public float getSpeedAccuracyMetersPerSecond() { 944 return mSpeedAccuracyMetersPerSecond; 945 } 946 947 /** 948 * Set the estimated speed accuracy of this location, meters per second. 949 * 950 * <p>See {@link #getSpeedAccuracyMetersPerSecond} for the definition of speed accuracy. 951 * 952 * <p>Following this call {@link #hasSpeedAccuracy} will return true. 953 */ setSpeedAccuracyMetersPerSecond(float speedAccuracyMeterPerSecond)954 public void setSpeedAccuracyMetersPerSecond(float speedAccuracyMeterPerSecond) { 955 mSpeedAccuracyMetersPerSecond = speedAccuracyMeterPerSecond; 956 mFieldsMask |= HAS_SPEED_ACCURACY_MASK; 957 } 958 959 /** 960 * Remove the speed accuracy from this location. 961 * 962 * <p>Following this call {@link #hasSpeedAccuracy} will return false, and 963 * {@link #getSpeedAccuracyMetersPerSecond} will return 0.0. 964 * 965 * @deprecated use a new Location object for location updates. 966 * @removed 967 */ 968 @Deprecated removeSpeedAccuracy()969 public void removeSpeedAccuracy() { 970 mSpeedAccuracyMetersPerSecond = 0.0f; 971 mFieldsMask &= ~HAS_SPEED_ACCURACY_MASK; 972 } 973 974 /** 975 * True if this location has a bearing accuracy. 976 */ hasBearingAccuracy()977 public boolean hasBearingAccuracy() { 978 return (mFieldsMask & HAS_BEARING_ACCURACY_MASK) != 0; 979 } 980 981 /** 982 * Get the estimated bearing accuracy of this location, in degrees. 983 * 984 * <p>We define bearing accuracy at 68% confidence. Specifically, as 1-side of the 985 * 2-sided range on each side of the estimated bearing reported by {@link #getBearing()}, 986 * within which there is a 68% probability of finding the true bearing. 987 * 988 * <p>In the case where the underlying distribution is assumed Gaussian normal, this would be 989 * considered 1 standard deviation. 990 * 991 * <p>For example, if {@link #getBearing()} returns 60, and 992 * {@link #getBearingAccuracyDegrees()} returns 10, then there is a 68% probability of the 993 * true bearing being between 50 and 70 degrees. 994 * 995 * <p>If this location does not have a bearing accuracy, then 0.0 is returned. 996 */ getBearingAccuracyDegrees()997 public float getBearingAccuracyDegrees() { 998 return mBearingAccuracyDegrees; 999 } 1000 1001 /** 1002 * Set the estimated bearing accuracy of this location, degrees. 1003 * 1004 * <p>See {@link #getBearingAccuracyDegrees} for the definition of bearing accuracy. 1005 * 1006 * <p>Following this call {@link #hasBearingAccuracy} will return true. 1007 */ setBearingAccuracyDegrees(float bearingAccuracyDegrees)1008 public void setBearingAccuracyDegrees(float bearingAccuracyDegrees) { 1009 mBearingAccuracyDegrees = bearingAccuracyDegrees; 1010 mFieldsMask |= HAS_BEARING_ACCURACY_MASK; 1011 } 1012 1013 /** 1014 * Remove the bearing accuracy from this location. 1015 * 1016 * <p>Following this call {@link #hasBearingAccuracy} will return false, and 1017 * {@link #getBearingAccuracyDegrees} will return 0.0. 1018 * 1019 * @deprecated use a new Location object for location updates. 1020 * @removed 1021 */ 1022 @Deprecated removeBearingAccuracy()1023 public void removeBearingAccuracy() { 1024 mBearingAccuracyDegrees = 0.0f; 1025 mFieldsMask &= ~HAS_BEARING_ACCURACY_MASK; 1026 } 1027 1028 /** 1029 * Return true if this Location object is complete. 1030 * 1031 * <p>A location object is currently considered complete if it has 1032 * a valid provider, accuracy, wall-clock time and elapsed real-time. 1033 * 1034 * <p>All locations supplied by the {@link LocationManager} to 1035 * applications must be complete. 1036 * 1037 * @see #makeComplete 1038 * @hide 1039 */ 1040 @SystemApi isComplete()1041 public boolean isComplete() { 1042 if (mProvider == null) return false; 1043 if (!hasAccuracy()) return false; 1044 if (mTime == 0) return false; 1045 if (mElapsedRealtimeNanos == 0) return false; 1046 return true; 1047 } 1048 1049 /** 1050 * Helper to fill incomplete fields. 1051 * 1052 * <p>Used to assist in backwards compatibility with 1053 * Location objects received from applications. 1054 * 1055 * @see #isComplete 1056 * @hide 1057 */ 1058 @TestApi 1059 @SystemApi makeComplete()1060 public void makeComplete() { 1061 if (mProvider == null) mProvider = "?"; 1062 if (!hasAccuracy()) { 1063 mFieldsMask |= HAS_HORIZONTAL_ACCURACY_MASK; 1064 mHorizontalAccuracyMeters = 100.0f; 1065 } 1066 if (mTime == 0) mTime = System.currentTimeMillis(); 1067 if (mElapsedRealtimeNanos == 0) mElapsedRealtimeNanos = SystemClock.elapsedRealtimeNanos(); 1068 } 1069 1070 /** 1071 * Returns additional provider-specific information about the 1072 * location fix as a Bundle. The keys and values are determined 1073 * by the provider. If no additional information is available, 1074 * null is returned. 1075 * 1076 * <p> A number of common key/value pairs are listed 1077 * below. Providers that use any of the keys on this list must 1078 * provide the corresponding value as described below. 1079 * 1080 * <ul> 1081 * <li> satellites - the number of satellites used to derive the fix 1082 * </ul> 1083 */ getExtras()1084 public Bundle getExtras() { 1085 return mExtras; 1086 } 1087 1088 /** 1089 * Sets the extra information associated with this fix to the 1090 * given Bundle. 1091 * 1092 * <p>Note this stores a copy of the given extras, so any changes to extras after calling this 1093 * method won't be reflected in the location bundle. 1094 */ setExtras(Bundle extras)1095 public void setExtras(Bundle extras) { 1096 mExtras = (extras == null) ? null : new Bundle(extras); 1097 } 1098 1099 @Override toString()1100 public String toString() { 1101 StringBuilder s = new StringBuilder(); 1102 s.append("Location["); 1103 s.append(mProvider); 1104 s.append(String.format(" %.6f,%.6f", mLatitude, mLongitude)); 1105 if (hasAccuracy()) s.append(String.format(" hAcc=%.0f", mHorizontalAccuracyMeters)); 1106 else s.append(" hAcc=???"); 1107 if (mTime == 0) { 1108 s.append(" t=?!?"); 1109 } 1110 if (mElapsedRealtimeNanos == 0) { 1111 s.append(" et=?!?"); 1112 } else { 1113 s.append(" et="); 1114 TimeUtils.formatDuration(mElapsedRealtimeNanos / 1000000L, s); 1115 } 1116 if (hasElapsedRealtimeUncertaintyNanos()) { 1117 s.append(" etAcc="); 1118 TimeUtils.formatDuration((long) (mElapsedRealtimeUncertaintyNanos / 1000000), s); 1119 } 1120 if (hasAltitude()) s.append(" alt=").append(mAltitude); 1121 if (hasSpeed()) s.append(" vel=").append(mSpeed); 1122 if (hasBearing()) s.append(" bear=").append(mBearing); 1123 if (hasVerticalAccuracy()) s.append(String.format(" vAcc=%.0f", mVerticalAccuracyMeters)); 1124 else s.append(" vAcc=???"); 1125 if (hasSpeedAccuracy()) s.append(String.format(" sAcc=%.0f", mSpeedAccuracyMetersPerSecond)); 1126 else s.append(" sAcc=???"); 1127 if (hasBearingAccuracy()) s.append(String.format(" bAcc=%.0f", mBearingAccuracyDegrees)); 1128 else s.append(" bAcc=???"); 1129 if (isFromMockProvider()) s.append(" mock"); 1130 1131 if (mExtras != null) { 1132 s.append(" {").append(mExtras).append('}'); 1133 } 1134 s.append(']'); 1135 return s.toString(); 1136 } 1137 dump(Printer pw, String prefix)1138 public void dump(Printer pw, String prefix) { 1139 pw.println(prefix + toString()); 1140 } 1141 1142 public static final @android.annotation.NonNull Parcelable.Creator<Location> CREATOR = 1143 new Parcelable.Creator<Location>() { 1144 @Override 1145 public Location createFromParcel(Parcel in) { 1146 String provider = in.readString(); 1147 Location l = new Location(provider); 1148 l.mTime = in.readLong(); 1149 l.mElapsedRealtimeNanos = in.readLong(); 1150 l.mElapsedRealtimeUncertaintyNanos = in.readDouble(); 1151 l.mFieldsMask = in.readInt(); 1152 l.mLatitude = in.readDouble(); 1153 l.mLongitude = in.readDouble(); 1154 l.mAltitude = in.readDouble(); 1155 l.mSpeed = in.readFloat(); 1156 l.mBearing = in.readFloat(); 1157 l.mHorizontalAccuracyMeters = in.readFloat(); 1158 l.mVerticalAccuracyMeters = in.readFloat(); 1159 l.mSpeedAccuracyMetersPerSecond = in.readFloat(); 1160 l.mBearingAccuracyDegrees = in.readFloat(); 1161 l.mExtras = Bundle.setDefusable(in.readBundle(), true); 1162 return l; 1163 } 1164 1165 @Override 1166 public Location[] newArray(int size) { 1167 return new Location[size]; 1168 } 1169 }; 1170 1171 @Override describeContents()1172 public int describeContents() { 1173 return 0; 1174 } 1175 1176 @Override writeToParcel(Parcel parcel, int flags)1177 public void writeToParcel(Parcel parcel, int flags) { 1178 parcel.writeString(mProvider); 1179 parcel.writeLong(mTime); 1180 parcel.writeLong(mElapsedRealtimeNanos); 1181 parcel.writeDouble(mElapsedRealtimeUncertaintyNanos); 1182 parcel.writeInt(mFieldsMask); 1183 parcel.writeDouble(mLatitude); 1184 parcel.writeDouble(mLongitude); 1185 parcel.writeDouble(mAltitude); 1186 parcel.writeFloat(mSpeed); 1187 parcel.writeFloat(mBearing); 1188 parcel.writeFloat(mHorizontalAccuracyMeters); 1189 parcel.writeFloat(mVerticalAccuracyMeters); 1190 parcel.writeFloat(mSpeedAccuracyMetersPerSecond); 1191 parcel.writeFloat(mBearingAccuracyDegrees); 1192 parcel.writeBundle(mExtras); 1193 } 1194 1195 /** 1196 * Returns one of the optional extra {@link Location}s that can be attached 1197 * to this Location. 1198 * 1199 * @param key the key associated with the desired extra Location 1200 * @return the extra Location, or null if unavailable 1201 * @hide 1202 */ getExtraLocation(String key)1203 public Location getExtraLocation(String key) { 1204 if (mExtras != null) { 1205 Parcelable value = mExtras.getParcelable(key); 1206 if (value instanceof Location) { 1207 return (Location) value; 1208 } 1209 } 1210 return null; 1211 } 1212 1213 /** 1214 * Attaches an extra {@link Location} to this Location. 1215 * 1216 * @param key the key associated with the Location extra 1217 * @param value the Location to attach 1218 * @hide 1219 */ 1220 @UnsupportedAppUsage setExtraLocation(String key, Location value)1221 public void setExtraLocation(String key, Location value) { 1222 if (mExtras == null) { 1223 mExtras = new Bundle(); 1224 } 1225 mExtras.putParcelable(key, value); 1226 } 1227 1228 /** 1229 * Returns true if the Location came from a mock provider. 1230 * 1231 * @return true if this Location came from a mock provider, false otherwise 1232 */ isFromMockProvider()1233 public boolean isFromMockProvider() { 1234 return (mFieldsMask & HAS_MOCK_PROVIDER_MASK) != 0; 1235 } 1236 1237 /** 1238 * Flag this Location as having come from a mock provider or not. 1239 * 1240 * @param isFromMockProvider true if this Location came from a mock provider, false otherwise 1241 * @hide 1242 */ 1243 @SystemApi setIsFromMockProvider(boolean isFromMockProvider)1244 public void setIsFromMockProvider(boolean isFromMockProvider) { 1245 if (isFromMockProvider) { 1246 mFieldsMask |= HAS_MOCK_PROVIDER_MASK; 1247 } else { 1248 mFieldsMask &= ~HAS_MOCK_PROVIDER_MASK; 1249 } 1250 } 1251 1252 /** 1253 * Caches data used to compute distance and bearing (so successive calls to {@link #distanceTo} 1254 * and {@link #bearingTo} don't duplicate work. 1255 */ 1256 private static class BearingDistanceCache { 1257 private double mLat1 = 0.0; 1258 private double mLon1 = 0.0; 1259 private double mLat2 = 0.0; 1260 private double mLon2 = 0.0; 1261 private float mDistance = 0.0f; 1262 private float mInitialBearing = 0.0f; 1263 private float mFinalBearing = 0.0f; 1264 } 1265 } 1266