LocationManager.java revision 2291ca47c763d9c292865ada1450d3a094918882
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 17package android.location; 18 19import android.app.PendingIntent; 20import android.content.Context; 21import android.content.Intent; 22import android.os.Build; 23import android.os.Bundle; 24import android.os.Looper; 25import android.os.RemoteException; 26import android.os.Handler; 27import android.os.Message; 28import android.util.Log; 29 30 31import java.util.ArrayList; 32import java.util.HashMap; 33import java.util.List; 34 35import com.android.internal.location.ProviderProperties; 36 37/** 38 * This class provides access to the system location services. These 39 * services allow applications to obtain periodic updates of the 40 * device's geographical location, or to fire an application-specified 41 * {@link Intent} when the device enters the proximity of a given 42 * geographical location. 43 * 44 * <p>You do not 45 * instantiate this class directly; instead, retrieve it through 46 * {@link android.content.Context#getSystemService 47 * Context.getSystemService(Context.LOCATION_SERVICE)}. 48 * 49 * <p>At API version 17 the Location API's were simplified. 50 * Previously applications would need to explicitly enumerate, select, and 51 * track Location Providers (such as GPS or Network). 52 * This has been replaced by the concept of 53 * <em>Fused Location</em>. Now applications just specify the quality of service 54 * required for location updates (using the new {@link LocationRequest} class), 55 * and the system will fuse results from individual location providers 56 * as necessary before returning the result to the application. 57 * 58 * <p>As a result of this change, the {@link LocationProvider} and 59 * {@link Criteria} classes have been deprecated, in favor of 60 * {@link LocationRequest}. Furthermore, all Location Manager 61 * methods involving Criteria or explicitly named Providers have 62 * been deprecated, in favor of new variants that use 63 * {@link LocationRequest}. 64 * 65 * <p>A single {@link LocationRequest} object can trigger the use 66 * of all providers (including GPS, Network, and the passive) provider 67 * as necessary. This should result in a lot less work for your application. You 68 * no longer need to track the status and availability of each 69 * location provider. Just set the quality of locations required 70 * in {@link LocationRequest}, and let the system manage the rest. 71 * 72 * <p class="note">Unless noted, all Location API methods require 73 * the {@link android.Manifest.permission#ACCESS_COARSE_LOCATION} or 74 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permissions. 75 * If your application only has the coarse permission then it will not have 76 * access to the GPS or passive location providers. Other providers will still 77 * return location results, but the update rate will be throttled and the exact 78 * location will be obfuscated to a coarse level of accuracy. 79 */ 80public class LocationManager { 81 private static final String TAG = "LocationManager"; 82 83 private final Context mContext; 84 private final ILocationManager mService; 85 private final HashMap<GpsStatus.Listener, GpsStatusListenerTransport> mGpsStatusListeners = 86 new HashMap<GpsStatus.Listener, GpsStatusListenerTransport>(); 87 private final HashMap<GpsStatus.NmeaListener, GpsStatusListenerTransport> mNmeaListeners = 88 new HashMap<GpsStatus.NmeaListener, GpsStatusListenerTransport>(); 89 private final GpsStatus mGpsStatus = new GpsStatus(); 90 91 /** 92 * Name of the network location provider. 93 * <p>This provider determines location based on 94 * availability of cell tower and WiFi access points. Results are retrieved 95 * by means of a network lookup. 96 * 97 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 98 */ 99 @Deprecated 100 public static final String NETWORK_PROVIDER = "network"; 101 102 /** 103 * Name of the GPS location provider. 104 * 105 * <p>This provider determines location using 106 * satellites. Depending on conditions, this provider may take a while to return 107 * a location fix. Requires the permission 108 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION}. 109 * 110 * <p> The extras Bundle for the GPS location provider can contain the 111 * following key/value pairs: 112 * <ul> 113 * <li> satellites - the number of satellites used to derive the fix 114 * </ul> 115 * 116 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 117 */ 118 @Deprecated 119 public static final String GPS_PROVIDER = "gps"; 120 121 /** 122 * A special location provider for receiving locations without actually initiating 123 * a location fix. 124 * 125 * <p>This provider can be used to passively receive location updates 126 * when other applications or services request them without actually requesting 127 * the locations yourself. This provider will return locations generated by other 128 * providers. You can query the {@link Location#getProvider()} method to determine 129 * the origin of the location update. Requires the permission 130 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION}, although if the GPS is 131 * not enabled this provider might only return coarse fixes. 132 * 133 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 134 */ 135 @Deprecated 136 public static final String PASSIVE_PROVIDER = "passive"; 137 138 /** 139 * Name of the Fused location provider. 140 * 141 * <p>This provider combines inputs for all possible location sources 142 * to provide the best possible Location fix. It is implicitly 143 * used for all API's that involve the {@link LocationRequest} 144 * object. 145 * 146 * @hide 147 */ 148 public static final String FUSED_PROVIDER = "fused"; 149 150 /** 151 * Key used for the Bundle extra holding a boolean indicating whether 152 * a proximity alert is entering (true) or exiting (false).. 153 */ 154 public static final String KEY_PROXIMITY_ENTERING = "entering"; 155 156 /** 157 * Key used for a Bundle extra holding an Integer status value 158 * when a status change is broadcast using a PendingIntent. 159 * 160 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 161 */ 162 @Deprecated 163 public static final String KEY_STATUS_CHANGED = "status"; 164 165 /** 166 * Key used for a Bundle extra holding an Boolean status value 167 * when a provider enabled/disabled event is broadcast using a PendingIntent. 168 * 169 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 170 */ 171 @Deprecated 172 public static final String KEY_PROVIDER_ENABLED = "providerEnabled"; 173 174 /** 175 * Key used for a Bundle extra holding a Location value 176 * when a location change is broadcast using a PendingIntent. 177 */ 178 public static final String KEY_LOCATION_CHANGED = "location"; 179 180 /** 181 * Broadcast intent action indicating that the GPS has either been 182 * enabled or disabled. An intent extra provides this state as a boolean, 183 * where {@code true} means enabled. 184 * @see #EXTRA_GPS_ENABLED 185 * 186 * @hide 187 */ 188 public static final String GPS_ENABLED_CHANGE_ACTION = 189 "android.location.GPS_ENABLED_CHANGE"; 190 191 /** 192 * Broadcast intent action when the configured location providers 193 * change. 194 * 195 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 196 */ 197 @Deprecated 198 public static final String PROVIDERS_CHANGED_ACTION = 199 "android.location.PROVIDERS_CHANGED"; 200 201 /** 202 * Broadcast intent action indicating that the GPS has either started or 203 * stopped receiving GPS fixes. An intent extra provides this state as a 204 * boolean, where {@code true} means that the GPS is actively receiving fixes. 205 * @see #EXTRA_GPS_ENABLED 206 * 207 * @hide 208 */ 209 public static final String GPS_FIX_CHANGE_ACTION = 210 "android.location.GPS_FIX_CHANGE"; 211 212 /** 213 * The lookup key for a boolean that indicates whether GPS is enabled or 214 * disabled. {@code true} means GPS is enabled. Retrieve it with 215 * {@link android.content.Intent#getBooleanExtra(String,boolean)}. 216 * 217 * @hide 218 */ 219 public static final String EXTRA_GPS_ENABLED = "enabled"; 220 221 // Map from LocationListeners to their associated ListenerTransport objects 222 private HashMap<LocationListener,ListenerTransport> mListeners = 223 new HashMap<LocationListener,ListenerTransport>(); 224 225 private class ListenerTransport extends ILocationListener.Stub { 226 private static final int TYPE_LOCATION_CHANGED = 1; 227 private static final int TYPE_STATUS_CHANGED = 2; 228 private static final int TYPE_PROVIDER_ENABLED = 3; 229 private static final int TYPE_PROVIDER_DISABLED = 4; 230 231 private LocationListener mListener; 232 private final Handler mListenerHandler; 233 234 ListenerTransport(LocationListener listener, Looper looper) { 235 mListener = listener; 236 237 if (looper == null) { 238 mListenerHandler = new Handler() { 239 @Override 240 public void handleMessage(Message msg) { 241 _handleMessage(msg); 242 } 243 }; 244 } else { 245 mListenerHandler = new Handler(looper) { 246 @Override 247 public void handleMessage(Message msg) { 248 _handleMessage(msg); 249 } 250 }; 251 } 252 } 253 254 @Override 255 public void onLocationChanged(Location location) { 256 Message msg = Message.obtain(); 257 msg.what = TYPE_LOCATION_CHANGED; 258 msg.obj = location; 259 mListenerHandler.sendMessage(msg); 260 } 261 262 @Override 263 public void onStatusChanged(String provider, int status, Bundle extras) { 264 Message msg = Message.obtain(); 265 msg.what = TYPE_STATUS_CHANGED; 266 Bundle b = new Bundle(); 267 b.putString("provider", provider); 268 b.putInt("status", status); 269 if (extras != null) { 270 b.putBundle("extras", extras); 271 } 272 msg.obj = b; 273 mListenerHandler.sendMessage(msg); 274 } 275 276 @Override 277 public void onProviderEnabled(String provider) { 278 Message msg = Message.obtain(); 279 msg.what = TYPE_PROVIDER_ENABLED; 280 msg.obj = provider; 281 mListenerHandler.sendMessage(msg); 282 } 283 284 @Override 285 public void onProviderDisabled(String provider) { 286 Message msg = Message.obtain(); 287 msg.what = TYPE_PROVIDER_DISABLED; 288 msg.obj = provider; 289 mListenerHandler.sendMessage(msg); 290 } 291 292 private void _handleMessage(Message msg) { 293 switch (msg.what) { 294 case TYPE_LOCATION_CHANGED: 295 Location location = new Location((Location) msg.obj); 296 mListener.onLocationChanged(location); 297 break; 298 case TYPE_STATUS_CHANGED: 299 Bundle b = (Bundle) msg.obj; 300 String provider = b.getString("provider"); 301 int status = b.getInt("status"); 302 Bundle extras = b.getBundle("extras"); 303 mListener.onStatusChanged(provider, status, extras); 304 break; 305 case TYPE_PROVIDER_ENABLED: 306 mListener.onProviderEnabled((String) msg.obj); 307 break; 308 case TYPE_PROVIDER_DISABLED: 309 mListener.onProviderDisabled((String) msg.obj); 310 break; 311 } 312 try { 313 mService.locationCallbackFinished(this); 314 } catch (RemoteException e) { 315 Log.e(TAG, "locationCallbackFinished: RemoteException", e); 316 } 317 } 318 } 319 320 /** 321 * @hide - hide this constructor because it has a parameter 322 * of type ILocationManager, which is a system private class. The 323 * right way to create an instance of this class is using the 324 * factory Context.getSystemService. 325 */ 326 public LocationManager(Context context, ILocationManager service) { 327 mService = service; 328 mContext = context; 329 } 330 331 private LocationProvider createProvider(String name, ProviderProperties properties) { 332 return new LocationProvider(name, properties); 333 } 334 335 /** 336 * Returns a list of the names of all known location providers. 337 * <p>All providers are returned, including ones that are not permitted to 338 * be accessed by the calling activity or are currently disabled. 339 * 340 * @return list of Strings containing names of the provider 341 * 342 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 343 */ 344 @Deprecated 345 public List<String> getAllProviders() { 346 try { 347 return mService.getAllProviders(); 348 } catch (RemoteException e) { 349 Log.e(TAG, "RemoteException", e); 350 } 351 return null; 352 } 353 354 /** 355 * Returns a list of the names of location providers. 356 * 357 * @param enabledOnly if true then only the providers which are currently 358 * enabled are returned. 359 * @return list of Strings containing names of the providers 360 * 361 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 362 */ 363 @Deprecated 364 public List<String> getProviders(boolean enabledOnly) { 365 try { 366 return mService.getProviders(null, enabledOnly); 367 } catch (RemoteException e) { 368 Log.e(TAG, "RemoteException", e); 369 } 370 return null; 371 } 372 373 /** 374 * Returns the information associated with the location provider of the 375 * given name, or null if no provider exists by that name. 376 * 377 * @param name the provider name 378 * @return a LocationProvider, or null 379 * 380 * @throws IllegalArgumentException if name is null or does not exist 381 * @throws SecurityException if the caller is not permitted to access the 382 * given provider. 383 * 384 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 385 */ 386 @Deprecated 387 public LocationProvider getProvider(String name) { 388 checkProvider(name); 389 try { 390 ProviderProperties properties = mService.getProviderProperties(name); 391 if (properties == null) { 392 return null; 393 } 394 return createProvider(name, properties); 395 } catch (RemoteException e) { 396 Log.e(TAG, "RemoteException", e); 397 } 398 return null; 399 } 400 401 /** 402 * Returns a list of the names of LocationProviders that satisfy the given 403 * criteria, or null if none do. Only providers that are permitted to be 404 * accessed by the calling activity will be returned. 405 * 406 * @param criteria the criteria that the returned providers must match 407 * @param enabledOnly if true then only the providers which are currently 408 * enabled are returned. 409 * @return list of Strings containing names of the providers 410 * 411 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 412 */ 413 @Deprecated 414 public List<String> getProviders(Criteria criteria, boolean enabledOnly) { 415 checkCriteria(criteria); 416 try { 417 return mService.getProviders(criteria, enabledOnly); 418 } catch (RemoteException e) { 419 Log.e(TAG, "RemoteException", e); 420 } 421 return null; 422 } 423 424 /** 425 * Returns the name of the provider that best meets the given criteria. Only providers 426 * that are permitted to be accessed by the calling activity will be 427 * returned. If several providers meet the criteria, the one with the best 428 * accuracy is returned. If no provider meets the criteria, 429 * the criteria are loosened in the following sequence: 430 * 431 * <ul> 432 * <li> power requirement 433 * <li> accuracy 434 * <li> bearing 435 * <li> speed 436 * <li> altitude 437 * </ul> 438 * 439 * <p> Note that the requirement on monetary cost is not removed 440 * in this process. 441 * 442 * @param criteria the criteria that need to be matched 443 * @param enabledOnly if true then only a provider that is currently enabled is returned 444 * @return name of the provider that best matches the requirements 445 * 446 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 447 */ 448 @Deprecated 449 public String getBestProvider(Criteria criteria, boolean enabledOnly) { 450 checkCriteria(criteria); 451 try { 452 return mService.getBestProvider(criteria, enabledOnly); 453 } catch (RemoteException e) { 454 Log.e(TAG, "RemoteException", e); 455 } 456 return null; 457 } 458 459 /** 460 * Register for location updates using the named provider, and a 461 * pending intent. 462 * 463 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 464 * for more detail on how to use this (deprecated) method. 465 * 466 * @param provider the name of the provider with which to register 467 * @param minTime minimum time interval between location updates, in milliseconds 468 * @param minDistance minimum distance between location updates, in meters 469 * @param listener a {@link LocationListener} whose 470 * {@link LocationListener#onLocationChanged} method will be called for 471 * each location update 472 * 473 * @throws IllegalArgumentException if provider is null or doesn't exist 474 * on this device 475 * @throws IllegalArgumentException if listener is null 476 * @throws RuntimeException if the calling thread has no Looper 477 * @throws SecurityException if no suitable permission is present 478 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 479 */ 480 @Deprecated 481 public void requestLocationUpdates(String provider, long minTime, float minDistance, 482 LocationListener listener) { 483 checkProvider(provider); 484 checkListener(listener); 485 486 LocationRequest request = LocationRequest.createFromDeprecatedProvider( 487 provider, minTime, minDistance, false); 488 requestLocationUpdates(request, listener, null, null); 489 } 490 491 /** 492 * Register for location updates using the named provider, and a callback on 493 * the specified looper thread. 494 * 495 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 496 * for more detail on how to use this (deprecated) method. 497 * 498 * @param provider the name of the provider with which to register 499 * @param minTime minimum time interval between location updates, in milliseconds 500 * @param minDistance minimum distance between location updates, in meters 501 * @param listener a {@link LocationListener} whose 502 * {@link LocationListener#onLocationChanged} method will be called for 503 * each location update 504 * @param looper a Looper object whose message queue will be used to 505 * implement the callback mechanism, or null to make callbacks on the calling 506 * thread 507 * 508 * @throws IllegalArgumentException if provider is null or doesn't exist 509 * @throws IllegalArgumentException if listener is null 510 * @throws SecurityException if no suitable permission is present 511 * 512 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 513 */ 514 @Deprecated 515 public void requestLocationUpdates(String provider, long minTime, float minDistance, 516 LocationListener listener, Looper looper) { 517 checkProvider(provider); 518 checkListener(listener); 519 520 LocationRequest request = LocationRequest.createFromDeprecatedProvider( 521 provider, minTime, minDistance, false); 522 requestLocationUpdates(request, listener, looper, null); 523 } 524 525 /** 526 * Register for location updates using a Criteria, and a callback 527 * on the specified looper thread. 528 * 529 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 530 * for more detail on how to use this (deprecated) method. 531 * 532 * @param minTime minimum time interval between location updates, in milliseconds 533 * @param minDistance minimum distance between location updates, in meters 534 * @param criteria contains parameters for the location manager to choose the 535 * appropriate provider and parameters to compute the location 536 * @param listener a {@link LocationListener} whose 537 * {@link LocationListener#onLocationChanged} method will be called for 538 * each location update 539 * @param looper a Looper object whose message queue will be used to 540 * implement the callback mechanism, or null to make callbacks on the calling 541 * thread 542 * 543 * @throws IllegalArgumentException if criteria is null 544 * @throws IllegalArgumentException if listener is null 545 * @throws SecurityException if no suitable permission is present 546 * 547 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 548 */ 549 @Deprecated 550 public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria, 551 LocationListener listener, Looper looper) { 552 checkCriteria(criteria); 553 checkListener(listener); 554 555 LocationRequest request = LocationRequest.createFromDeprecatedCriteria( 556 criteria, minTime, minDistance, false); 557 requestLocationUpdates(request, listener, looper, null); 558 } 559 560 /** 561 * Register for location updates using the named provider, and a 562 * pending intent. 563 * 564 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 565 * for more detail on how to use this (deprecated) method. 566 * 567 * @param provider the name of the provider with which to register 568 * @param minTime minimum time interval between location updates, in milliseconds 569 * @param minDistance minimum distance between location updates, in meters 570 * @param intent a {@link PendingIntent} to be sent for each location update 571 * 572 * @throws IllegalArgumentException if provider is null or doesn't exist 573 * on this device 574 * @throws IllegalArgumentException if intent is null 575 * @throws SecurityException if no suitable permission is present 576 * 577 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 578 */ 579 @Deprecated 580 public void requestLocationUpdates(String provider, long minTime, float minDistance, 581 PendingIntent intent) { 582 checkProvider(provider); 583 checkPendingIntent(intent); 584 585 LocationRequest request = LocationRequest.createFromDeprecatedProvider( 586 provider, minTime, minDistance, false); 587 requestLocationUpdates(request, null, null, intent); 588 } 589 590 /** 591 * Register for location updates using a Criteria and pending intent. 592 * 593 * <p>The <code>requestLocationUpdates()</code> and 594 * <code>requestSingleUpdate()</code> methods involving 595 * an explicit String provider or {@link Criteria} are deprecated. 596 * 597 * <p>They register the current activity to be updated 598 * periodically by the named provider, or by the provider matching 599 * the specified {@link Criteria}, with location and status updates. 600 * 601 * <p> It may take a while to receive the first location update. If 602 * an immediate location is required, applications may use the 603 * {@link #getLastKnownLocation(String)} method. 604 * 605 * <p> Location updates are received either by {@link LocationListener} 606 * callbacks, or by broadcast intents to a supplied {@link PendingIntent}. 607 * 608 * <p> If the caller supplied a pending intent, then location updates 609 * are sent with a key of {@link #KEY_LOCATION_CHANGED} and a 610 * {@link android.location.Location} value. 611 * 612 * <p> The location update interval can be controlled using the minTime parameter. 613 * The elapsed time between location updates will never be less than 614 * minTime, although it can be more depending on the Location Provider 615 * implementation and the update interval requested by other applications. 616 * 617 * <p> Choosing a sensible value for minTime is important to conserve 618 * battery life. Each location update requires power from 619 * GPS, WIFI, Cell and other radios. Select a minTime value as high as 620 * possible while still providing a reasonable user experience. 621 * If your application is not in the foreground and showing 622 * location to the user then your application should avoid using an active 623 * provider (such as {@link #NETWORK_PROVIDER} or {@link #GPS_PROVIDER}), 624 * but if you insist then select a minTime of 5 * 60 * 1000 (5 minutes) 625 * or greater. If your application is in the foreground and showing 626 * location to the user then it is appropriate to select a faster 627 * update interval. 628 * 629 * <p> The minDistance parameter can also be used to control the 630 * frequency of location updates. If it is greater than 0 then the 631 * location provider will only send your application an update when 632 * the location has changed by at least minDistance meters, AND 633 * at least minTime milliseconds have passed. However it is more 634 * difficult for location providers to save power using the minDistance 635 * parameter, so minTime should be the primary tool to conserving battery 636 * life. 637 * 638 * <p> If your application wants to passively observe location 639 * updates triggered by other applications, but not consume 640 * any additional power otherwise, then use the {@link #PASSIVE_PROVIDER} 641 * This provider does not actively turn on or modify active location 642 * providers, so you do not need to be as careful about minTime and 643 * minDistance. However if your application performs heavy work 644 * on a location update (such as network activity) then you should 645 * select non-zero values for minTime and/or minDistance to rate-limit 646 * your update frequency in the case another application enables a 647 * location provider with extremely fast updates. 648 * 649 * <p>In case the provider is disabled by the user, updates will stop, 650 * and a provider availability update will be sent. 651 * As soon as the provider is enabled again, 652 * location updates will immediately resume and a provider availability 653 * update sent. Providers can also send status updates, at any time, 654 * with extra's specific to the provider. If a callback was supplied 655 * then status and availability updates are via 656 * {@link LocationListener#onProviderDisabled}, 657 * {@link LocationListener#onProviderEnabled} or 658 * {@link LocationListener#onStatusChanged}. Alternately, if a 659 * pending intent was supplied then status and availability updates 660 * are broadcast intents with extra keys of 661 * {@link #KEY_PROVIDER_ENABLED} or {@link #KEY_STATUS_CHANGED}. 662 * 663 * <p> If a {@link LocationListener} is used but with no Looper specified 664 * then the calling thread must already 665 * be a {@link android.os.Looper} thread such as the main thread of the 666 * calling Activity. If a Looper is specified with a {@link LocationListener} 667 * then callbacks are made on the supplied Looper thread. 668 * 669 * <p class="note"> Prior to Jellybean, the minTime parameter was 670 * only a hint, and some location provider implementations ignored it. 671 * From Jellybean and onwards it is mandatory for Android compatible 672 * devices to observe both the minTime and minDistance parameters. 673 * 674 * @param minTime minimum time interval between location updates, in milliseconds 675 * @param minDistance minimum distance between location updates, in meters 676 * @param criteria contains parameters for the location manager to choose the 677 * appropriate provider and parameters to compute the location 678 * @param intent a {@link PendingIntent} to be sent for each location update 679 * 680 * @throws IllegalArgumentException if criteria is null 681 * @throws IllegalArgumentException if intent is null 682 * @throws SecurityException if no suitable permission is present 683 * 684 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 685 */ 686 @Deprecated 687 public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria, 688 PendingIntent intent) { 689 checkCriteria(criteria); 690 checkPendingIntent(intent); 691 692 LocationRequest request = LocationRequest.createFromDeprecatedCriteria( 693 criteria, minTime, minDistance, false); 694 requestLocationUpdates(request, null, null, intent); 695 } 696 697 /** 698 * Register for a single location update using the named provider and 699 * a callback. 700 * 701 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 702 * for more detail on how to use this (deprecated) method. 703 * 704 * @param provider the name of the provider with which to register 705 * @param listener a {@link LocationListener} whose 706 * {@link LocationListener#onLocationChanged} method will be called when 707 * the location update is available 708 * @param looper a Looper object whose message queue will be used to 709 * implement the callback mechanism, or null to make callbacks on the calling 710 * thread 711 * 712 * @throws IllegalArgumentException if provider is null or doesn't exist 713 * @throws IllegalArgumentException if listener is null 714 * @throws SecurityException if no suitable permission is present 715 * 716 * @deprecated Use {@link LocationRequest#setNumUpdates} instead 717 */ 718 @Deprecated 719 public void requestSingleUpdate(String provider, LocationListener listener, Looper looper) { 720 checkProvider(provider); 721 checkListener(listener); 722 723 LocationRequest request = LocationRequest.createFromDeprecatedProvider( 724 provider, 0, 0, true); 725 requestLocationUpdates(request, listener, looper, null); 726 } 727 728 /** 729 * Register for a single location update using a Criteria and 730 * a callback. 731 * 732 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 733 * for more detail on how to use this (deprecated) method. 734 * 735 * @param criteria contains parameters for the location manager to choose the 736 * appropriate provider and parameters to compute the location 737 * @param listener a {@link LocationListener} whose 738 * {@link LocationListener#onLocationChanged} method will be called when 739 * the location update is available 740 * @param looper a Looper object whose message queue will be used to 741 * implement the callback mechanism, or null to make callbacks on the calling 742 * thread 743 * 744 * @throws IllegalArgumentException if criteria is null 745 * @throws IllegalArgumentException if listener is null 746 * @throws SecurityException if no suitable permission is present 747 * 748 * @deprecated Use {@link LocationRequest#setNumUpdates} instead 749 */ 750 @Deprecated 751 public void requestSingleUpdate(Criteria criteria, LocationListener listener, Looper looper) { 752 checkCriteria(criteria); 753 checkListener(listener); 754 755 LocationRequest request = LocationRequest.createFromDeprecatedCriteria( 756 criteria, 0, 0, true); 757 requestLocationUpdates(request, listener, looper, null); 758 } 759 760 /** 761 * Register for a single location update using a named provider and pending intent. 762 * 763 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 764 * for more detail on how to use this (deprecated) method. 765 * 766 * @param provider the name of the provider with which to register 767 * @param intent a {@link PendingIntent} to be sent for the location update 768 * 769 * @throws IllegalArgumentException if provider is null or doesn't exist 770 * @throws IllegalArgumentException if intent is null 771 * @throws SecurityException if no suitable permission is present 772 * 773 * @deprecated Use {@link LocationRequest#setNumUpdates} instead 774 */ 775 @Deprecated 776 public void requestSingleUpdate(String provider, PendingIntent intent) { 777 checkProvider(provider); 778 checkPendingIntent(intent); 779 780 LocationRequest request = LocationRequest.createFromDeprecatedProvider( 781 provider, 0, 0, true); 782 requestLocationUpdates(request, null, null, intent); 783 } 784 785 /** 786 * Register for a single location update using a Criteria and pending intent. 787 * 788 * <p>See {@link #requestLocationUpdates(long, float, Criteria, PendingIntent)} 789 * for more detail on how to use this (deprecated) method. 790 * 791 * @param criteria contains parameters for the location manager to choose the 792 * appropriate provider and parameters to compute the location 793 * @param intent a {@link PendingIntent} to be sent for the location update 794 * 795 * @throws IllegalArgumentException if provider is null or doesn't exist 796 * @throws IllegalArgumentException if intent is null 797 * @throws SecurityException if no suitable permission is present 798 * 799 * @deprecated Use {@link LocationRequest#setNumUpdates} instead 800 */ 801 @Deprecated 802 public void requestSingleUpdate(Criteria criteria, PendingIntent intent) { 803 checkCriteria(criteria); 804 checkPendingIntent(intent); 805 806 LocationRequest request = LocationRequest.createFromDeprecatedCriteria( 807 criteria, 0, 0, true); 808 requestLocationUpdates(request, null, null, intent); 809 } 810 811 /** 812 * Register for fused location updates using a LocationRequest and callback. 813 * 814 * <p>The system will automatically select and enable the best providers 815 * to compute a location for your application. It may use only passive 816 * locations, or just a single location source, or it may fuse together 817 * multiple location sources in order to produce the best possible 818 * result, depending on the quality of service requested in the 819 * {@link LocationRequest}. 820 * 821 * <p>LocationRequest can be null, in which case the system will choose 822 * default, low power parameters for location updates. You will occasionally 823 * receive location updates as available, without a major power impact on the 824 * system. If your application just needs an occasional location update 825 * without any strict demands, then pass a null LocationRequest. 826 * 827 * <p>Only one LocationRequest can be registered for each unique callback 828 * or pending intent. So a subsequent request with the same callback or 829 * pending intent will over-write the previous LocationRequest. 830 * 831 * <p> If a pending intent is supplied then location updates 832 * are sent with a key of {@link #KEY_LOCATION_CHANGED} and a 833 * {@link android.location.Location} value. If a callback is supplied 834 * then location updates are made using the 835 * {@link LocationListener#onLocationChanged} callback, on the specified 836 * Looper thread. If a {@link LocationListener} is used 837 * but with a null Looper then the calling thread must already 838 * be a {@link android.os.Looper} thread (such as the main thread) and 839 * callbacks will occur on this thread. 840 * 841 * <p> Provider status updates and availability updates are deprecated 842 * because the system is performing provider fusion on the applications 843 * behalf. So {@link LocationListener#onProviderDisabled}, 844 * {@link LocationListener#onProviderEnabled}, {@link LocationListener#onStatusChanged} 845 * will not be called, and intents with extra keys of 846 * {@link #KEY_PROVIDER_ENABLED} or {@link #KEY_STATUS_CHANGED} will not 847 * be received. 848 * 849 * <p> To unregister for Location updates, use: {@link #removeUpdates(LocationListener)}. 850 * 851 * @param request quality of service required, null for default low power 852 * @param listener a {@link LocationListener} whose 853 * {@link LocationListener#onLocationChanged} method will be called when 854 * the location update is available 855 * @param looper a Looper object whose message queue will be used to 856 * implement the callback mechanism, or null to make callbacks on the calling 857 * thread 858 * 859 * @throws IllegalArgumentException if listener is null 860 * @throws SecurityException if no suitable permission is present 861 */ 862 public void requestLocationUpdates(LocationRequest request, LocationListener listener, 863 Looper looper) { 864 checkListener(listener); 865 requestLocationUpdates(request, listener, looper, null); 866 } 867 868 869 /** 870 * Register for fused location updates using a LocationRequest and a pending intent. 871 * 872 * <p> To unregister for Location updates, use: {@link #removeUpdates(PendingIntent)}. 873 * 874 * <p> See {@link #requestLocationUpdates(LocationRequest, LocationListener, Looper)} 875 * for more detail. 876 * 877 * @param request quality of service required, null for default low power 878 * @param intent a {@link PendingIntent} to be sent for the location update 879 * 880 * @throws IllegalArgumentException if intent is null 881 * @throws SecurityException if no suitable permission is present 882 */ 883 public void requestLocationUpdates(LocationRequest request, PendingIntent intent) { 884 checkPendingIntent(intent); 885 requestLocationUpdates(request, null, null, intent); 886 } 887 888 private ListenerTransport wrapListener(LocationListener listener, Looper looper) { 889 if (listener == null) return null; 890 synchronized (mListeners) { 891 ListenerTransport transport = mListeners.get(listener); 892 if (transport == null) { 893 transport = new ListenerTransport(listener, looper); 894 } 895 mListeners.put(listener, transport); 896 return transport; 897 } 898 } 899 900 private void requestLocationUpdates(LocationRequest request, LocationListener listener, 901 Looper looper, PendingIntent intent) { 902 903 String packageName = mContext.getPackageName(); 904 905 // wrap the listener class 906 ListenerTransport transport = wrapListener(listener, looper); 907 908 try { 909 mService.requestLocationUpdates(request, transport, intent, packageName); 910 } catch (RemoteException e) { 911 Log.e(TAG, "RemoteException", e); 912 } 913 } 914 915 /** 916 * Removes all location updates for the specified LocationListener. 917 * 918 * <p>Following this call, updates will no longer 919 * occur for this listener. 920 * 921 * @param listener listener object that no longer needs location updates 922 * @throws IllegalArgumentException if listener is null 923 */ 924 public void removeUpdates(LocationListener listener) { 925 checkListener(listener); 926 String packageName = mContext.getPackageName(); 927 928 ListenerTransport transport; 929 synchronized (mListeners) { 930 transport = mListeners.remove(listener); 931 } 932 if (transport == null) return; 933 934 try { 935 mService.removeUpdates(transport, null, packageName); 936 } catch (RemoteException e) { 937 Log.e(TAG, "RemoteException", e); 938 } 939 } 940 941 /** 942 * Removes all location updates for the specified pending intent. 943 * 944 * <p>Following this call, updates will no longer for this pending intent. 945 * 946 * @param intent pending intent object that no longer needs location updates 947 * @throws IllegalArgumentException if intent is null 948 */ 949 public void removeUpdates(PendingIntent intent) { 950 checkPendingIntent(intent); 951 String packageName = mContext.getPackageName(); 952 953 try { 954 mService.removeUpdates(null, intent, packageName); 955 } catch (RemoteException e) { 956 Log.e(TAG, "RemoteException", e); 957 } 958 } 959 960 /** 961 * Set a proximity alert for the location given by the position 962 * (latitude, longitude) and the given radius. 963 * 964 * <p> When the device 965 * detects that it has entered or exited the area surrounding the 966 * location, the given PendingIntent will be used to create an Intent 967 * to be fired. 968 * 969 * <p> The fired Intent will have a boolean extra added with key 970 * {@link #KEY_PROXIMITY_ENTERING}. If the value is true, the device is 971 * entering the proximity region; if false, it is exiting. 972 * 973 * <p> Due to the approximate nature of position estimation, if the 974 * device passes through the given area briefly, it is possible 975 * that no Intent will be fired. Similarly, an Intent could be 976 * fired if the device passes very close to the given area but 977 * does not actually enter it. 978 * 979 * <p> After the number of milliseconds given by the expiration 980 * parameter, the location manager will delete this proximity 981 * alert and no longer monitor it. A value of -1 indicates that 982 * there should be no expiration time. 983 * 984 * <p> Internally, this method uses both {@link #NETWORK_PROVIDER} 985 * and {@link #GPS_PROVIDER}. 986 * 987 * <p>Before API version 17, this method could be used with 988 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} or 989 * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}. 990 * From API version 17 and onwards, this method requires 991 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission. 992 * 993 * @param latitude the latitude of the central point of the 994 * alert region 995 * @param longitude the longitude of the central point of the 996 * alert region 997 * @param radius the radius of the central point of the 998 * alert region, in meters 999 * @param expiration time for this proximity alert, in milliseconds, 1000 * or -1 to indicate no expiration 1001 * @param intent a PendingIntent that will be used to generate an Intent to 1002 * fire when entry to or exit from the alert region is detected 1003 * 1004 * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 1005 * permission is not present 1006 * 1007 * @deprecated Use {@link LocationRequest} and {@link Geofence} instead 1008 */ 1009 @Deprecated 1010 public void addProximityAlert(double latitude, double longitude, float radius, long expiration, 1011 PendingIntent intent) { 1012 checkPendingIntent(intent); 1013 if (expiration < 0) expiration = Long.MAX_VALUE; 1014 1015 Geofence fence = Geofence.createCircle(latitude, longitude, radius); 1016 LocationRequest request = new LocationRequest().setExpireIn(expiration); 1017 try { 1018 mService.requestGeofence(request, fence, intent, mContext.getPackageName()); 1019 } catch (RemoteException e) { 1020 Log.e(TAG, "RemoteException", e); 1021 } 1022 } 1023 1024 /** 1025 * Add a geofence with the specified LocationRequest quality of service. 1026 * 1027 * <p> When the device 1028 * detects that it has entered or exited the area surrounding the 1029 * location, the given PendingIntent will be used to create an Intent 1030 * to be fired. 1031 * 1032 * <p> The fired Intent will have a boolean extra added with key 1033 * {@link #KEY_PROXIMITY_ENTERING}. If the value is true, the device is 1034 * entering the proximity region; if false, it is exiting. 1035 * 1036 * <p> The geofence engine fuses results from all location providers to 1037 * provide the best balance between accuracy and power. Applications 1038 * can choose the quality of service required using the 1039 * {@link LocationRequest} object. If it is null then a default, 1040 * low power geo-fencing implementation is used. It is possible to cross 1041 * a geo-fence without notification, but the system will do its best 1042 * to detect, using {@link LocationRequest} as a hint to trade-off 1043 * accuracy and power. 1044 * 1045 * <p> The power required by the geofence engine can depend on many factors, 1046 * such as quality and interval requested in {@link LocationRequest}, 1047 * distance to nearest geofence and current device velocity. 1048 * 1049 * @param request quality of service required, null for default low power 1050 * @param fence a geographical description of the geofence area 1051 * @param intent pending intent to receive geofence updates 1052 * 1053 * @throws IllegalArgumentException if fence is null 1054 * @throws IllegalArgumentException if intent is null 1055 * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 1056 * permission is not present 1057 */ 1058 public void addGeofence(LocationRequest request, Geofence fence, PendingIntent intent) { 1059 checkPendingIntent(intent); 1060 checkGeofence(fence); 1061 1062 try { 1063 mService.requestGeofence(request, fence, intent, mContext.getPackageName()); 1064 } catch (RemoteException e) { 1065 Log.e(TAG, "RemoteException", e); 1066 } 1067 } 1068 1069 /** 1070 * Removes the proximity alert with the given PendingIntent. 1071 * 1072 * <p>Before API version 17, this method could be used with 1073 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} or 1074 * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}. 1075 * From API version 17 and onwards, this method requires 1076 * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission. 1077 * 1078 * @param intent the PendingIntent that no longer needs to be notified of 1079 * proximity alerts 1080 * 1081 * @throws IllegalArgumentException if intent is null 1082 * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 1083 * permission is not present 1084 * 1085 * @deprecated Use {@link LocationRequest} and {@link Geofence} instead 1086 */ 1087 @Deprecated 1088 public void removeProximityAlert(PendingIntent intent) { 1089 checkPendingIntent(intent); 1090 String packageName = mContext.getPackageName(); 1091 1092 try { 1093 mService.removeGeofence(null, intent, packageName); 1094 } catch (RemoteException e) { 1095 Log.e(TAG, "RemoteException", e); 1096 } 1097 } 1098 1099 /** 1100 * Remove a single geofence. 1101 * 1102 * <p>This removes only the specified geofence associated with the 1103 * specified pending intent. All other geofences remain unchanged. 1104 * 1105 * @param fence a geofence previously passed to {@link #addGeofence} 1106 * @param intent a pending intent previously passed to {@link #addGeofence} 1107 * 1108 * @throws IllegalArgumentException if fence is null 1109 * @throws IllegalArgumentException if intent is null 1110 * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 1111 * permission is not present 1112 */ 1113 public void removeGeofence(Geofence fence, PendingIntent intent) { 1114 checkPendingIntent(intent); 1115 checkGeofence(fence); 1116 String packageName = mContext.getPackageName(); 1117 1118 try { 1119 mService.removeGeofence(fence, intent, packageName); 1120 } catch (RemoteException e) { 1121 Log.e(TAG, "RemoteException", e); 1122 } 1123 } 1124 1125 /** 1126 * Remove all geofences registered to the specified pending intent. 1127 * 1128 * @param intent a pending intent previously passed to {@link #addGeofence} 1129 * 1130 * @throws IllegalArgumentException if intent is null 1131 * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION} 1132 * permission is not present 1133 */ 1134 public void removeAllGeofences(PendingIntent intent) { 1135 checkPendingIntent(intent); 1136 String packageName = mContext.getPackageName(); 1137 1138 try { 1139 mService.removeGeofence(null, intent, packageName); 1140 } catch (RemoteException e) { 1141 Log.e(TAG, "RemoteException", e); 1142 } 1143 } 1144 1145 /** 1146 * Returns the current enabled/disabled status of the given provider. 1147 * 1148 * <p>If the user has enabled this provider in the Settings menu, true 1149 * is returned otherwise false is returned 1150 * 1151 * @param provider the name of the provider 1152 * @return true if the provider is enabled 1153 * 1154 * @throws IllegalArgumentException if provider is null 1155 * @throws SecurityException if no suitable permission is present 1156 * 1157 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 1158 */ 1159 @Deprecated 1160 public boolean isProviderEnabled(String provider) { 1161 checkProvider(provider); 1162 1163 try { 1164 return mService.isProviderEnabled(provider); 1165 } catch (RemoteException e) { 1166 Log.e(TAG, "RemoteException", e); 1167 return false; 1168 } 1169 } 1170 1171 /** 1172 * Get the last known location. 1173 * 1174 * <p>This location could be very old so use 1175 * {@link Location#getElapsedRealtimeNanos} to calculate its age. It can 1176 * also return null if no previous location is available. 1177 * 1178 * <p>Always returns immediately. 1179 * 1180 * @return The last known location, or null if not available 1181 * @throws SecurityException if no suitable permission is present 1182 */ 1183 public Location getLastLocation() { 1184 String packageName = mContext.getPackageName(); 1185 1186 try { 1187 return mService.getLastLocation(null, packageName); 1188 } catch (RemoteException e) { 1189 Log.e(TAG, "RemoteException", e); 1190 return null; 1191 } 1192 } 1193 1194 /** 1195 * Returns a Location indicating the data from the last known 1196 * location fix obtained from the given provider. 1197 * 1198 * <p> This can be done 1199 * without starting the provider. Note that this location could 1200 * be out-of-date, for example if the device was turned off and 1201 * moved to another location. 1202 * 1203 * <p> If the provider is currently disabled, null is returned. 1204 * 1205 * @param provider the name of the provider 1206 * @return the last known location for the provider, or null 1207 * 1208 * @throws SecurityException if no suitable permission is present 1209 * @throws IllegalArgumentException if provider is null or doesn't exist 1210 * 1211 * @deprecated Use {@link #getLastLocation} instead 1212 */ 1213 @Deprecated 1214 public Location getLastKnownLocation(String provider) { 1215 checkProvider(provider); 1216 String packageName = mContext.getPackageName(); 1217 LocationRequest request = LocationRequest.createFromDeprecatedProvider( 1218 provider, 0, 0, true); 1219 1220 try { 1221 return mService.getLastLocation(request, packageName); 1222 } catch (RemoteException e) { 1223 Log.e(TAG, "RemoteException", e); 1224 return null; 1225 } 1226 } 1227 1228 // --- Mock provider support --- 1229 // TODO: It would be fantastic to deprecate mock providers entirely, and replace 1230 // with something closer to LocationProviderBase.java 1231 1232 /** 1233 * Creates a mock location provider and adds it to the set of active providers. 1234 * 1235 * @param name the provider name 1236 * 1237 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1238 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1239 * Settings.Secure.ALLOW_MOCK_LOCATION} system setting is not enabled 1240 * @throws IllegalArgumentException if a provider with the given name already exists 1241 * 1242 * @deprecated requesting location providers by name is deprecated 1243 */ 1244 @Deprecated 1245 public void addTestProvider(String name, boolean requiresNetwork, boolean requiresSatellite, 1246 boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude, 1247 boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) { 1248 ProviderProperties properties = new ProviderProperties(requiresNetwork, 1249 requiresSatellite, requiresCell, hasMonetaryCost, supportsAltitude, supportsSpeed, 1250 supportsBearing, powerRequirement, accuracy); 1251 if (name.matches(LocationProvider.BAD_CHARS_REGEX)) { 1252 throw new IllegalArgumentException("provider name contains illegal character: " + name); 1253 } 1254 1255 try { 1256 mService.addTestProvider(name, properties); 1257 } catch (RemoteException e) { 1258 Log.e(TAG, "RemoteException", e); 1259 } 1260 } 1261 1262 /** 1263 * Removes the mock location provider with the given name. 1264 * 1265 * @param provider the provider name 1266 * 1267 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1268 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1269 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1270 * @throws IllegalArgumentException if no provider with the given name exists 1271 * 1272 * @deprecated requesting location providers by name is deprecated 1273 */ 1274 @Deprecated 1275 public void removeTestProvider(String provider) { 1276 try { 1277 mService.removeTestProvider(provider); 1278 } catch (RemoteException e) { 1279 Log.e(TAG, "RemoteException", e); 1280 } 1281 } 1282 1283 /** 1284 * Sets a mock location for the given provider. 1285 * <p>This location will be used in place of any actual location from the provider. 1286 * The location object must have a minimum number of fields set to be 1287 * considered a valid LocationProvider Location, as per documentation 1288 * on {@link Location} class. 1289 * 1290 * @param provider the provider name 1291 * @param loc the mock location 1292 * 1293 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1294 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1295 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1296 * @throws IllegalArgumentException if no provider with the given name exists 1297 * @throws IllegalArgumentException if the location is incomplete 1298 * 1299 * @deprecated requesting location providers by name is deprecated 1300 */ 1301 @Deprecated 1302 public void setTestProviderLocation(String provider, Location loc) { 1303 if (!loc.isComplete()) { 1304 IllegalArgumentException e = new IllegalArgumentException( 1305 "Incomplete location object, missing timestamp or accuracy? " + loc); 1306 if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN) { 1307 // just log on old platform (for backwards compatibility) 1308 Log.w(TAG, e); 1309 loc.makeComplete(); 1310 } else { 1311 // really throw it! 1312 throw e; 1313 } 1314 } 1315 1316 try { 1317 mService.setTestProviderLocation(provider, loc); 1318 } catch (RemoteException e) { 1319 Log.e(TAG, "RemoteException", e); 1320 } 1321 } 1322 1323 /** 1324 * Removes any mock location associated with the given provider. 1325 * 1326 * @param provider the provider name 1327 * 1328 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1329 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1330 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1331 * @throws IllegalArgumentException if no provider with the given name exists 1332 * 1333 * @deprecated requesting location providers by name is deprecated 1334 */ 1335 @Deprecated 1336 public void clearTestProviderLocation(String provider) { 1337 try { 1338 mService.clearTestProviderLocation(provider); 1339 } catch (RemoteException e) { 1340 Log.e(TAG, "RemoteException", e); 1341 } 1342 } 1343 1344 /** 1345 * Sets a mock enabled value for the given provider. This value will be used in place 1346 * of any actual value from the provider. 1347 * 1348 * @param provider the provider name 1349 * @param enabled the mock enabled value 1350 * 1351 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1352 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1353 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1354 * @throws IllegalArgumentException if no provider with the given name exists 1355 * 1356 * @deprecated requesting location providers by name is deprecated 1357 */ 1358 @Deprecated 1359 public void setTestProviderEnabled(String provider, boolean enabled) { 1360 try { 1361 mService.setTestProviderEnabled(provider, enabled); 1362 } catch (RemoteException e) { 1363 Log.e(TAG, "RemoteException", e); 1364 } 1365 } 1366 1367 /** 1368 * Removes any mock enabled value associated with the given provider. 1369 * 1370 * @param provider the provider name 1371 * 1372 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1373 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1374 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1375 * @throws IllegalArgumentException if no provider with the given name exists 1376 * 1377 * @deprecated requesting location providers by name is deprecated 1378 */ 1379 @Deprecated 1380 public void clearTestProviderEnabled(String provider) { 1381 try { 1382 mService.clearTestProviderEnabled(provider); 1383 } catch (RemoteException e) { 1384 Log.e(TAG, "RemoteException", e); 1385 } 1386 } 1387 1388 /** 1389 * Sets mock status values for the given provider. These values will be used in place 1390 * of any actual values from the provider. 1391 * 1392 * @param provider the provider name 1393 * @param status the mock status 1394 * @param extras a Bundle containing mock extras 1395 * @param updateTime the mock update time 1396 * 1397 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1398 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1399 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1400 * @throws IllegalArgumentException if no provider with the given name exists 1401 * 1402 * @deprecated requesting location providers by name is deprecated 1403 */ 1404 @Deprecated 1405 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) { 1406 try { 1407 mService.setTestProviderStatus(provider, status, extras, updateTime); 1408 } catch (RemoteException e) { 1409 Log.e(TAG, "RemoteException", e); 1410 } 1411 } 1412 1413 /** 1414 * Removes any mock status values associated with the given provider. 1415 * 1416 * @param provider the provider name 1417 * 1418 * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present 1419 * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION 1420 * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled 1421 * @throws IllegalArgumentException if no provider with the given name exists 1422 * 1423 * @deprecated requesting location providers by name is deprecated 1424 */ 1425 @Deprecated 1426 public void clearTestProviderStatus(String provider) { 1427 try { 1428 mService.clearTestProviderStatus(provider); 1429 } catch (RemoteException e) { 1430 Log.e(TAG, "RemoteException", e); 1431 } 1432 } 1433 1434 // --- GPS-specific support --- 1435 1436 // This class is used to send GPS status events to the client's main thread. 1437 private class GpsStatusListenerTransport extends IGpsStatusListener.Stub { 1438 1439 private final GpsStatus.Listener mListener; 1440 private final GpsStatus.NmeaListener mNmeaListener; 1441 1442 // This must not equal any of the GpsStatus event IDs 1443 private static final int NMEA_RECEIVED = 1000; 1444 1445 private class Nmea { 1446 long mTimestamp; 1447 String mNmea; 1448 1449 Nmea(long timestamp, String nmea) { 1450 mTimestamp = timestamp; 1451 mNmea = nmea; 1452 } 1453 } 1454 private ArrayList<Nmea> mNmeaBuffer; 1455 1456 GpsStatusListenerTransport(GpsStatus.Listener listener) { 1457 mListener = listener; 1458 mNmeaListener = null; 1459 } 1460 1461 GpsStatusListenerTransport(GpsStatus.NmeaListener listener) { 1462 mNmeaListener = listener; 1463 mListener = null; 1464 mNmeaBuffer = new ArrayList<Nmea>(); 1465 } 1466 1467 @Override 1468 public void onGpsStarted() { 1469 if (mListener != null) { 1470 Message msg = Message.obtain(); 1471 msg.what = GpsStatus.GPS_EVENT_STARTED; 1472 mGpsHandler.sendMessage(msg); 1473 } 1474 } 1475 1476 @Override 1477 public void onGpsStopped() { 1478 if (mListener != null) { 1479 Message msg = Message.obtain(); 1480 msg.what = GpsStatus.GPS_EVENT_STOPPED; 1481 mGpsHandler.sendMessage(msg); 1482 } 1483 } 1484 1485 @Override 1486 public void onFirstFix(int ttff) { 1487 if (mListener != null) { 1488 mGpsStatus.setTimeToFirstFix(ttff); 1489 Message msg = Message.obtain(); 1490 msg.what = GpsStatus.GPS_EVENT_FIRST_FIX; 1491 mGpsHandler.sendMessage(msg); 1492 } 1493 } 1494 1495 @Override 1496 public void onSvStatusChanged(int svCount, int[] prns, float[] snrs, 1497 float[] elevations, float[] azimuths, int ephemerisMask, 1498 int almanacMask, int usedInFixMask) { 1499 if (mListener != null) { 1500 mGpsStatus.setStatus(svCount, prns, snrs, elevations, azimuths, 1501 ephemerisMask, almanacMask, usedInFixMask); 1502 1503 Message msg = Message.obtain(); 1504 msg.what = GpsStatus.GPS_EVENT_SATELLITE_STATUS; 1505 // remove any SV status messages already in the queue 1506 mGpsHandler.removeMessages(GpsStatus.GPS_EVENT_SATELLITE_STATUS); 1507 mGpsHandler.sendMessage(msg); 1508 } 1509 } 1510 1511 @Override 1512 public void onNmeaReceived(long timestamp, String nmea) { 1513 if (mNmeaListener != null) { 1514 synchronized (mNmeaBuffer) { 1515 mNmeaBuffer.add(new Nmea(timestamp, nmea)); 1516 } 1517 Message msg = Message.obtain(); 1518 msg.what = NMEA_RECEIVED; 1519 // remove any NMEA_RECEIVED messages already in the queue 1520 mGpsHandler.removeMessages(NMEA_RECEIVED); 1521 mGpsHandler.sendMessage(msg); 1522 } 1523 } 1524 1525 private final Handler mGpsHandler = new Handler() { 1526 @Override 1527 public void handleMessage(Message msg) { 1528 if (msg.what == NMEA_RECEIVED) { 1529 synchronized (mNmeaBuffer) { 1530 int length = mNmeaBuffer.size(); 1531 for (int i = 0; i < length; i++) { 1532 Nmea nmea = mNmeaBuffer.get(i); 1533 mNmeaListener.onNmeaReceived(nmea.mTimestamp, nmea.mNmea); 1534 } 1535 mNmeaBuffer.clear(); 1536 } 1537 } else { 1538 // synchronize on mGpsStatus to ensure the data is copied atomically. 1539 synchronized(mGpsStatus) { 1540 mListener.onGpsStatusChanged(msg.what); 1541 } 1542 } 1543 } 1544 }; 1545 } 1546 1547 /** 1548 * Adds a GPS status listener. 1549 * 1550 * @param listener GPS status listener object to register 1551 * 1552 * @return true if the listener was successfully added 1553 * 1554 * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present 1555 */ 1556 public boolean addGpsStatusListener(GpsStatus.Listener listener) { 1557 boolean result; 1558 1559 if (mGpsStatusListeners.get(listener) != null) { 1560 // listener is already registered 1561 return true; 1562 } 1563 try { 1564 GpsStatusListenerTransport transport = new GpsStatusListenerTransport(listener); 1565 result = mService.addGpsStatusListener(transport); 1566 if (result) { 1567 mGpsStatusListeners.put(listener, transport); 1568 } 1569 } catch (RemoteException e) { 1570 Log.e(TAG, "RemoteException in registerGpsStatusListener: ", e); 1571 result = false; 1572 } 1573 1574 return result; 1575 } 1576 1577 /** 1578 * Removes a GPS status listener. 1579 * 1580 * @param listener GPS status listener object to remove 1581 */ 1582 public void removeGpsStatusListener(GpsStatus.Listener listener) { 1583 try { 1584 GpsStatusListenerTransport transport = mGpsStatusListeners.remove(listener); 1585 if (transport != null) { 1586 mService.removeGpsStatusListener(transport); 1587 } 1588 } catch (RemoteException e) { 1589 Log.e(TAG, "RemoteException in unregisterGpsStatusListener: ", e); 1590 } 1591 } 1592 1593 /** 1594 * Adds an NMEA listener. 1595 * 1596 * @param listener a {@link GpsStatus.NmeaListener} object to register 1597 * 1598 * @return true if the listener was successfully added 1599 * 1600 * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present 1601 */ 1602 public boolean addNmeaListener(GpsStatus.NmeaListener listener) { 1603 boolean result; 1604 1605 if (mNmeaListeners.get(listener) != null) { 1606 // listener is already registered 1607 return true; 1608 } 1609 try { 1610 GpsStatusListenerTransport transport = new GpsStatusListenerTransport(listener); 1611 result = mService.addGpsStatusListener(transport); 1612 if (result) { 1613 mNmeaListeners.put(listener, transport); 1614 } 1615 } catch (RemoteException e) { 1616 Log.e(TAG, "RemoteException in registerGpsStatusListener: ", e); 1617 result = false; 1618 } 1619 1620 return result; 1621 } 1622 1623 /** 1624 * Removes an NMEA listener. 1625 * 1626 * @param listener a {@link GpsStatus.NmeaListener} object to remove 1627 */ 1628 public void removeNmeaListener(GpsStatus.NmeaListener listener) { 1629 try { 1630 GpsStatusListenerTransport transport = mNmeaListeners.remove(listener); 1631 if (transport != null) { 1632 mService.removeGpsStatusListener(transport); 1633 } 1634 } catch (RemoteException e) { 1635 Log.e(TAG, "RemoteException in unregisterGpsStatusListener: ", e); 1636 } 1637 } 1638 1639 /** 1640 * Retrieves information about the current status of the GPS engine. 1641 * This should only be called from the {@link GpsStatus.Listener#onGpsStatusChanged} 1642 * callback to ensure that the data is copied atomically. 1643 * 1644 * The caller may either pass in a {@link GpsStatus} object to set with the latest 1645 * status information, or pass null to create a new {@link GpsStatus} object. 1646 * 1647 * @param status object containing GPS status details, or null. 1648 * @return status object containing updated GPS status. 1649 */ 1650 public GpsStatus getGpsStatus(GpsStatus status) { 1651 if (status == null) { 1652 status = new GpsStatus(); 1653 } 1654 status.setStatus(mGpsStatus); 1655 return status; 1656 } 1657 1658 /** 1659 * Sends additional commands to a location provider. 1660 * Can be used to support provider specific extensions to the Location Manager API 1661 * 1662 * @param provider name of the location provider. 1663 * @param command name of the command to send to the provider. 1664 * @param extras optional arguments for the command (or null). 1665 * The provider may optionally fill the extras Bundle with results from the command. 1666 * 1667 * @return true if the command succeeds. 1668 * 1669 * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager} 1670 */ 1671 @Deprecated 1672 public boolean sendExtraCommand(String provider, String command, Bundle extras) { 1673 try { 1674 return mService.sendExtraCommand(provider, command, extras); 1675 } catch (RemoteException e) { 1676 Log.e(TAG, "RemoteException in sendExtraCommand: ", e); 1677 return false; 1678 } 1679 } 1680 1681 /** 1682 * Used by NetInitiatedActivity to report user response 1683 * for network initiated GPS fix requests. 1684 * 1685 * @hide 1686 */ 1687 public boolean sendNiResponse(int notifId, int userResponse) { 1688 try { 1689 return mService.sendNiResponse(notifId, userResponse); 1690 } catch (RemoteException e) { 1691 Log.e(TAG, "RemoteException in sendNiResponse: ", e); 1692 return false; 1693 } 1694 } 1695 1696 private static void checkProvider(String provider) { 1697 if (provider == null) { 1698 throw new IllegalArgumentException("invalid provider: " + provider); 1699 } 1700 } 1701 1702 private static void checkCriteria(Criteria criteria) { 1703 if (criteria == null) { 1704 throw new IllegalArgumentException("invalid criteria: " + criteria); 1705 } 1706 } 1707 1708 private static void checkListener(LocationListener listener) { 1709 if (listener == null) { 1710 throw new IllegalArgumentException("invalid listener: " + listener); 1711 } 1712 } 1713 1714 private void checkPendingIntent(PendingIntent intent) { 1715 if (intent == null) { 1716 throw new IllegalArgumentException("invalid pending intent: " + intent); 1717 } 1718 if (!intent.isTargetedToPackage()) { 1719 IllegalArgumentException e = new IllegalArgumentException( 1720 "pending intent msut be targeted to package"); 1721 if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.JELLY_BEAN) { 1722 throw e; 1723 } else { 1724 Log.w(TAG, e); 1725 } 1726 } 1727 } 1728 1729 private static void checkGeofence(Geofence fence) { 1730 if (fence == null) { 1731 throw new IllegalArgumentException("invalid geofence: " + fence); 1732 } 1733 } 1734} 1735