LocationManager.java revision 4fab68b5324e1f9b6765cdc33e66d1f074623dc2
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     * <p>Before API version 17, this method could be used with
998     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} or
999     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
1000     * From API version 17 and onwards, this method requires
1001     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission.
1002     *
1003     * @param latitude the latitude of the central point of the
1004     * alert region
1005     * @param longitude the longitude of the central point of the
1006     * alert region
1007     * @param radius the radius of the central point of the
1008     * alert region, in meters
1009     * @param expiration time for this proximity alert, in milliseconds,
1010     * or -1 to indicate no expiration
1011     * @param intent a PendingIntent that will be used to generate an Intent to
1012     * fire when entry to or exit from the alert region is detected
1013     *
1014     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
1015     * permission is not present
1016     *
1017     * @deprecated Use {@link LocationRequest} and {@link Geofence} instead
1018     */
1019    @Deprecated
1020    public void addProximityAlert(double latitude, double longitude, float radius, long expiration,
1021            PendingIntent intent) {
1022        checkPendingIntent(intent);
1023        if (expiration < 0) expiration = Long.MAX_VALUE;
1024
1025        Geofence fence = Geofence.createCircle(latitude, longitude, radius);
1026        LocationRequest request = new LocationRequest().setExpireIn(expiration);
1027        try {
1028            mService.requestGeofence(request, fence, intent, mContext.getPackageName());
1029        } catch (RemoteException e) {
1030            Log.e(TAG, "RemoteException", e);
1031        }
1032    }
1033
1034    /**
1035     * Add a geofence with the specified LocationRequest quality of service.
1036     *
1037     * <p> When the device
1038     * detects that it has entered or exited the area surrounding the
1039     * location, the given PendingIntent will be used to create an Intent
1040     * to be fired.
1041     *
1042     * <p> The fired Intent will have a boolean extra added with key
1043     * {@link #KEY_PROXIMITY_ENTERING}. If the value is true, the device is
1044     * entering the proximity region; if false, it is exiting.
1045     *
1046     * <p> The geofence engine fuses results from all location providers to
1047     * provide the best balance between accuracy and power. Applications
1048     * can choose the quality of service required using the
1049     * {@link LocationRequest} object. If it is null then a default,
1050     * low power geo-fencing implementation is used. It is possible to cross
1051     * a geo-fence without notification, but the system will do its best
1052     * to detect, using {@link LocationRequest} as a hint to trade-off
1053     * accuracy and power.
1054     *
1055     * <p> The power required by the geofence engine can depend on many factors,
1056     * such as quality and interval requested in {@link LocationRequest},
1057     * distance to nearest geofence and current device velocity.
1058     *
1059     * @param request quality of service required, null for default low power
1060     * @param fence a geographical description of the geofence area
1061     * @param intent pending intent to receive geofence updates
1062     *
1063     * @throws IllegalArgumentException if fence is null
1064     * @throws IllegalArgumentException if intent is null
1065     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
1066     * permission is not present
1067     */
1068    public void addGeofence(LocationRequest request, Geofence fence, PendingIntent intent) {
1069        checkPendingIntent(intent);
1070        checkGeofence(fence);
1071
1072        try {
1073            mService.requestGeofence(request, fence, intent, mContext.getPackageName());
1074        } catch (RemoteException e) {
1075            Log.e(TAG, "RemoteException", e);
1076        }
1077    }
1078
1079    /**
1080     * Removes the proximity alert with the given PendingIntent.
1081     *
1082     * <p>Before API version 17, this method could be used with
1083     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} or
1084     * {@link android.Manifest.permission#ACCESS_COARSE_LOCATION}.
1085     * From API version 17 and onwards, this method requires
1086     * {@link android.Manifest.permission#ACCESS_FINE_LOCATION} permission.
1087     *
1088     * @param intent the PendingIntent that no longer needs to be notified of
1089     * proximity alerts
1090     *
1091     * @throws IllegalArgumentException if intent is null
1092     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
1093     * permission is not present
1094     *
1095     * @deprecated Use {@link LocationRequest} and {@link Geofence} instead
1096     */
1097    @Deprecated
1098    public void removeProximityAlert(PendingIntent intent) {
1099        checkPendingIntent(intent);
1100        String packageName = mContext.getPackageName();
1101
1102        try {
1103            mService.removeGeofence(null, intent, packageName);
1104        } catch (RemoteException e) {
1105            Log.e(TAG, "RemoteException", e);
1106        }
1107    }
1108
1109    /**
1110     * Remove a single geofence.
1111     *
1112     * <p>This removes only the specified geofence associated with the
1113     * specified pending intent. All other geofences remain unchanged.
1114     *
1115     * @param fence a geofence previously passed to {@link #addGeofence}
1116     * @param intent a pending intent previously passed to {@link #addGeofence}
1117     *
1118     * @throws IllegalArgumentException if fence is null
1119     * @throws IllegalArgumentException if intent is null
1120     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
1121     * permission is not present
1122     */
1123    public void removeGeofence(Geofence fence, PendingIntent intent) {
1124        checkPendingIntent(intent);
1125        checkGeofence(fence);
1126        String packageName = mContext.getPackageName();
1127
1128        try {
1129            mService.removeGeofence(fence, intent, packageName);
1130        } catch (RemoteException e) {
1131            Log.e(TAG, "RemoteException", e);
1132        }
1133    }
1134
1135    /**
1136     * Remove all geofences registered to the specified pending intent.
1137     *
1138     * @param intent a pending intent previously passed to {@link #addGeofence}
1139     *
1140     * @throws IllegalArgumentException if intent is null
1141     * @throws SecurityException if {@link android.Manifest.permission#ACCESS_FINE_LOCATION}
1142     * permission is not present
1143     */
1144    public void removeAllGeofences(PendingIntent intent) {
1145        checkPendingIntent(intent);
1146        String packageName = mContext.getPackageName();
1147
1148        try {
1149            mService.removeGeofence(null, intent, packageName);
1150        } catch (RemoteException e) {
1151            Log.e(TAG, "RemoteException", e);
1152        }
1153    }
1154
1155    /**
1156     * Returns the current enabled/disabled status of the given provider.
1157     *
1158     * <p>If the user has enabled this provider in the Settings menu, true
1159     * is returned otherwise false is returned
1160     *
1161     * @param provider the name of the provider
1162     * @return true if the provider is enabled
1163     *
1164     * @throws IllegalArgumentException if provider is null
1165     * @throws SecurityException if no suitable permission is present
1166     *
1167     * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager}
1168     */
1169    @Deprecated
1170    public boolean isProviderEnabled(String provider) {
1171        checkProvider(provider);
1172
1173        try {
1174            return mService.isProviderEnabled(provider);
1175        } catch (RemoteException e) {
1176            Log.e(TAG, "RemoteException", e);
1177            return false;
1178        }
1179    }
1180
1181    /**
1182     * Get the last known location.
1183     *
1184     * <p>This location could be very old so use
1185     * {@link Location#getElapsedRealtimeNano} to calculate its age. It can
1186     * also return null if no previous location is available.
1187     *
1188     * <p>Always returns immediately.
1189     *
1190     * @return The last known location, or null if not available
1191     * @throws SecurityException if no suitable permission is present
1192     */
1193    public Location getLastLocation() {
1194        String packageName = mContext.getPackageName();
1195
1196        try {
1197            return mService.getLastLocation(null, packageName);
1198        } catch (RemoteException e) {
1199            Log.e(TAG, "RemoteException", e);
1200            return null;
1201        }
1202    }
1203
1204    /**
1205     * Returns a Location indicating the data from the last known
1206     * location fix obtained from the given provider.
1207     *
1208     * <p> This can be done
1209     * without starting the provider.  Note that this location could
1210     * be out-of-date, for example if the device was turned off and
1211     * moved to another location.
1212     *
1213     * <p> If the provider is currently disabled, null is returned.
1214     *
1215     * @param provider the name of the provider
1216     * @return the last known location for the provider, or null
1217     *
1218     * @throws SecurityException if no suitable permission is present
1219     * @throws IllegalArgumentException if provider is null or doesn't exist
1220     *
1221     * @deprecated Use {@link #getLastLocation} instead
1222     */
1223    @Deprecated
1224    public Location getLastKnownLocation(String provider) {
1225        checkProvider(provider);
1226        String packageName = mContext.getPackageName();
1227        LocationRequest request = LocationRequest.createFromDeprecatedProvider(
1228                provider, 0, 0, true);
1229
1230        try {
1231            return mService.getLastLocation(request, packageName);
1232        } catch (RemoteException e) {
1233            Log.e(TAG, "RemoteException", e);
1234            return null;
1235        }
1236    }
1237
1238    // --- Mock provider support ---
1239    // TODO: It would be fantastic to deprecate mock providers entirely, and replace
1240    // with something closer to LocationProviderBase.java
1241
1242    /**
1243     * Creates a mock location provider and adds it to the set of active providers.
1244     *
1245     * @param name the provider name
1246     *
1247     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1248     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1249     * Settings.Secure.ALLOW_MOCK_LOCATION} system setting is not enabled
1250     * @throws IllegalArgumentException if a provider with the given name already exists
1251     *
1252     * @deprecated requesting location providers by name is deprecated
1253     */
1254    @Deprecated
1255    public void addTestProvider(String name, boolean requiresNetwork, boolean requiresSatellite,
1256            boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude,
1257            boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) {
1258        ProviderProperties properties = new ProviderProperties(requiresNetwork,
1259                requiresSatellite, requiresCell, hasMonetaryCost, supportsAltitude, supportsSpeed,
1260                supportsBearing, powerRequirement, accuracy);
1261        if (name.matches(LocationProvider.BAD_CHARS_REGEX)) {
1262            throw new IllegalArgumentException("provider name contains illegal character: " + name);
1263        }
1264
1265        try {
1266            mService.addTestProvider(name, properties);
1267        } catch (RemoteException e) {
1268            Log.e(TAG, "RemoteException", e);
1269        }
1270    }
1271
1272    /**
1273     * Removes the mock location provider with the given name.
1274     *
1275     * @param provider the provider name
1276     *
1277     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1278     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1279     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1280     * @throws IllegalArgumentException if no provider with the given name exists
1281     *
1282     * @deprecated requesting location providers by name is deprecated
1283     */
1284    @Deprecated
1285    public void removeTestProvider(String provider) {
1286        try {
1287            mService.removeTestProvider(provider);
1288        } catch (RemoteException e) {
1289            Log.e(TAG, "RemoteException", e);
1290        }
1291    }
1292
1293    /**
1294     * Sets a mock location for the given provider.
1295     * <p>This location will be used in place of any actual location from the provider.
1296     * The location object must have a minimum number of fields set to be
1297     * considered a valid LocationProvider Location, as per documentation
1298     * on {@link Location} class.
1299     *
1300     * @param provider the provider name
1301     * @param loc the mock location
1302     *
1303     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1304     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1305     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1306     * @throws IllegalArgumentException if no provider with the given name exists
1307     * @throws IllegalArgumentException if the location is incomplete
1308     *
1309     * @deprecated requesting location providers by name is deprecated
1310     */
1311    @Deprecated
1312    public void setTestProviderLocation(String provider, Location loc) {
1313        if (!loc.isComplete()) {
1314            IllegalArgumentException e = new IllegalArgumentException(
1315                    "Incomplete location object, missing timestamp or accuracy? " + loc);
1316            if (mContext.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.JELLY_BEAN) {
1317                // just log on old platform (for backwards compatibility)
1318                Log.w(TAG, e);
1319                loc.makeComplete();
1320            } else {
1321                // really throw it!
1322                throw e;
1323            }
1324        }
1325
1326        try {
1327            mService.setTestProviderLocation(provider, loc);
1328        } catch (RemoteException e) {
1329            Log.e(TAG, "RemoteException", e);
1330        }
1331    }
1332
1333    /**
1334     * Removes any mock location associated with the given provider.
1335     *
1336     * @param provider the provider name
1337     *
1338     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1339     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1340     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1341     * @throws IllegalArgumentException if no provider with the given name exists
1342     *
1343     * @deprecated requesting location providers by name is deprecated
1344     */
1345    @Deprecated
1346    public void clearTestProviderLocation(String provider) {
1347        try {
1348            mService.clearTestProviderLocation(provider);
1349        } catch (RemoteException e) {
1350            Log.e(TAG, "RemoteException", e);
1351        }
1352    }
1353
1354    /**
1355     * Sets a mock enabled value for the given provider.  This value will be used in place
1356     * of any actual value from the provider.
1357     *
1358     * @param provider the provider name
1359     * @param enabled the mock enabled value
1360     *
1361     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1362     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1363     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1364     * @throws IllegalArgumentException if no provider with the given name exists
1365     *
1366     * @deprecated requesting location providers by name is deprecated
1367     */
1368    @Deprecated
1369    public void setTestProviderEnabled(String provider, boolean enabled) {
1370        try {
1371            mService.setTestProviderEnabled(provider, enabled);
1372        } catch (RemoteException e) {
1373            Log.e(TAG, "RemoteException", e);
1374        }
1375    }
1376
1377    /**
1378     * Removes any mock enabled value associated with the given provider.
1379     *
1380     * @param provider the provider name
1381     *
1382     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1383     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1384     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1385     * @throws IllegalArgumentException if no provider with the given name exists
1386     *
1387     * @deprecated requesting location providers by name is deprecated
1388     */
1389    @Deprecated
1390    public void clearTestProviderEnabled(String provider) {
1391        try {
1392            mService.clearTestProviderEnabled(provider);
1393        } catch (RemoteException e) {
1394            Log.e(TAG, "RemoteException", e);
1395        }
1396    }
1397
1398    /**
1399     * Sets mock status values for the given provider.  These values will be used in place
1400     * of any actual values from the provider.
1401     *
1402     * @param provider the provider name
1403     * @param status the mock status
1404     * @param extras a Bundle containing mock extras
1405     * @param updateTime the mock update time
1406     *
1407     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1408     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1409     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1410     * @throws IllegalArgumentException if no provider with the given name exists
1411     *
1412     * @deprecated requesting location providers by name is deprecated
1413     */
1414    @Deprecated
1415    public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
1416        try {
1417            mService.setTestProviderStatus(provider, status, extras, updateTime);
1418        } catch (RemoteException e) {
1419            Log.e(TAG, "RemoteException", e);
1420        }
1421    }
1422
1423    /**
1424     * Removes any mock status values associated with the given provider.
1425     *
1426     * @param provider the provider name
1427     *
1428     * @throws SecurityException if the ACCESS_MOCK_LOCATION permission is not present
1429     * or the {@link android.provider.Settings.Secure#ALLOW_MOCK_LOCATION
1430     * Settings.Secure.ALLOW_MOCK_LOCATION}} system setting is not enabled
1431     * @throws IllegalArgumentException if no provider with the given name exists
1432     *
1433     * @deprecated requesting location providers by name is deprecated
1434     */
1435    @Deprecated
1436    public void clearTestProviderStatus(String provider) {
1437        try {
1438            mService.clearTestProviderStatus(provider);
1439        } catch (RemoteException e) {
1440            Log.e(TAG, "RemoteException", e);
1441        }
1442    }
1443
1444    // --- GPS-specific support ---
1445
1446    // This class is used to send GPS status events to the client's main thread.
1447    private class GpsStatusListenerTransport extends IGpsStatusListener.Stub {
1448
1449        private final GpsStatus.Listener mListener;
1450        private final GpsStatus.NmeaListener mNmeaListener;
1451
1452        // This must not equal any of the GpsStatus event IDs
1453        private static final int NMEA_RECEIVED = 1000;
1454
1455        private class Nmea {
1456            long mTimestamp;
1457            String mNmea;
1458
1459            Nmea(long timestamp, String nmea) {
1460                mTimestamp = timestamp;
1461                mNmea = nmea;
1462            }
1463        }
1464        private ArrayList<Nmea> mNmeaBuffer;
1465
1466        GpsStatusListenerTransport(GpsStatus.Listener listener) {
1467            mListener = listener;
1468            mNmeaListener = null;
1469        }
1470
1471        GpsStatusListenerTransport(GpsStatus.NmeaListener listener) {
1472            mNmeaListener = listener;
1473            mListener = null;
1474            mNmeaBuffer = new ArrayList<Nmea>();
1475        }
1476
1477        @Override
1478        public void onGpsStarted() {
1479            if (mListener != null) {
1480                Message msg = Message.obtain();
1481                msg.what = GpsStatus.GPS_EVENT_STARTED;
1482                mGpsHandler.sendMessage(msg);
1483            }
1484        }
1485
1486        @Override
1487        public void onGpsStopped() {
1488            if (mListener != null) {
1489                Message msg = Message.obtain();
1490                msg.what = GpsStatus.GPS_EVENT_STOPPED;
1491                mGpsHandler.sendMessage(msg);
1492            }
1493        }
1494
1495        @Override
1496        public void onFirstFix(int ttff) {
1497            if (mListener != null) {
1498                mGpsStatus.setTimeToFirstFix(ttff);
1499                Message msg = Message.obtain();
1500                msg.what = GpsStatus.GPS_EVENT_FIRST_FIX;
1501                mGpsHandler.sendMessage(msg);
1502            }
1503        }
1504
1505        @Override
1506        public void onSvStatusChanged(int svCount, int[] prns, float[] snrs,
1507                float[] elevations, float[] azimuths, int ephemerisMask,
1508                int almanacMask, int usedInFixMask) {
1509            if (mListener != null) {
1510                mGpsStatus.setStatus(svCount, prns, snrs, elevations, azimuths,
1511                        ephemerisMask, almanacMask, usedInFixMask);
1512
1513                Message msg = Message.obtain();
1514                msg.what = GpsStatus.GPS_EVENT_SATELLITE_STATUS;
1515                // remove any SV status messages already in the queue
1516                mGpsHandler.removeMessages(GpsStatus.GPS_EVENT_SATELLITE_STATUS);
1517                mGpsHandler.sendMessage(msg);
1518            }
1519        }
1520
1521        @Override
1522        public void onNmeaReceived(long timestamp, String nmea) {
1523            if (mNmeaListener != null) {
1524                synchronized (mNmeaBuffer) {
1525                    mNmeaBuffer.add(new Nmea(timestamp, nmea));
1526                }
1527                Message msg = Message.obtain();
1528                msg.what = NMEA_RECEIVED;
1529                // remove any NMEA_RECEIVED messages already in the queue
1530                mGpsHandler.removeMessages(NMEA_RECEIVED);
1531                mGpsHandler.sendMessage(msg);
1532            }
1533        }
1534
1535        private final Handler mGpsHandler = new Handler() {
1536            @Override
1537            public void handleMessage(Message msg) {
1538                if (msg.what == NMEA_RECEIVED) {
1539                    synchronized (mNmeaBuffer) {
1540                        int length = mNmeaBuffer.size();
1541                        for (int i = 0; i < length; i++) {
1542                            Nmea nmea = mNmeaBuffer.get(i);
1543                            mNmeaListener.onNmeaReceived(nmea.mTimestamp, nmea.mNmea);
1544                        }
1545                        mNmeaBuffer.clear();
1546                    }
1547                } else {
1548                    // synchronize on mGpsStatus to ensure the data is copied atomically.
1549                    synchronized(mGpsStatus) {
1550                        mListener.onGpsStatusChanged(msg.what);
1551                    }
1552                }
1553            }
1554        };
1555    }
1556
1557    /**
1558     * Adds a GPS status listener.
1559     *
1560     * @param listener GPS status listener object to register
1561     *
1562     * @return true if the listener was successfully added
1563     *
1564     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
1565     */
1566    public boolean addGpsStatusListener(GpsStatus.Listener listener) {
1567        boolean result;
1568
1569        if (mGpsStatusListeners.get(listener) != null) {
1570            // listener is already registered
1571            return true;
1572        }
1573        try {
1574            GpsStatusListenerTransport transport = new GpsStatusListenerTransport(listener);
1575            result = mService.addGpsStatusListener(transport);
1576            if (result) {
1577                mGpsStatusListeners.put(listener, transport);
1578            }
1579        } catch (RemoteException e) {
1580            Log.e(TAG, "RemoteException in registerGpsStatusListener: ", e);
1581            result = false;
1582        }
1583
1584        return result;
1585    }
1586
1587    /**
1588     * Removes a GPS status listener.
1589     *
1590     * @param listener GPS status listener object to remove
1591     */
1592    public void removeGpsStatusListener(GpsStatus.Listener listener) {
1593        try {
1594            GpsStatusListenerTransport transport = mGpsStatusListeners.remove(listener);
1595            if (transport != null) {
1596                mService.removeGpsStatusListener(transport);
1597            }
1598        } catch (RemoteException e) {
1599            Log.e(TAG, "RemoteException in unregisterGpsStatusListener: ", e);
1600        }
1601    }
1602
1603    /**
1604     * Adds an NMEA listener.
1605     *
1606     * @param listener a {#link GpsStatus.NmeaListener} object to register
1607     *
1608     * @return true if the listener was successfully added
1609     *
1610     * @throws SecurityException if the ACCESS_FINE_LOCATION permission is not present
1611     */
1612    public boolean addNmeaListener(GpsStatus.NmeaListener listener) {
1613        boolean result;
1614
1615        if (mNmeaListeners.get(listener) != null) {
1616            // listener is already registered
1617            return true;
1618        }
1619        try {
1620            GpsStatusListenerTransport transport = new GpsStatusListenerTransport(listener);
1621            result = mService.addGpsStatusListener(transport);
1622            if (result) {
1623                mNmeaListeners.put(listener, transport);
1624            }
1625        } catch (RemoteException e) {
1626            Log.e(TAG, "RemoteException in registerGpsStatusListener: ", e);
1627            result = false;
1628        }
1629
1630        return result;
1631    }
1632
1633    /**
1634     * Removes an NMEA listener.
1635     *
1636     * @param listener a {#link GpsStatus.NmeaListener} object to remove
1637     */
1638    public void removeNmeaListener(GpsStatus.NmeaListener listener) {
1639        try {
1640            GpsStatusListenerTransport transport = mNmeaListeners.remove(listener);
1641            if (transport != null) {
1642                mService.removeGpsStatusListener(transport);
1643            }
1644        } catch (RemoteException e) {
1645            Log.e(TAG, "RemoteException in unregisterGpsStatusListener: ", e);
1646        }
1647    }
1648
1649     /**
1650     * Retrieves information about the current status of the GPS engine.
1651     * This should only be called from the {@link GpsStatus.Listener#onGpsStatusChanged}
1652     * callback to ensure that the data is copied atomically.
1653     *
1654     * The caller may either pass in a {@link GpsStatus} object to set with the latest
1655     * status information, or pass null to create a new {@link GpsStatus} object.
1656     *
1657     * @param status object containing GPS status details, or null.
1658     * @return status object containing updated GPS status.
1659     */
1660    public GpsStatus getGpsStatus(GpsStatus status) {
1661        if (status == null) {
1662            status = new GpsStatus();
1663       }
1664       status.setStatus(mGpsStatus);
1665       return status;
1666    }
1667
1668    /**
1669     * Sends additional commands to a location provider.
1670     * Can be used to support provider specific extensions to the Location Manager API
1671     *
1672     * @param provider name of the location provider.
1673     * @param command name of the command to send to the provider.
1674     * @param extras optional arguments for the command (or null).
1675     * The provider may optionally fill the extras Bundle with results from the command.
1676     *
1677     * @return true if the command succeeds.
1678     *
1679     * @deprecated Use {@link LocationRequest} instead, see notes on {@link LocationManager}
1680     */
1681    @Deprecated
1682    public boolean sendExtraCommand(String provider, String command, Bundle extras) {
1683        try {
1684            return mService.sendExtraCommand(provider, command, extras);
1685        } catch (RemoteException e) {
1686            Log.e(TAG, "RemoteException in sendExtraCommand: ", e);
1687            return false;
1688        }
1689    }
1690
1691    /**
1692     * Used by NetInitiatedActivity to report user response
1693     * for network initiated GPS fix requests.
1694     *
1695     * @hide
1696     */
1697    public boolean sendNiResponse(int notifId, int userResponse) {
1698    	try {
1699            return mService.sendNiResponse(notifId, userResponse);
1700        } catch (RemoteException e) {
1701            Log.e(TAG, "RemoteException in sendNiResponse: ", e);
1702            return false;
1703        }
1704    }
1705
1706    private static void checkProvider(String provider) {
1707        if (provider == null) {
1708            throw new IllegalArgumentException("invalid provider: " + provider);
1709        }
1710    }
1711
1712    private static void checkCriteria(Criteria criteria) {
1713        if (criteria == null) {
1714            throw new IllegalArgumentException("invalid criteria: " + criteria);
1715        }
1716    }
1717
1718    private static void checkListener(LocationListener listener) {
1719        if (listener == null) {
1720            throw new IllegalArgumentException("invalid listener: " + listener);
1721        }
1722    }
1723
1724    private void checkPendingIntent(PendingIntent intent) {
1725        if (intent == null) {
1726            throw new IllegalArgumentException("invalid pending intent: " + intent);
1727        }
1728        if (!intent.isTargetedToPackage()) {
1729            IllegalArgumentException e = new IllegalArgumentException(
1730                    "pending intent msut be targeted to package");
1731            if (mContext.getApplicationInfo().targetSdkVersion > Build.VERSION_CODES.JELLY_BEAN) {
1732                throw e;
1733            } else {
1734                Log.w(TAG, e);
1735            }
1736        }
1737    }
1738
1739    private static void checkGeofence(Geofence fence) {
1740        if (fence == null) {
1741            throw new IllegalArgumentException("invalid geofence: " + fence);
1742        }
1743    }
1744}
1745