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