blob: e48e04757826b0feded9b4f1bdc3f60637496c47 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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 com.android.server;
18
19import java.io.BufferedReader;
20import java.io.File;
21import java.io.FileDescriptor;
22import java.io.FileReader;
23import java.io.FileWriter;
24import java.io.IOException;
25import java.io.PrintWriter;
26import java.util.ArrayList;
27import java.util.HashMap;
28import java.util.HashSet;
29import java.util.List;
30import java.util.Map;
31import java.util.Set;
32import java.util.regex.Pattern;
33
34import android.app.AlarmManager;
35import android.app.PendingIntent;
36import android.content.BroadcastReceiver;
37import android.content.ContentResolver;
38import android.content.Context;
39import android.content.Intent;
40import android.content.IntentFilter;
41import android.content.pm.PackageManager;
42import android.location.Address;
43import android.location.IGpsStatusListener;
44import android.location.ILocationListener;
45import android.location.ILocationManager;
46import android.location.Location;
47import android.location.LocationManager;
48import android.location.LocationProvider;
49import android.location.LocationProviderImpl;
50import android.net.ConnectivityManager;
51import android.net.Uri;
52import android.net.wifi.ScanResult;
53import android.net.wifi.WifiManager;
54import android.os.Binder;
55import android.os.Bundle;
56import android.os.Handler;
57import android.os.IBinder;
58import android.os.Message;
59import android.os.PowerManager;
60import android.os.RemoteException;
61import android.os.SystemClock;
62import android.provider.Settings;
63import android.telephony.CellLocation;
64import android.telephony.PhoneStateListener;
65import android.telephony.TelephonyManager;
66import android.util.Config;
67import android.util.Log;
68import android.util.PrintWriterPrinter;
69import android.util.SparseIntArray;
70
71import com.android.internal.app.IBatteryStats;
72import com.android.internal.location.CellState;
73import com.android.internal.location.GpsLocationProvider;
74import com.android.internal.location.ILocationCollector;
75import com.android.internal.location.INetworkLocationManager;
76import com.android.internal.location.INetworkLocationProvider;
77import com.android.internal.location.TrackProvider;
78import com.android.server.am.BatteryStatsService;
79
80/**
81 * The service class that manages LocationProviders and issues location
82 * updates and alerts.
83 *
84 * {@hide}
85 */
86public class LocationManagerService extends ILocationManager.Stub
87 implements INetworkLocationManager {
88 private static final String TAG = "LocationManagerService";
89
90 // Minimum time interval between last known location writes, in milliseconds.
91 private static final long MIN_LAST_KNOWN_LOCATION_TIME = 60L * 1000L;
92
93 // Max time to hold wake lock for, in milliseconds.
94 private static final long MAX_TIME_FOR_WAKE_LOCK = 60 * 1000L;
95
96 // Time to wait after releasing a wake lock for clients to process location update,
97 // in milliseconds.
98 private static final long TIME_AFTER_WAKE_LOCK = 2 * 1000L;
99
100 // The last time a location was written, by provider name.
101 private HashMap<String,Long> mLastWriteTime = new HashMap<String,Long>();
102
103 private static final Pattern PATTERN_COMMA = Pattern.compile(",");
104
105 private static final String ACCESS_FINE_LOCATION =
106 android.Manifest.permission.ACCESS_FINE_LOCATION;
107 private static final String ACCESS_COARSE_LOCATION =
108 android.Manifest.permission.ACCESS_COARSE_LOCATION;
109 private static final String ACCESS_MOCK_LOCATION =
110 android.Manifest.permission.ACCESS_MOCK_LOCATION;
111 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
112 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
113
114 // Set of providers that are explicitly enabled
115 private final Set<String> mEnabledProviders = new HashSet<String>();
116
117 // Set of providers that are explicitly disabled
118 private final Set<String> mDisabledProviders = new HashSet<String>();
119
120 // Locations, status values, and extras for mock providers
121 HashMap<String,MockProvider> mMockProviders = new HashMap<String,MockProvider>();
122 private final HashMap<String,Location> mMockProviderLocation = new HashMap<String,Location>();
123 private final HashMap<String,Integer> mMockProviderStatus = new HashMap<String,Integer>();
124 private final HashMap<String,Bundle> mMockProviderStatusExtras = new HashMap<String,Bundle>();
125 private final HashMap<String,Long> mMockProviderStatusUpdateTime = new HashMap<String,Long>();
126
127 private static boolean sProvidersLoaded = false;
128
129 private final Context mContext;
130 private GpsLocationProvider mGpsLocationProvider;
131 private boolean mGpsNavigating;
132 private LocationProviderImpl mNetworkLocationProvider;
133 private INetworkLocationProvider mNetworkLocationInterface;
134 private LocationWorkerHandler mLocationHandler;
135
136 // Handler messages
137 private static final int MESSAGE_HEARTBEAT = 1;
138 private static final int MESSAGE_ACQUIRE_WAKE_LOCK = 2;
139 private static final int MESSAGE_RELEASE_WAKE_LOCK = 3;
140 private static final int MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER = 4;
141
142 // Alarm manager and wakelock variables
143 private final static String ALARM_INTENT = "com.android.location.ALARM_INTENT";
144 private final static String WAKELOCK_KEY = "LocationManagerService";
145 private final static String WIFILOCK_KEY = "LocationManagerService";
146 private AlarmManager mAlarmManager;
147 private long mAlarmInterval = 0;
148 private boolean mScreenOn = true;
149 private PowerManager.WakeLock mWakeLock = null;
150 private WifiManager.WifiLock mWifiLock = null;
151 private long mWakeLockAcquireTime = 0;
152 private boolean mWakeLockGpsReceived = true;
153 private boolean mWakeLockNetworkReceived = true;
154 private boolean mWifiWakeLockAcquired = false;
155 private boolean mCellWakeLockAcquired = false;
156
157 private final IBatteryStats mBatteryStats;
158
159 /**
160 * Mapping from listener IBinder/PendingIntent to local Listener wrappers.
161 */
162 private final ArrayList<Receiver> mListeners = new ArrayList<Receiver>();
163
164 /**
165 * Used for reporting which UIDs are causing the GPS to run.
166 */
167 private final SparseIntArray mReportedGpsUids = new SparseIntArray();
168 private int mReportedGpsSeq = 0;
169
170 /**
171 * Mapping from listener IBinder/PendingIntent to a map from provider name to UpdateRecord.
172 * This also serves as the lock for our state.
173 */
174 private final HashMap<Receiver,HashMap<String,UpdateRecord>> mLocationListeners =
175 new HashMap<Receiver,HashMap<String,UpdateRecord>>();
176
177 /**
178 * Mapping from listener IBinder/PendingIntent to a map from provider name to last broadcast
179 * location.
180 */
181 private final HashMap<Receiver,HashMap<String,Location>> mLastFixBroadcast =
182 new HashMap<Receiver,HashMap<String,Location>>();
183 private final HashMap<Receiver,HashMap<String,Long>> mLastStatusBroadcast =
184 new HashMap<Receiver,HashMap<String,Long>>();
185
186 /**
187 * Mapping from provider name to all its UpdateRecords
188 */
189 private final HashMap<String,ArrayList<UpdateRecord>> mRecordsByProvider =
190 new HashMap<String,ArrayList<UpdateRecord>>();
191
192 /**
193 * Mappings from provider name to object to use for current location. Locations
194 * contained in this list may not always be valid.
195 */
196 private final HashMap<String,Location> mLocationsByProvider =
197 new HashMap<String,Location>();
198
199 // Proximity listeners
200 private Receiver mProximityListener = null;
201 private HashMap<PendingIntent,ProximityAlert> mProximityAlerts =
202 new HashMap<PendingIntent,ProximityAlert>();
203 private HashSet<ProximityAlert> mProximitiesEntered =
204 new HashSet<ProximityAlert>();
205
206 // Last known location for each provider
207 private HashMap<String,Location> mLastKnownLocation =
208 new HashMap<String,Location>();
209
210 // Battery status extras (from com.android.server.BatteryService)
211 private static final String BATTERY_EXTRA_SCALE = "scale";
212 private static final String BATTERY_EXTRA_LEVEL = "level";
213 private static final String BATTERY_EXTRA_PLUGGED = "plugged";
214
215 // Last known cell service state
216 private TelephonyManager mTelephonyManager;
217
218 // Location collector
219 private ILocationCollector mCollector;
220
221 // Wifi Manager
222 private WifiManager mWifiManager;
223
The Android Open Source Project4df24232009-03-05 14:34:35 -0800224 private int mNetworkState = LocationProvider.TEMPORARILY_UNAVAILABLE;
225 private boolean mWifiEnabled = false;
226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 /**
228 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
229 * location updates.
230 */
231 private final class Receiver implements IBinder.DeathRecipient {
232 final ILocationListener mListener;
233 final PendingIntent mPendingIntent;
234 final int mUid;
235 final Object mKey;
236
237 Receiver(ILocationListener listener, int uid) {
238 mListener = listener;
239 mPendingIntent = null;
240 mUid = uid;
241 mKey = listener.asBinder();
242 }
243
244 Receiver(PendingIntent intent, int uid) {
245 mPendingIntent = intent;
246 mListener = null;
247 mUid = uid;
248 mKey = intent;
249 }
250
251 @Override
252 public boolean equals(Object otherObj) {
253 if (otherObj instanceof Receiver) {
254 return mKey.equals(
255 ((Receiver)otherObj).mKey);
256 }
257 return false;
258 }
259
260 @Override
261 public int hashCode() {
262 return mKey.hashCode();
263 }
264
265
266 @Override
267 public String toString() {
268 if (mListener != null) {
269 return "Receiver{"
270 + Integer.toHexString(System.identityHashCode(this))
271 + " uid " + mUid + " Listener " + mKey + "}";
272 } else {
273 return "Receiver{"
274 + Integer.toHexString(System.identityHashCode(this))
275 + " uid " + mUid + " Intent " + mKey + "}";
276 }
277 }
278
279 public boolean isListener() {
280 return mListener != null;
281 }
282
283 public boolean isPendingIntent() {
284 return mPendingIntent != null;
285 }
286
287 public ILocationListener getListener() {
288 if (mListener != null) {
289 return mListener;
290 }
291 throw new IllegalStateException("Request for non-existent listener");
292 }
293
294 public PendingIntent getPendingIntent() {
295 if (mPendingIntent != null) {
296 return mPendingIntent;
297 }
298 throw new IllegalStateException("Request for non-existent intent");
299 }
300
301 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
302 if (mListener != null) {
303 try {
304 mListener.onStatusChanged(provider, status, extras);
305 } catch (RemoteException e) {
306 return false;
307 }
308 } else {
309 Intent statusChanged = new Intent();
310 statusChanged.putExtras(extras);
311 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
312 try {
313 mPendingIntent.send(mContext, 0, statusChanged, null, null);
314 } catch (PendingIntent.CanceledException e) {
315 return false;
316 }
317 }
318 return true;
319 }
320
321 public boolean callLocationChangedLocked(Location location) {
322 if (mListener != null) {
323 try {
324 mListener.onLocationChanged(location);
325 } catch (RemoteException e) {
326 return false;
327 }
328 } else {
329 Intent locationChanged = new Intent();
330 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, location);
331 try {
332 mPendingIntent.send(mContext, 0, locationChanged, null, null);
333 } catch (PendingIntent.CanceledException e) {
334 return false;
335 }
336 }
337 return true;
338 }
339
340 public void binderDied() {
341 if (Config.LOGD) {
342 Log.d(TAG, "Location listener died");
343 }
344 synchronized (mLocationListeners) {
345 removeUpdatesLocked(this);
346 }
347 }
348 }
349
350 private Location readLastKnownLocationLocked(String provider) {
351 Location location = null;
352 String s = null;
353 try {
354 File f = new File(LocationManager.SYSTEM_DIR + "/location."
355 + provider);
356 if (!f.exists()) {
357 return null;
358 }
359 BufferedReader reader = new BufferedReader(new FileReader(f), 256);
360 s = reader.readLine();
361 } catch (IOException e) {
362 Log.w(TAG, "Unable to read last known location", e);
363 }
364
365 if (s == null) {
366 return null;
367 }
368 try {
369 String[] tokens = PATTERN_COMMA.split(s);
370 int idx = 0;
371 long time = Long.parseLong(tokens[idx++]);
372 double latitude = Double.parseDouble(tokens[idx++]);
373 double longitude = Double.parseDouble(tokens[idx++]);
374 double altitude = Double.parseDouble(tokens[idx++]);
375 float bearing = Float.parseFloat(tokens[idx++]);
376 float speed = Float.parseFloat(tokens[idx++]);
377
378 location = new Location(provider);
379 location.setTime(time);
380 location.setLatitude(latitude);
381 location.setLongitude(longitude);
382 location.setAltitude(altitude);
383 location.setBearing(bearing);
384 location.setSpeed(speed);
385 } catch (NumberFormatException nfe) {
386 Log.e(TAG, "NumberFormatException reading last known location", nfe);
387 return null;
388 }
389
390 return location;
391 }
392
393 private void writeLastKnownLocationLocked(String provider,
394 Location location) {
395 long now = SystemClock.elapsedRealtime();
396 Long last = mLastWriteTime.get(provider);
397 if ((last != null)
398 && (now - last.longValue() < MIN_LAST_KNOWN_LOCATION_TIME)) {
399 return;
400 }
401 mLastWriteTime.put(provider, now);
402
403 StringBuilder sb = new StringBuilder(100);
404 sb.append(location.getTime());
405 sb.append(',');
406 sb.append(location.getLatitude());
407 sb.append(',');
408 sb.append(location.getLongitude());
409 sb.append(',');
410 sb.append(location.getAltitude());
411 sb.append(',');
412 sb.append(location.getBearing());
413 sb.append(',');
414 sb.append(location.getSpeed());
415
416 FileWriter writer = null;
417 try {
418 File d = new File(LocationManager.SYSTEM_DIR);
419 if (!d.exists()) {
420 if (!d.mkdirs()) {
421 Log.w(TAG, "Unable to create directory to write location");
422 return;
423 }
424 }
425 File f = new File(LocationManager.SYSTEM_DIR + "/location." + provider);
426 writer = new FileWriter(f);
427 writer.write(sb.toString());
428 } catch (IOException e) {
429 Log.w(TAG, "Unable to write location", e);
430 } finally {
431 if (writer != null) {
432 try {
433 writer.close();
434 } catch (IOException e) {
435 Log.w(TAG, "Exception closing file", e);
436 }
437 }
438 }
439 }
440
441 /**
442 * Load providers from /data/location/<provider_name>/
443 * class
444 * kml
445 * nmea
446 * track
447 * location
448 * properties
449 */
450 private void loadProviders() {
451 synchronized (mLocationListeners) {
452 if (sProvidersLoaded) {
453 return;
454 }
455
456 // Load providers
457 loadProvidersLocked();
458 sProvidersLoaded = true;
459 }
460 }
461
462 private void loadProvidersLocked() {
463 try {
464 _loadProvidersLocked();
465 } catch (Exception e) {
466 Log.e(TAG, "Exception loading providers:", e);
467 }
468 }
469
470 private void _loadProvidersLocked() {
471 // Attempt to load "real" providers first
472 if (GpsLocationProvider.isSupported()) {
473 // Create a gps location provider
474 mGpsLocationProvider = new GpsLocationProvider(mContext);
475 LocationProviderImpl.addProvider(mGpsLocationProvider);
476 }
477
478 // Load fake providers if real providers are not available
479 File f = new File(LocationManager.PROVIDER_DIR);
480 if (f.isDirectory()) {
481 File[] subdirs = f.listFiles();
482 for (int i = 0; i < subdirs.length; i++) {
483 if (!subdirs[i].isDirectory()) {
484 continue;
485 }
486
487 String name = subdirs[i].getName();
488
489 if (Config.LOGD) {
490 Log.d(TAG, "Found dir " + subdirs[i].getAbsolutePath());
491 Log.d(TAG, "name = " + name);
492 }
493
494 // Don't create a fake provider if a real provider exists
495 if (LocationProviderImpl.getProvider(name) == null) {
496 LocationProviderImpl provider = null;
497 try {
498 File classFile = new File(subdirs[i], "class");
499 // Look for a 'class' file
500 provider = LocationProviderImpl.loadFromClass(classFile);
501
502 // Look for an 'kml', 'nmea', or 'track' file
503 if (provider == null) {
504 // Load properties from 'properties' file, if present
505 File propertiesFile = new File(subdirs[i], "properties");
506
507 if (propertiesFile.exists()) {
508 provider = new TrackProvider(name);
509 ((TrackProvider)provider).readProperties(propertiesFile);
510
511 File kmlFile = new File(subdirs[i], "kml");
512 if (kmlFile.exists()) {
513 ((TrackProvider) provider).readKml(kmlFile);
514 } else {
515 File nmeaFile = new File(subdirs[i], "nmea");
516 if (nmeaFile.exists()) {
517 ((TrackProvider) provider).readNmea(name, nmeaFile);
518 } else {
519 File trackFile = new File(subdirs[i], "track");
520 if (trackFile.exists()) {
521 ((TrackProvider) provider).readTrack(trackFile);
522 }
523 }
524 }
525 }
526 }
527 if (provider != null) {
528 LocationProviderImpl.addProvider(provider);
529 }
530 // Grab the initial location of a TrackProvider and
531 // store it as the last known location for that provider
532 if (provider instanceof TrackProvider) {
533 TrackProvider tp = (TrackProvider) provider;
534 mLastKnownLocation.put(tp.getName(), tp.getInitialLocation());
535 }
536 } catch (Exception e) {
537 Log.e(TAG, "Exception loading provder " + name, e);
538 }
539 }
540 }
541 }
542
543 updateProvidersLocked();
544 }
545
546 /**
547 * @param context the context that the LocationManagerService runs in
548 */
549 public LocationManagerService(Context context) {
550 super();
551 mContext = context;
552 mLocationHandler = new LocationWorkerHandler();
553
554 if (Config.LOGD) {
555 Log.d(TAG, "Constructed LocationManager Service");
556 }
557
558 // Alarm manager, needs to be done before calling loadProviders() below
559 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
560
561 // Create a wake lock, needs to be done before calling loadProviders() below
562 PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
563 mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
564
565 // Battery statistics service to be notified when GPS turns on or off
566 mBatteryStats = BatteryStatsService.getService();
567
568 // Load providers
569 loadProviders();
570
571 // Listen for Radio changes
572 mTelephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
573 mTelephonyManager.listen(mPhoneStateListener,
574 PhoneStateListener.LISTEN_CELL_LOCATION |
575 PhoneStateListener.LISTEN_SIGNAL_STRENGTH |
576 PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
577
578 // Register for Network (Wifi or Mobile) updates
579 NetworkStateBroadcastReceiver networkReceiver = new NetworkStateBroadcastReceiver();
580 IntentFilter networkIntentFilter = new IntentFilter();
581 networkIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
582 networkIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
583 networkIntentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
584 networkIntentFilter.addAction(GpsLocationProvider.GPS_ENABLED_CHANGE_ACTION);
585 context.registerReceiver(networkReceiver, networkIntentFilter);
586
587 // Register for power updates
588 PowerStateBroadcastReceiver powerStateReceiver = new PowerStateBroadcastReceiver();
589 IntentFilter intentFilter = new IntentFilter();
590 intentFilter.addAction(ALARM_INTENT);
591 intentFilter.addAction(Intent.ACTION_SCREEN_OFF);
592 intentFilter.addAction(Intent.ACTION_SCREEN_ON);
593 intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
594 intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
595 intentFilter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
596 context.registerReceiver(powerStateReceiver, intentFilter);
597
598 // Get the wifi manager
599 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
600
601 // Create a wifi lock for future use
602 mWifiLock = getWifiWakelockLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800603 }
604
605 public void setInstallCallback(InstallCallback callback) {
606 synchronized (mLocationListeners) {
607 mLocationHandler.removeMessages(MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER);
608 Message m = Message.obtain(mLocationHandler,
609 MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER, callback);
610 mLocationHandler.sendMessageAtFrontOfQueue(m);
611 }
612 }
613
614 public void setNetworkLocationProvider(INetworkLocationProvider provider) {
615 synchronized (mLocationListeners) {
616 mNetworkLocationInterface = provider;
617 provider.addListener(getPackageNames());
618 mNetworkLocationProvider = (LocationProviderImpl)provider;
619 LocationProviderImpl.addProvider(mNetworkLocationProvider);
620 updateProvidersLocked();
The Android Open Source Project4df24232009-03-05 14:34:35 -0800621
622 // notify NetworkLocationProvider of any events it might have missed
623 synchronized (mLocationListeners) {
624 mNetworkLocationProvider.updateNetworkState(mNetworkState);
625 mNetworkLocationInterface.updateWifiEnabledState(mWifiEnabled);
626 mNetworkLocationInterface.updateCellLockStatus(mCellWakeLockAcquired);
627
628 if (mLastCellState != null) {
629 if (mCollector != null) {
630 mCollector.updateCellState(mLastCellState);
631 }
632 mNetworkLocationProvider.updateCellState(mLastCellState);
633 }
634
635 // There might be an existing wifi scan available
636 if (mWifiManager != null) {
637 List<ScanResult> wifiScanResults = mWifiManager.getScanResults();
638 if (wifiScanResults != null && wifiScanResults.size() != 0) {
639 mNetworkLocationInterface.updateWifiScanResults(wifiScanResults);
640 if (mCollector != null) {
641 mCollector.updateWifiScanResults(wifiScanResults);
642 }
643 }
644 }
645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 }
647 }
648
649 public void setLocationCollector(ILocationCollector collector) {
650 synchronized (mLocationListeners) {
651 mCollector = collector;
652 if (mGpsLocationProvider != null) {
653 mGpsLocationProvider.setLocationCollector(mCollector);
654 }
655 }
656 }
657
658 private WifiManager.WifiLock getWifiWakelockLocked() {
659 if (mWifiLock == null && mWifiManager != null) {
660 mWifiLock = mWifiManager.createWifiLock(WifiManager.WIFI_MODE_SCAN_ONLY, WIFILOCK_KEY);
661 mWifiLock.setReferenceCounted(false);
662 }
663 return mWifiLock;
664 }
665
666 private boolean isAllowedBySettingsLocked(String provider) {
667 if (mEnabledProviders.contains(provider)) {
668 return true;
669 }
670 if (mDisabledProviders.contains(provider)) {
671 return false;
672 }
673 // Use system settings
674 ContentResolver resolver = mContext.getContentResolver();
675 String allowedProviders = Settings.Secure.getString(resolver,
676 Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
677
678 return ((allowedProviders != null) && (allowedProviders.contains(provider)));
679 }
680
681 private void checkPermissionsSafe(String provider) {
682 if (LocationManager.GPS_PROVIDER.equals(provider)
683 && (mContext.checkCallingPermission(ACCESS_FINE_LOCATION)
684 != PackageManager.PERMISSION_GRANTED)) {
685 throw new SecurityException("Requires ACCESS_FINE_LOCATION permission");
686 }
687 if (LocationManager.NETWORK_PROVIDER.equals(provider)
688 && (mContext.checkCallingPermission(ACCESS_FINE_LOCATION)
689 != PackageManager.PERMISSION_GRANTED)
690 && (mContext.checkCallingPermission(ACCESS_COARSE_LOCATION)
691 != PackageManager.PERMISSION_GRANTED)) {
692 throw new SecurityException(
693 "Requires ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission");
694 }
695 }
696
697 private boolean isAllowedProviderSafe(String provider) {
698 if (LocationManager.GPS_PROVIDER.equals(provider)
699 && (mContext.checkCallingPermission(ACCESS_FINE_LOCATION)
700 != PackageManager.PERMISSION_GRANTED)) {
701 return false;
702 }
703 if (LocationManager.NETWORK_PROVIDER.equals(provider)
704 && (mContext.checkCallingPermission(ACCESS_FINE_LOCATION)
705 != PackageManager.PERMISSION_GRANTED)
706 && (mContext.checkCallingPermission(ACCESS_COARSE_LOCATION)
707 != PackageManager.PERMISSION_GRANTED)) {
708 return false;
709 }
710
711 return true;
712 }
713
714 private String[] getPackageNames() {
715 // Since a single UID may correspond to multiple packages, this can only be used as an
716 // approximation for tracking
717 return mContext.getPackageManager().getPackagesForUid(Binder.getCallingUid());
718 }
719
720 public List<String> getAllProviders() {
721 try {
722 synchronized (mLocationListeners) {
723 return _getAllProvidersLocked();
724 }
725 } catch (SecurityException se) {
726 throw se;
727 } catch (Exception e) {
728 Log.e(TAG, "getAllProviders got exception:", e);
729 return null;
730 }
731 }
732
733 private List<String> _getAllProvidersLocked() {
734 if (Config.LOGD) {
735 Log.d(TAG, "getAllProviders");
736 }
737 List<LocationProviderImpl> providers = LocationProviderImpl.getProviders();
738 ArrayList<String> out = new ArrayList<String>(providers.size());
739
740 for (LocationProviderImpl p : providers) {
741 out.add(p.getName());
742 }
743 return out;
744 }
745
746 public List<String> getProviders(boolean enabledOnly) {
747 try {
748 synchronized (mLocationListeners) {
749 return _getProvidersLocked(enabledOnly);
750 }
751 } catch (SecurityException se) {
752 throw se;
753 } catch (Exception e) {
754 Log.e(TAG, "getProviders gotString exception:", e);
755 return null;
756 }
757 }
758
759 private List<String> _getProvidersLocked(boolean enabledOnly) {
760 if (Config.LOGD) {
761 Log.d(TAG, "getProviders");
762 }
763 List<LocationProviderImpl> providers = LocationProviderImpl.getProviders();
764 ArrayList<String> out = new ArrayList<String>();
765
766 for (LocationProviderImpl p : providers) {
767 String name = p.getName();
768 if (isAllowedProviderSafe(name)) {
769 if (enabledOnly && !isAllowedBySettingsLocked(name)) {
770 continue;
771 }
772 out.add(name);
773 }
774 }
775 return out;
776 }
777
778 public void updateProviders() {
779 synchronized (mLocationListeners) {
780 updateProvidersLocked();
781 }
782 }
783
784 private void updateProvidersLocked() {
785 for (LocationProviderImpl p : LocationProviderImpl.getProviders()) {
786 boolean isEnabled = p.isEnabled();
787 String name = p.getName();
788 boolean shouldBeEnabled = isAllowedBySettingsLocked(name);
789
790 // Collection is only allowed when network provider is being used
791 if (mCollector != null &&
792 p.getName().equals(LocationManager.NETWORK_PROVIDER)) {
793 mCollector.updateNetworkProviderStatus(shouldBeEnabled);
794 }
795
796 if (isEnabled && !shouldBeEnabled) {
797 updateProviderListenersLocked(name, false);
798 } else if (!isEnabled && shouldBeEnabled) {
799 updateProviderListenersLocked(name, true);
800 }
801
802 }
803 }
804
805 private void updateProviderListenersLocked(String provider, boolean enabled) {
806 int listeners = 0;
807
808 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
809 if (p == null) {
810 return;
811 }
812
813 ArrayList<Receiver> deadReceivers = null;
814
815 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
816 if (records != null) {
817 final int N = records.size();
818 for (int i=0; i<N; i++) {
819 UpdateRecord record = records.get(i);
820 // Sends a notification message to the receiver
821 try {
822 Receiver receiver = record.mReceiver;
823 if (receiver.isListener()) {
824 if (enabled) {
825 receiver.getListener().onProviderEnabled(provider);
826 } else {
827 receiver.getListener().onProviderDisabled(provider);
828 }
829 } else {
830 Intent providerIntent = new Intent();
831 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
832 try {
833 receiver.getPendingIntent().send(mContext, 0,
834 providerIntent, null, null);
835 } catch (PendingIntent.CanceledException e) {
836 if (deadReceivers == null) {
837 deadReceivers = new ArrayList<Receiver>();
838 deadReceivers.add(receiver);
839 }
840 }
841 }
842 } catch (RemoteException e) {
843 // The death link will clean this up.
844 }
845 listeners++;
846 }
847 }
848
849 if (deadReceivers != null) {
850 for (int i=deadReceivers.size()-1; i>=0; i--) {
851 removeUpdatesLocked(deadReceivers.get(i));
852 }
853 }
854
855 if (enabled) {
856 p.enable();
857 if (listeners > 0) {
858 p.setMinTime(getMinTimeLocked(provider));
859 p.enableLocationTracking(true);
860 updateWakelockStatusLocked(mScreenOn);
861 }
862 } else {
863 p.enableLocationTracking(false);
864 if (p == mGpsLocationProvider) {
865 mGpsNavigating = false;
866 reportStopGpsLocked();
867 }
868 p.disable();
869 updateWakelockStatusLocked(mScreenOn);
870 }
871
872 if (enabled && listeners > 0) {
873 mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider);
874 Message m = Message.obtain(mLocationHandler, MESSAGE_HEARTBEAT, provider);
875 mLocationHandler.sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000);
876 } else {
877 mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider);
878 }
879 }
880
881 private long getMinTimeLocked(String provider) {
882 long minTime = Long.MAX_VALUE;
883 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
884 if (records != null) {
885 for (int i=records.size()-1; i>=0; i--) {
886 minTime = Math.min(minTime, records.get(i).mMinTime);
887 }
888 }
889 return minTime;
890 }
891
892 private class UpdateRecord {
893 final String mProvider;
894 final Receiver mReceiver;
895 final long mMinTime;
896 final float mMinDistance;
897 final int mUid;
898 final String[] mPackages;
899
900 /**
901 * Note: must be constructed with lock held.
902 */
903 UpdateRecord(String provider, long minTime, float minDistance,
904 Receiver receiver, int uid, String[] packages) {
905 mProvider = provider;
906 mReceiver = receiver;
907 mMinTime = minTime;
908 mMinDistance = minDistance;
909 mUid = uid;
910 mPackages = packages;
911
912 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
913 if (records == null) {
914 records = new ArrayList<UpdateRecord>();
915 mRecordsByProvider.put(provider, records);
916 }
917 if (!records.contains(this)) {
918 records.add(this);
919 }
920 }
921
922 /**
923 * Method to be called when a record will no longer be used. Calling this multiple times
924 * must have the same effect as calling it once.
925 */
926 void disposeLocked() {
927 ArrayList<UpdateRecord> records = mRecordsByProvider.get(this.mProvider);
928 records.remove(this);
929 }
930
931 @Override
932 public String toString() {
933 return "UpdateRecord{"
934 + Integer.toHexString(System.identityHashCode(this))
935 + " " + mProvider + " " + mReceiver + "}";
936 }
937
938 void dump(PrintWriter pw, String prefix) {
939 pw.println(prefix + this);
940 pw.println(prefix + "mProvider=" + mProvider + " mReceiver=" + mReceiver);
941 pw.println(prefix + "mMinTime=" + mMinTime + " mMinDistance=" + mMinDistance);
942 StringBuilder sb = new StringBuilder();
943 if (mPackages != null) {
944 for (int i=0; i<mPackages.length; i++) {
945 if (i > 0) sb.append(", ");
946 sb.append(mPackages[i]);
947 }
948 }
949 pw.println(prefix + "mUid=" + mUid + " mPackages=" + sb);
950 }
951
952 /**
953 * Calls dispose().
954 */
955 @Override protected void finalize() {
956 synchronized (mLocationListeners) {
957 disposeLocked();
958 }
959 }
960 }
961
962 public void requestLocationUpdates(String provider,
963 long minTime, float minDistance, ILocationListener listener) {
964
965 try {
966 synchronized (mLocationListeners) {
967 requestLocationUpdatesLocked(provider, minTime, minDistance,
968 new Receiver(listener, Binder.getCallingUid()));
969 }
970 } catch (SecurityException se) {
971 throw se;
972 } catch (Exception e) {
973 Log.e(TAG, "requestUpdates got exception:", e);
974 }
975 }
976
977 public void requestLocationUpdatesPI(String provider,
978 long minTime, float minDistance, PendingIntent intent) {
979 try {
980 synchronized (mLocationListeners) {
981 requestLocationUpdatesLocked(provider, minTime, minDistance,
982 new Receiver(intent, Binder.getCallingUid()));
983 }
984 } catch (SecurityException se) {
985 throw se;
986 } catch (Exception e) {
987 Log.e(TAG, "requestUpdates got exception:", e);
988 }
989 }
990
991 private void requestLocationUpdatesLocked(String provider,
992 long minTime, float minDistance, Receiver receiver) {
993 if (Config.LOGD) {
994 Log.d(TAG, "_requestLocationUpdates: listener = " + receiver);
995 }
996
997 LocationProviderImpl impl = LocationProviderImpl.getProvider(provider);
998 if (impl == null) {
999 throw new IllegalArgumentException("provider=" + provider);
1000 }
1001
1002 checkPermissionsSafe(provider);
1003
1004 String[] packages = getPackageNames();
1005
1006 // so wakelock calls will succeed
1007 final int callingUid = Binder.getCallingUid();
1008 long identity = Binder.clearCallingIdentity();
1009 try {
1010 UpdateRecord r = new UpdateRecord(provider, minTime, minDistance,
1011 receiver, callingUid, packages);
1012 if (!mListeners.contains(receiver)) {
1013 try {
1014 if (receiver.isListener()) {
1015 receiver.getListener().asBinder().linkToDeath(receiver, 0);
1016 }
1017 mListeners.add(receiver);
1018 } catch (RemoteException e) {
1019 return;
1020 }
1021 }
1022
1023 HashMap<String,UpdateRecord> records = mLocationListeners.get(receiver);
1024 if (records == null) {
1025 records = new HashMap<String,UpdateRecord>();
1026 mLocationListeners.put(receiver, records);
1027 }
1028 UpdateRecord oldRecord = records.put(provider, r);
1029 if (oldRecord != null) {
1030 oldRecord.disposeLocked();
1031 }
1032
1033 boolean isProviderEnabled = isAllowedBySettingsLocked(provider);
1034 if (isProviderEnabled) {
1035 long minTimeForProvider = getMinTimeLocked(provider);
1036 impl.setMinTime(minTimeForProvider);
1037 impl.enableLocationTracking(true);
1038 updateWakelockStatusLocked(mScreenOn);
1039
1040 if (provider.equals(LocationManager.GPS_PROVIDER)) {
1041 if (mGpsNavigating) {
1042 updateReportedGpsLocked();
1043 }
1044 }
1045
1046 // Clear heartbeats if any before starting a new one
1047 mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider);
1048 Message m = Message.obtain(mLocationHandler, MESSAGE_HEARTBEAT, provider);
1049 mLocationHandler.sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000);
1050 } else {
1051 try {
1052 // Notify the listener that updates are currently disabled
1053 if (receiver.isListener()) {
1054 receiver.getListener().onProviderDisabled(provider);
1055 }
1056 } catch(RemoteException e) {
1057 Log.w(TAG, "RemoteException calling onProviderDisabled on " +
1058 receiver.getListener());
1059 }
1060 }
1061 } finally {
1062 Binder.restoreCallingIdentity(identity);
1063 }
1064 }
1065
1066 public void removeUpdates(ILocationListener listener) {
1067 try {
1068 synchronized (mLocationListeners) {
1069 removeUpdatesLocked(new Receiver(listener, Binder.getCallingUid()));
1070 }
1071 } catch (SecurityException se) {
1072 throw se;
1073 } catch (Exception e) {
1074 Log.e(TAG, "removeUpdates got exception:", e);
1075 }
1076 }
1077
1078 public void removeUpdatesPI(PendingIntent intent) {
1079 try {
1080 synchronized (mLocationListeners) {
1081 removeUpdatesLocked(new Receiver(intent, Binder.getCallingUid()));
1082 }
1083 } catch (SecurityException se) {
1084 throw se;
1085 } catch (Exception e) {
1086 Log.e(TAG, "removeUpdates got exception:", e);
1087 }
1088 }
1089
1090 private void removeUpdatesLocked(Receiver receiver) {
1091 if (Config.LOGD) {
1092 Log.d(TAG, "_removeUpdates: listener = " + receiver);
1093 }
1094
1095 // so wakelock calls will succeed
1096 final int callingUid = Binder.getCallingUid();
1097 long identity = Binder.clearCallingIdentity();
1098 try {
1099 int idx = mListeners.indexOf(receiver);
1100 if (idx >= 0) {
1101 Receiver myReceiver = mListeners.remove(idx);
1102 if (myReceiver.isListener()) {
1103 myReceiver.getListener().asBinder().unlinkToDeath(myReceiver, 0);
1104 }
1105 }
1106
1107 // Record which providers were associated with this listener
1108 HashSet<String> providers = new HashSet<String>();
1109 HashMap<String,UpdateRecord> oldRecords = mLocationListeners.get(receiver);
1110 if (oldRecords != null) {
1111 // Call dispose() on the obsolete update records.
1112 for (UpdateRecord record : oldRecords.values()) {
1113 if (record.mProvider.equals(LocationManager.NETWORK_PROVIDER)) {
1114 if (mNetworkLocationInterface != null) {
1115 mNetworkLocationInterface.removeListener(record.mPackages);
1116 }
1117 }
1118 record.disposeLocked();
1119 }
1120 // Accumulate providers
1121 providers.addAll(oldRecords.keySet());
1122 }
1123
1124 mLocationListeners.remove(receiver);
1125 mLastFixBroadcast.remove(receiver);
1126 mLastStatusBroadcast.remove(receiver);
1127
1128 // See if the providers associated with this listener have any
1129 // other listeners; if one does, inform it of the new smallest minTime
1130 // value; if one does not, disable location tracking for it
1131 for (String provider : providers) {
1132 // If provider is already disabled, don't need to do anything
1133 if (!isAllowedBySettingsLocked(provider)) {
1134 continue;
1135 }
1136
1137 boolean hasOtherListener = false;
1138 ArrayList<UpdateRecord> recordsForProvider = mRecordsByProvider.get(provider);
1139 if (recordsForProvider != null && recordsForProvider.size() > 0) {
1140 hasOtherListener = true;
1141 }
1142
1143 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
1144 if (p != null) {
1145 if (hasOtherListener) {
1146 p.setMinTime(getMinTimeLocked(provider));
1147 } else {
1148 mLocationHandler.removeMessages(MESSAGE_HEARTBEAT, provider);
1149 p.enableLocationTracking(false);
1150 }
1151
1152 if (p == mGpsLocationProvider && mGpsNavigating) {
1153 updateReportedGpsLocked();
1154 }
1155 }
1156 }
1157
1158 updateWakelockStatusLocked(mScreenOn);
1159 } finally {
1160 Binder.restoreCallingIdentity(identity);
1161 }
1162 }
1163
1164 public boolean addGpsStatusListener(IGpsStatusListener listener) {
1165 if (mGpsLocationProvider == null) {
1166 return false;
1167 }
1168 if (mContext.checkCallingPermission(ACCESS_FINE_LOCATION) !=
1169 PackageManager.PERMISSION_GRANTED) {
1170 throw new SecurityException("Requires ACCESS_FINE_LOCATION permission");
1171 }
1172
1173 try {
1174 mGpsLocationProvider.addGpsStatusListener(listener);
1175 } catch (RemoteException e) {
1176 Log.w(TAG, "RemoteException in addGpsStatusListener");
1177 return false;
1178 }
1179 return true;
1180 }
1181
1182 public void removeGpsStatusListener(IGpsStatusListener listener) {
1183 synchronized (mLocationListeners) {
1184 mGpsLocationProvider.removeGpsStatusListener(listener);
1185 }
1186 }
1187
1188 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
1189 // first check for permission to the provider
1190 checkPermissionsSafe(provider);
1191 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
1192 if ((mContext.checkCallingPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
1193 != PackageManager.PERMISSION_GRANTED)) {
1194 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1195 }
1196
1197 synchronized (mLocationListeners) {
1198 LocationProviderImpl impl = LocationProviderImpl.getProvider(provider);
1199 if (provider == null) {
1200 return false;
1201 }
1202
1203 return impl.sendExtraCommand(command, extras);
1204 }
1205 }
1206
1207 class ProximityAlert {
1208 final int mUid;
1209 final double mLatitude;
1210 final double mLongitude;
1211 final float mRadius;
1212 final long mExpiration;
1213 final PendingIntent mIntent;
1214 final Location mLocation;
1215
1216 public ProximityAlert(int uid, double latitude, double longitude,
1217 float radius, long expiration, PendingIntent intent) {
1218 mUid = uid;
1219 mLatitude = latitude;
1220 mLongitude = longitude;
1221 mRadius = radius;
1222 mExpiration = expiration;
1223 mIntent = intent;
1224
1225 mLocation = new Location("");
1226 mLocation.setLatitude(latitude);
1227 mLocation.setLongitude(longitude);
1228 }
1229
1230 long getExpiration() {
1231 return mExpiration;
1232 }
1233
1234 PendingIntent getIntent() {
1235 return mIntent;
1236 }
1237
1238 boolean isInProximity(double latitude, double longitude) {
1239 Location loc = new Location("");
1240 loc.setLatitude(latitude);
1241 loc.setLongitude(longitude);
1242
1243 double radius = loc.distanceTo(mLocation);
1244 return radius <= mRadius;
1245 }
1246
1247 @Override
1248 public String toString() {
1249 return "ProximityAlert{"
1250 + Integer.toHexString(System.identityHashCode(this))
1251 + " uid " + mUid + mIntent + "}";
1252 }
1253
1254 void dump(PrintWriter pw, String prefix) {
1255 pw.println(prefix + this);
1256 pw.println(prefix + "mLatitude=" + mLatitude + " mLongitude=" + mLongitude);
1257 pw.println(prefix + "mRadius=" + mRadius + " mExpiration=" + mExpiration);
1258 pw.println(prefix + "mIntent=" + mIntent);
1259 pw.println(prefix + "mLocation:");
1260 mLocation.dump(new PrintWriterPrinter(pw), prefix + " ");
1261 }
1262 }
1263
1264 // Listener for receiving locations to trigger proximity alerts
1265 class ProximityListener extends ILocationListener.Stub {
1266
1267 boolean isGpsAvailable = false;
1268
1269 // Note: this is called with the lock held.
1270 public void onLocationChanged(Location loc) {
1271
1272 // If Gps is available, then ignore updates from NetworkLocationProvider
1273 if (loc.getProvider().equals(LocationManager.GPS_PROVIDER)) {
1274 isGpsAvailable = true;
1275 }
1276 if (isGpsAvailable && loc.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
1277 return;
1278 }
1279
1280 // Process proximity alerts
1281 long now = System.currentTimeMillis();
1282 double latitude = loc.getLatitude();
1283 double longitude = loc.getLongitude();
1284 ArrayList<PendingIntent> intentsToRemove = null;
1285
1286 for (ProximityAlert alert : mProximityAlerts.values()) {
1287 PendingIntent intent = alert.getIntent();
1288 long expiration = alert.getExpiration();
1289
1290 if ((expiration == -1) || (now <= expiration)) {
1291 boolean entered = mProximitiesEntered.contains(alert);
1292 boolean inProximity =
1293 alert.isInProximity(latitude, longitude);
1294 if (!entered && inProximity) {
1295 if (Config.LOGD) {
1296 Log.i(TAG, "Entered alert");
1297 }
1298 mProximitiesEntered.add(alert);
1299 Intent enteredIntent = new Intent();
1300 enteredIntent.putExtra(LocationManager.KEY_PROXIMITY_ENTERING, true);
1301 try {
1302 intent.send(mContext, 0, enteredIntent, null, null);
1303 } catch (PendingIntent.CanceledException e) {
1304 if (Config.LOGD) {
1305 Log.i(TAG, "Canceled proximity alert: " + alert, e);
1306 }
1307 if (intentsToRemove == null) {
1308 intentsToRemove = new ArrayList<PendingIntent>();
1309 }
1310 intentsToRemove.add(intent);
1311 }
1312 } else if (entered && !inProximity) {
1313 if (Config.LOGD) {
1314 Log.i(TAG, "Exited alert");
1315 }
1316 mProximitiesEntered.remove(alert);
1317 Intent exitedIntent = new Intent();
1318 exitedIntent.putExtra(LocationManager.KEY_PROXIMITY_ENTERING, false);
1319 try {
1320 intent.send(mContext, 0, exitedIntent, null, null);
1321 } catch (PendingIntent.CanceledException e) {
1322 if (Config.LOGD) {
1323 Log.i(TAG, "Canceled proximity alert: " + alert, e);
1324 }
1325 if (intentsToRemove == null) {
1326 intentsToRemove = new ArrayList<PendingIntent>();
1327 }
1328 intentsToRemove.add(intent);
1329 }
1330 }
1331 } else {
1332 // Mark alert for expiration
1333 if (Config.LOGD) {
1334 Log.i(TAG, "Expiring proximity alert: " + alert);
1335 }
1336 if (intentsToRemove == null) {
1337 intentsToRemove = new ArrayList<PendingIntent>();
1338 }
1339 intentsToRemove.add(alert.getIntent());
1340 }
1341 }
1342
1343 // Remove expired alerts
1344 if (intentsToRemove != null) {
1345 for (PendingIntent i : intentsToRemove) {
1346 mProximityAlerts.remove(i);
1347 ProximityAlert alert = mProximityAlerts.get(i);
1348 mProximitiesEntered.remove(alert);
1349 }
1350 }
1351
1352 }
1353
1354 // Note: this is called with the lock held.
1355 public void onProviderDisabled(String provider) {
1356 if (provider.equals(LocationManager.GPS_PROVIDER)) {
1357 isGpsAvailable = false;
1358 }
1359 }
1360
1361 // Note: this is called with the lock held.
1362 public void onProviderEnabled(String provider) {
1363 // ignore
1364 }
1365
1366 // Note: this is called with the lock held.
1367 public void onStatusChanged(String provider, int status, Bundle extras) {
1368 if ((provider.equals(LocationManager.GPS_PROVIDER)) &&
1369 (status != LocationProvider.AVAILABLE)) {
1370 isGpsAvailable = false;
1371 }
1372 }
1373 }
1374
1375 public void addProximityAlert(double latitude, double longitude,
1376 float radius, long expiration, PendingIntent intent) {
1377 try {
1378 synchronized (mLocationListeners) {
1379 addProximityAlertLocked(latitude, longitude, radius, expiration, intent);
1380 }
1381 } catch (SecurityException se) {
1382 throw se;
1383 } catch (Exception e) {
1384 Log.e(TAG, "addProximityAlert got exception:", e);
1385 }
1386 }
1387
1388 private void addProximityAlertLocked(double latitude, double longitude,
1389 float radius, long expiration, PendingIntent intent) {
1390 if (Config.LOGD) {
1391 Log.d(TAG, "addProximityAlert: latitude = " + latitude +
1392 ", longitude = " + longitude +
1393 ", expiration = " + expiration +
1394 ", intent = " + intent);
1395 }
1396
1397 // Require ability to access all providers for now
1398 if (!isAllowedProviderSafe(LocationManager.GPS_PROVIDER) ||
1399 !isAllowedProviderSafe(LocationManager.NETWORK_PROVIDER)) {
1400 throw new SecurityException("Requires ACCESS_FINE_LOCATION permission");
1401 }
1402
1403 if (expiration != -1) {
1404 expiration += System.currentTimeMillis();
1405 }
1406 ProximityAlert alert = new ProximityAlert(Binder.getCallingUid(),
1407 latitude, longitude, radius, expiration, intent);
1408 mProximityAlerts.put(intent, alert);
1409
1410 if (mProximityListener == null) {
1411 mProximityListener = new Receiver(new ProximityListener(), -1);
1412
1413 LocationProvider provider = LocationProviderImpl.getProvider(
1414 LocationManager.GPS_PROVIDER);
1415 if (provider != null) {
1416 requestLocationUpdatesLocked(provider.getName(), 1000L, 1.0f, mProximityListener);
1417 }
1418
1419 provider =
1420 LocationProviderImpl.getProvider(LocationManager.NETWORK_PROVIDER);
1421 if (provider != null) {
1422 requestLocationUpdatesLocked(provider.getName(), 1000L, 1.0f, mProximityListener);
1423 }
1424 } else if (mGpsNavigating) {
1425 updateReportedGpsLocked();
1426 }
1427 }
1428
1429 public void removeProximityAlert(PendingIntent intent) {
1430 try {
1431 synchronized (mLocationListeners) {
1432 removeProximityAlertLocked(intent);
1433 }
1434 } catch (SecurityException se) {
1435 throw se;
1436 } catch (Exception e) {
1437 Log.e(TAG, "removeProximityAlert got exception:", e);
1438 }
1439 }
1440
1441 private void removeProximityAlertLocked(PendingIntent intent) {
1442 if (Config.LOGD) {
1443 Log.d(TAG, "removeProximityAlert: intent = " + intent);
1444 }
1445
1446 mProximityAlerts.remove(intent);
1447 if (mProximityAlerts.size() == 0) {
1448 removeUpdatesLocked(mProximityListener);
1449 mProximityListener = null;
1450 } else if (mGpsNavigating) {
1451 updateReportedGpsLocked();
1452 }
1453 }
1454
1455 /**
1456 * @return null if the provider does not exits
1457 * @throw SecurityException if the provider is not allowed to be
1458 * accessed by the caller
1459 */
1460 public Bundle getProviderInfo(String provider) {
1461 try {
1462 synchronized (mLocationListeners) {
1463 return _getProviderInfoLocked(provider);
1464 }
1465 } catch (SecurityException se) {
1466 throw se;
1467 } catch (Exception e) {
1468 Log.e(TAG, "_getProviderInfo got exception:", e);
1469 return null;
1470 }
1471 }
1472
1473 private Bundle _getProviderInfoLocked(String provider) {
1474 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
1475 if (p == null) {
1476 return null;
1477 }
1478
1479 checkPermissionsSafe(provider);
1480
1481 Bundle b = new Bundle();
1482 b.putBoolean("network", p.requiresNetwork());
1483 b.putBoolean("satellite", p.requiresSatellite());
1484 b.putBoolean("cell", p.requiresCell());
1485 b.putBoolean("cost", p.hasMonetaryCost());
1486 b.putBoolean("altitude", p.supportsAltitude());
1487 b.putBoolean("speed", p.supportsSpeed());
1488 b.putBoolean("bearing", p.supportsBearing());
1489 b.putInt("power", p.getPowerRequirement());
1490 b.putInt("accuracy", p.getAccuracy());
1491
1492 return b;
1493 }
1494
1495 public boolean isProviderEnabled(String provider) {
1496 try {
1497 synchronized (mLocationListeners) {
1498 return _isProviderEnabledLocked(provider);
1499 }
1500 } catch (SecurityException se) {
1501 throw se;
1502 } catch (Exception e) {
1503 Log.e(TAG, "isProviderEnabled got exception:", e);
1504 return false;
1505 }
1506 }
1507
1508 private boolean _isProviderEnabledLocked(String provider) {
1509 checkPermissionsSafe(provider);
1510
1511 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
1512 if (p == null) {
1513 throw new IllegalArgumentException("provider=" + provider);
1514 }
1515 return isAllowedBySettingsLocked(provider);
1516 }
1517
1518 public Location getLastKnownLocation(String provider) {
1519 try {
1520 synchronized (mLocationListeners) {
1521 return _getLastKnownLocationLocked(provider);
1522 }
1523 } catch (SecurityException se) {
1524 throw se;
1525 } catch (Exception e) {
1526 Log.e(TAG, "getLastKnownLocation got exception:", e);
1527 return null;
1528 }
1529 }
1530
1531 private Location _getLastKnownLocationLocked(String provider) {
1532 checkPermissionsSafe(provider);
1533
1534 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
1535 if (p == null) {
1536 throw new IllegalArgumentException("provider=" + provider);
1537 }
1538
1539 if (!isAllowedBySettingsLocked(provider)) {
1540 return null;
1541 }
1542
1543 Location location = mLastKnownLocation.get(provider);
1544 if (location == null) {
1545 // Get the persistent last known location for the provider
1546 location = readLastKnownLocationLocked(provider);
1547 if (location != null) {
1548 mLastKnownLocation.put(provider, location);
1549 }
1550 }
1551
1552 return location;
1553 }
1554
1555 private static boolean shouldBroadcastSafe(Location loc, Location lastLoc, UpdateRecord record) {
1556 // Always broadcast the first update
1557 if (lastLoc == null) {
1558 return true;
1559 }
1560
1561 // Don't broadcast same location again regardless of condition
1562 // TODO - we should probably still rebroadcast if user explicitly sets a minTime > 0
1563 if (loc.getTime() == lastLoc.getTime()) {
1564 return false;
1565 }
1566
1567 // Check whether sufficient distance has been traveled
1568 double minDistance = record.mMinDistance;
1569 if (minDistance > 0.0) {
1570 if (loc.distanceTo(lastLoc) <= minDistance) {
1571 return false;
1572 }
1573 }
1574
1575 return true;
1576 }
1577
1578 private void handleLocationChangedLocked(String provider) {
1579 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1580 if (records == null || records.size() == 0) {
1581 return;
1582 }
1583
1584 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
1585 if (p == null) {
1586 return;
1587 }
1588
1589 // Get location object
1590 Location loc = mLocationsByProvider.get(provider);
1591 if (loc == null) {
1592 loc = new Location(provider);
1593 mLocationsByProvider.put(provider, loc);
1594 } else {
1595 loc.reset();
1596 }
1597
1598 // Use the mock location if available
1599 Location mockLoc = mMockProviderLocation.get(provider);
1600 boolean locationValid;
1601 if (mockLoc != null) {
1602 locationValid = true;
1603 loc.set(mockLoc);
1604 } else {
1605 locationValid = p.getLocation(loc);
1606 }
1607
1608 // Update last known location for provider
1609 if (locationValid) {
1610 Location location = mLastKnownLocation.get(provider);
1611 if (location == null) {
1612 mLastKnownLocation.put(provider, new Location(loc));
1613 } else {
1614 location.set(loc);
1615 }
1616 writeLastKnownLocationLocked(provider, loc);
1617
1618 if (p instanceof INetworkLocationProvider) {
1619 mWakeLockNetworkReceived = true;
1620 } else if (p instanceof GpsLocationProvider) {
1621 // Gps location received signal is in NetworkStateBroadcastReceiver
1622 }
1623 }
1624
1625 // Fetch latest status update time
1626 long newStatusUpdateTime = p.getStatusUpdateTime();
1627
1628 // Override real time with mock time if present
1629 Long mockStatusUpdateTime = mMockProviderStatusUpdateTime.get(provider);
1630 if (mockStatusUpdateTime != null) {
1631 newStatusUpdateTime = mockStatusUpdateTime.longValue();
1632 }
1633
1634 // Get latest status
1635 Bundle extras = new Bundle();
1636 int status = p.getStatus(extras);
1637
1638 // Override status with mock status if present
1639 Integer mockStatus = mMockProviderStatus.get(provider);
1640 if (mockStatus != null) {
1641 status = mockStatus.intValue();
1642 }
1643
1644 // Override extras with mock extras if present
1645 Bundle mockExtras = mMockProviderStatusExtras.get(provider);
1646 if (mockExtras != null) {
1647 extras.clear();
1648 extras.putAll(mockExtras);
1649 }
1650
1651 ArrayList<Receiver> deadReceivers = null;
1652
1653 // Broadcast location or status to all listeners
1654 final int N = records.size();
1655 for (int i=0; i<N; i++) {
1656 UpdateRecord r = records.get(i);
1657 Receiver receiver = r.mReceiver;
1658
1659 // Broadcast location only if it is valid
1660 if (locationValid) {
1661 HashMap<String,Location> map = mLastFixBroadcast.get(receiver);
1662 if (map == null) {
1663 map = new HashMap<String,Location>();
1664 mLastFixBroadcast.put(receiver, map);
1665 }
1666 Location lastLoc = map.get(provider);
1667 if ((lastLoc == null) || shouldBroadcastSafe(loc, lastLoc, r)) {
1668 if (lastLoc == null) {
1669 lastLoc = new Location(loc);
1670 map.put(provider, lastLoc);
1671 } else {
1672 lastLoc.set(loc);
1673 }
1674 if (!receiver.callLocationChangedLocked(loc)) {
1675 Log.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
1676 if (deadReceivers == null) {
1677 deadReceivers = new ArrayList<Receiver>();
1678 }
1679 deadReceivers.add(receiver);
1680 }
1681 }
1682 }
1683
1684 // Broadcast status message
1685 HashMap<String,Long> statusMap = mLastStatusBroadcast.get(receiver);
1686 if (statusMap == null) {
1687 statusMap = new HashMap<String,Long>();
1688 mLastStatusBroadcast.put(receiver, statusMap);
1689 }
1690 long prevStatusUpdateTime =
1691 (statusMap.get(provider) != null) ? statusMap.get(provider) : 0;
1692
1693 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
1694 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
1695
1696 statusMap.put(provider, newStatusUpdateTime);
1697 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
1698 Log.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
1699 if (deadReceivers == null) {
1700 deadReceivers = new ArrayList<Receiver>();
1701 }
1702 if (!deadReceivers.contains(receiver)) {
1703 deadReceivers.add(receiver);
1704 }
1705 }
1706 }
1707 }
1708
1709 if (deadReceivers != null) {
1710 for (int i=deadReceivers.size()-1; i>=0; i--) {
1711 removeUpdatesLocked(deadReceivers.get(i));
1712 }
1713 }
1714 }
1715
1716 private class LocationWorkerHandler extends Handler {
1717
1718 @Override
1719 public void handleMessage(Message msg) {
1720 try {
1721 if (msg.what == MESSAGE_HEARTBEAT) {
1722 // log("LocationWorkerHandler: Heartbeat!");
1723
1724 synchronized (mLocationListeners) {
1725 String provider = (String) msg.obj;
1726 if (!isAllowedBySettingsLocked(provider)) {
1727 return;
1728 }
1729
1730 // Process the location fix if the screen is on or we're holding a wakelock
1731 if (mScreenOn || (mWakeLockAcquireTime != 0)) {
1732 handleLocationChangedLocked(provider);
1733 }
1734
1735 // If it continues to have listeners
1736 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1737 if (records != null && records.size() > 0) {
1738 Message m = Message.obtain(this, MESSAGE_HEARTBEAT, provider);
1739 sendMessageAtTime(m, SystemClock.uptimeMillis() + 1000);
1740 }
1741
1742 if ((mWakeLockAcquireTime != 0) &&
1743 (SystemClock.elapsedRealtime() - mWakeLockAcquireTime
1744 > MAX_TIME_FOR_WAKE_LOCK)) {
1745
1746 removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK);
1747 removeMessages(MESSAGE_RELEASE_WAKE_LOCK);
1748
1749 log("LocationWorkerHandler: Exceeded max time for wake lock");
1750 Message m = Message.obtain(this, MESSAGE_RELEASE_WAKE_LOCK);
1751 sendMessageAtFrontOfQueue(m);
1752
1753 } else if (mWakeLockAcquireTime != 0 &&
1754 mWakeLockGpsReceived && mWakeLockNetworkReceived) {
1755
1756 removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK);
1757 removeMessages(MESSAGE_RELEASE_WAKE_LOCK);
1758
1759 log("LocationWorkerHandler: Locations received.");
1760 mWakeLockAcquireTime = 0;
1761 Message m = Message.obtain(this, MESSAGE_RELEASE_WAKE_LOCK);
1762 sendMessageDelayed(m, TIME_AFTER_WAKE_LOCK);
1763 }
1764 }
1765
1766 } else if (msg.what == MESSAGE_ACQUIRE_WAKE_LOCK) {
1767 log("LocationWorkerHandler: Acquire");
1768 synchronized (mLocationListeners) {
1769 acquireWakeLockLocked();
1770 }
1771 } else if (msg.what == MESSAGE_RELEASE_WAKE_LOCK) {
1772 log("LocationWorkerHandler: Release");
1773
1774 // Update wakelock status so the next alarm is set before releasing wakelock
1775 synchronized (mLocationListeners) {
1776 updateWakelockStatusLocked(mScreenOn);
1777 releaseWakeLockLocked();
1778 }
1779 } else if (msg.what == MESSAGE_INSTALL_NETWORK_LOCATION_PROVIDER) {
1780 synchronized (mLocationListeners) {
1781 Log.d(TAG, "installing network location provider");
1782 INetworkLocationManager.InstallCallback callback =
1783 (INetworkLocationManager.InstallCallback)msg.obj;
1784 callback.installNetworkLocationProvider(LocationManagerService.this);
1785 }
1786 }
1787 } catch (Exception e) {
1788 // Log, don't crash!
1789 Log.e(TAG, "Exception in LocationWorkerHandler.handleMessage:", e);
1790 }
1791 }
1792 }
1793
1794 class CellLocationUpdater extends Thread {
1795 CellLocation mNextLocation;
1796
1797 CellLocationUpdater() {
1798 super("CellLocationUpdater");
1799 }
1800
1801 @Override
1802 public void run() {
1803 int curAsu = -1;
1804 CellLocation curLocation = null;
1805
1806 while (true) {
1807 // See if there is more work to do...
1808 synchronized (mLocationListeners) {
1809 if (curLocation == mNextLocation) {
1810 mCellLocationUpdater = null;
1811 break;
1812 }
1813
1814 curLocation = mNextLocation;
1815 if (curLocation == null) {
1816 mCellLocationUpdater = null;
1817 break;
1818 }
1819
1820 curAsu = mLastSignalStrength;
1821
1822 mNextLocation = null;
1823 }
1824
1825 try {
1826 // Gets cell state. This can block so must be done without
1827 // locks held.
1828 CellState cs = new CellState(mTelephonyManager, curLocation, curAsu);
1829
1830 synchronized (mLocationListeners) {
1831 mLastCellState = cs;
1832
1833 cs.updateSignalStrength(mLastSignalStrength);
1834 cs.updateRadioType(mLastRadioType);
1835
1836 // Notify collector
1837 if (mCollector != null) {
1838 mCollector.updateCellState(cs);
1839 }
1840
1841 // Updates providers
1842 List<LocationProviderImpl> providers = LocationProviderImpl.getProviders();
1843 for (LocationProviderImpl provider : providers) {
1844 if (provider.requiresCell()) {
1845 provider.updateCellState(cs);
1846 }
1847 }
1848 }
1849 } catch (RuntimeException e) {
1850 Log.e(TAG, "Exception in PhoneStateListener.onCellLocationChanged:", e);
1851 }
1852 }
1853 }
1854 }
1855
1856 CellLocationUpdater mCellLocationUpdater = null;
1857 CellState mLastCellState = null;
1858 int mLastSignalStrength = -1;
1859 int mLastRadioType = -1;
1860
1861 PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
1862
1863 @Override
1864 public void onCellLocationChanged(CellLocation cellLocation) {
1865 synchronized (mLocationListeners) {
1866 if (mCellLocationUpdater == null) {
1867 mCellLocationUpdater = new CellLocationUpdater();
1868 mCellLocationUpdater.start();
1869 }
1870 mCellLocationUpdater.mNextLocation = cellLocation;
1871 }
1872 }
1873
1874 @Override
1875 public void onSignalStrengthChanged(int asu) {
1876 synchronized (mLocationListeners) {
1877 mLastSignalStrength = asu;
1878
1879 if (mLastCellState != null) {
1880 mLastCellState.updateSignalStrength(asu);
1881 }
1882 }
1883 }
1884
1885 @Override
1886 public void onDataConnectionStateChanged(int state) {
1887 synchronized (mLocationListeners) {
1888 // Get radio type
1889 int radioType = mTelephonyManager.getNetworkType();
1890 if (radioType == TelephonyManager.NETWORK_TYPE_GPRS ||
1891 radioType == TelephonyManager.NETWORK_TYPE_EDGE) {
1892 radioType = CellState.RADIO_TYPE_GPRS;
1893 } else if (radioType == TelephonyManager.NETWORK_TYPE_UMTS) {
1894 radioType = CellState.RADIO_TYPE_WCDMA;
1895 }
1896 mLastRadioType = radioType;
1897
1898 if (mLastCellState != null) {
1899 mLastCellState.updateRadioType(radioType);
1900 }
1901 }
1902 }
1903 };
1904
1905 private class PowerStateBroadcastReceiver extends BroadcastReceiver {
1906 @Override public void onReceive(Context context, Intent intent) {
1907 String action = intent.getAction();
1908
1909 if (action.equals(ALARM_INTENT)) {
1910 synchronized (mLocationListeners) {
1911 log("PowerStateBroadcastReceiver: Alarm received");
1912 mLocationHandler.removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK);
1913 // Have to do this immediately, rather than posting a
1914 // message, so we execute our code while the system
1915 // is holding a wake lock until the alarm broadcast
1916 // is finished.
1917 acquireWakeLockLocked();
1918 }
1919
1920 } else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
1921 log("PowerStateBroadcastReceiver: Screen off");
1922 synchronized (mLocationListeners) {
1923 updateWakelockStatusLocked(false);
1924 }
1925
1926 } else if (action.equals(Intent.ACTION_SCREEN_ON)) {
1927 log("PowerStateBroadcastReceiver: Screen on");
1928 synchronized (mLocationListeners) {
1929 updateWakelockStatusLocked(true);
1930 }
1931
1932 } else if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {
1933 log("PowerStateBroadcastReceiver: Battery changed");
1934 synchronized (mLocationListeners) {
1935 int scale = intent.getIntExtra(BATTERY_EXTRA_SCALE, 100);
1936 int level = intent.getIntExtra(BATTERY_EXTRA_LEVEL, 0);
1937 boolean plugged = intent.getIntExtra(BATTERY_EXTRA_PLUGGED, 0) != 0;
1938
1939 // Notify collector battery state
1940 if (mCollector != null) {
1941 mCollector.updateBatteryState(scale, level, plugged);
1942 }
1943 }
1944 } else if (action.equals(Intent.ACTION_PACKAGE_REMOVED)
1945 || action.equals(Intent.ACTION_PACKAGE_RESTARTED)) {
1946 synchronized (mLocationListeners) {
1947 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
1948 if (uid >= 0) {
1949 ArrayList<Receiver> removedRecs = null;
1950 for (ArrayList<UpdateRecord> i : mRecordsByProvider.values()) {
1951 for (int j=i.size()-1; j>=0; j--) {
1952 UpdateRecord ur = i.get(j);
1953 if (ur.mReceiver.isPendingIntent() && ur.mUid == uid) {
1954 if (removedRecs == null) {
1955 removedRecs = new ArrayList<Receiver>();
1956 }
1957 if (!removedRecs.contains(ur.mReceiver)) {
1958 removedRecs.add(ur.mReceiver);
1959 }
1960 }
1961 }
1962 }
1963 ArrayList<ProximityAlert> removedAlerts = null;
1964 for (ProximityAlert i : mProximityAlerts.values()) {
1965 if (i.mUid == uid) {
1966 if (removedAlerts == null) {
1967 removedAlerts = new ArrayList<ProximityAlert>();
1968 }
1969 if (!removedAlerts.contains(i)) {
1970 removedAlerts.add(i);
1971 }
1972 }
1973 }
1974 if (removedRecs != null) {
1975 for (int i=removedRecs.size()-1; i>=0; i--) {
1976 removeUpdatesLocked(removedRecs.get(i));
1977 }
1978 }
1979 if (removedAlerts != null) {
1980 for (int i=removedAlerts.size()-1; i>=0; i--) {
1981 removeProximityAlertLocked(removedAlerts.get(i).mIntent);
1982 }
1983 }
1984 }
1985 }
1986 }
1987 }
1988 }
1989
1990 private class NetworkStateBroadcastReceiver extends BroadcastReceiver {
1991 @Override public void onReceive(Context context, Intent intent) {
1992 String action = intent.getAction();
1993
1994 if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
1995
1996 List<ScanResult> wifiScanResults = mWifiManager.getScanResults();
1997
1998 if (wifiScanResults == null) {
1999 return;
2000 }
2001
2002 // Notify provider and collector of Wifi scan results
2003 synchronized (mLocationListeners) {
2004 if (mCollector != null) {
2005 mCollector.updateWifiScanResults(wifiScanResults);
2006 }
2007 if (mNetworkLocationInterface != null) {
2008 mNetworkLocationInterface.updateWifiScanResults(wifiScanResults);
2009 }
2010 }
2011
2012 } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 boolean noConnectivity =
2014 intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
2015 if (!noConnectivity) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002016 mNetworkState = LocationProvider.AVAILABLE;
2017 } else {
2018 mNetworkState = LocationProvider.TEMPORARILY_UNAVAILABLE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020
2021 // Notify location providers of current network state
2022 synchronized (mLocationListeners) {
2023 List<LocationProviderImpl> providers = LocationProviderImpl.getProviders();
2024 for (LocationProviderImpl provider : providers) {
2025 if (provider.requiresNetwork()) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002026 provider.updateNetworkState(mNetworkState);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028 }
2029 }
2030
2031 } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
2032 int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
2033 WifiManager.WIFI_STATE_UNKNOWN);
2034
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 if (state == WifiManager.WIFI_STATE_ENABLED) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002036 mWifiEnabled = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002037 } else if (state == WifiManager.WIFI_STATE_DISABLED) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002038 mWifiEnabled = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 } else {
2040 return;
2041 }
2042
2043 // Notify network provider of current wifi enabled state
2044 synchronized (mLocationListeners) {
2045 if (mNetworkLocationInterface != null) {
The Android Open Source Project4df24232009-03-05 14:34:35 -08002046 mNetworkLocationInterface.updateWifiEnabledState(mWifiEnabled);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 }
2048 }
2049
2050 } else if (action.equals(GpsLocationProvider.GPS_ENABLED_CHANGE_ACTION)) {
2051
2052 final boolean enabled = intent.getBooleanExtra(GpsLocationProvider.EXTRA_ENABLED,
2053 false);
2054
2055 synchronized (mLocationListeners) {
2056 if (enabled) {
2057 updateReportedGpsLocked();
2058 mGpsNavigating = true;
2059 } else {
2060 reportStopGpsLocked();
2061 mGpsNavigating = false;
2062 // When GPS is disabled, we are OK to release wake-lock
2063 mWakeLockGpsReceived = true;
2064 }
2065 }
2066 }
2067
2068 }
2069 }
2070
2071 // Wake locks
2072
2073 private void updateWakelockStatusLocked(boolean screenOn) {
2074 log("updateWakelockStatus(): " + screenOn);
2075
2076 boolean needsLock = false;
2077 long minTime = Integer.MAX_VALUE;
2078
2079 if (mNetworkLocationProvider != null && mNetworkLocationProvider.isLocationTracking()) {
2080 needsLock = true;
2081 minTime = Math.min(mNetworkLocationProvider.getMinTime(), minTime);
2082 }
2083
2084 if (mGpsLocationProvider != null && mGpsLocationProvider.isLocationTracking()) {
2085 needsLock = true;
2086 minTime = Math.min(mGpsLocationProvider.getMinTime(), minTime);
2087 if (screenOn) {
2088 startGpsLocked();
2089 } else if (mScreenOn && !screenOn) {
2090 // We just turned the screen off so stop navigating
2091 stopGpsLocked();
2092 }
2093 }
2094
2095 mScreenOn = screenOn;
2096
2097 PendingIntent sender =
2098 PendingIntent.getBroadcast(mContext, 0, new Intent(ALARM_INTENT), 0);
2099
2100 // Cancel existing alarm
2101 log("Cancelling existing alarm");
2102 mAlarmManager.cancel(sender);
2103
2104 if (needsLock && !mScreenOn) {
2105 long now = SystemClock.elapsedRealtime();
2106 mAlarmManager.set(
2107 AlarmManager.ELAPSED_REALTIME_WAKEUP, now + minTime, sender);
2108 mAlarmInterval = minTime;
2109 log("Creating a new wakelock alarm with minTime = " + minTime);
2110 } else {
2111 log("No need for alarm");
2112 mAlarmInterval = -1;
2113
2114 // Clear out existing wakelocks
2115 mLocationHandler.removeMessages(MESSAGE_ACQUIRE_WAKE_LOCK);
2116 mLocationHandler.removeMessages(MESSAGE_RELEASE_WAKE_LOCK);
2117 releaseWakeLockLocked();
2118 }
2119 }
2120
2121 private void acquireWakeLockLocked() {
2122 try {
2123 acquireWakeLockXLocked();
2124 } catch (Exception e) {
2125 // This is to catch a runtime exception thrown when we try to release an
2126 // already released lock.
2127 Log.e(TAG, "exception in acquireWakeLock()", e);
2128 }
2129 }
2130
2131 private void acquireWakeLockXLocked() {
2132 if (mWakeLock.isHeld()) {
2133 log("Must release wakelock before acquiring");
2134 mWakeLockAcquireTime = 0;
2135 mWakeLock.release();
2136 }
2137
2138 boolean networkActive = (mNetworkLocationProvider != null)
2139 && mNetworkLocationProvider.isLocationTracking();
2140 boolean gpsActive = (mGpsLocationProvider != null)
2141 && mGpsLocationProvider.isLocationTracking();
2142
2143 boolean needsLock = networkActive || gpsActive;
2144 if (!needsLock) {
2145 log("No need for Lock!");
2146 return;
2147 }
2148
2149 mWakeLockGpsReceived = !gpsActive;
2150 mWakeLockNetworkReceived = !networkActive;
2151
2152 // Acquire wake lock
2153 mWakeLock.acquire();
2154 mWakeLockAcquireTime = SystemClock.elapsedRealtime();
2155 log("Acquired wakelock");
2156
2157 // Start the gps provider
2158 startGpsLocked();
2159
2160 // Acquire cell lock
2161 if (mCellWakeLockAcquired) {
2162 // Lock is already acquired
2163 } else if (!mWakeLockNetworkReceived) {
2164 mTelephonyManager.enableLocationUpdates();
2165 mCellWakeLockAcquired = true;
2166 } else {
2167 mCellWakeLockAcquired = false;
2168 }
2169
2170 // Notify NetworkLocationProvider
2171 if (mNetworkLocationInterface != null) {
2172 mNetworkLocationInterface.updateCellLockStatus(mCellWakeLockAcquired);
2173 }
2174
2175 // Acquire wifi lock
2176 WifiManager.WifiLock wifiLock = getWifiWakelockLocked();
2177 if (wifiLock != null) {
2178 if (mWifiWakeLockAcquired) {
2179 // Lock is already acquired
2180 } else if (mWifiManager.isWifiEnabled() && !mWakeLockNetworkReceived) {
2181 wifiLock.acquire();
2182 mWifiWakeLockAcquired = true;
2183 } else {
2184 mWifiWakeLockAcquired = false;
2185 Log.w(TAG, "acquireWakeLock(): Unable to get WiFi lock");
2186 }
2187 }
2188 }
2189
2190 private boolean reportGpsUidLocked(int curSeq, int nextSeq, int uid) {
2191 int seq = mReportedGpsUids.get(uid, -1);
2192 if (seq == curSeq) {
2193 // Already reported; propagate to next sequence.
2194 mReportedGpsUids.put(uid, nextSeq);
2195 return true;
2196 } else if (seq != nextSeq) {
2197 try {
2198 // New UID; report it.
2199 mBatteryStats.noteStartGps(uid);
2200 mReportedGpsUids.put(uid, nextSeq);
2201 return true;
2202 } catch (RemoteException e) {
2203 }
2204 }
2205 return false;
2206 }
2207
2208 private void updateReportedGpsLocked() {
2209 if (mGpsLocationProvider == null) {
2210 return;
2211 }
2212
2213 final String name = mGpsLocationProvider.getName();
2214 final int curSeq = mReportedGpsSeq;
2215 final int nextSeq = (curSeq+1) >= 0 ? (curSeq+1) : 0;
2216 mReportedGpsSeq = nextSeq;
2217
2218 ArrayList<UpdateRecord> urs = mRecordsByProvider.get(name);
2219 int num = 0;
2220 final int N = urs.size();
2221 for (int i=0; i<N; i++) {
2222 UpdateRecord ur = urs.get(i);
2223 if (ur.mReceiver == mProximityListener) {
2224 // We don't want the system to take the blame for this one.
2225 continue;
2226 }
2227 if (reportGpsUidLocked(curSeq, nextSeq, ur.mUid)) {
2228 num++;
2229 }
2230 }
2231
2232 for (ProximityAlert pe : mProximityAlerts.values()) {
2233 if (reportGpsUidLocked(curSeq, nextSeq, pe.mUid)) {
2234 num++;
2235 }
2236 }
2237
2238 if (num != mReportedGpsUids.size()) {
2239 // The number of uids is processed is different than the
2240 // array; report any that are no longer active.
2241 for (int i=mReportedGpsUids.size()-1; i>=0; i--) {
2242 if (mReportedGpsUids.valueAt(i) != nextSeq) {
2243 try {
2244 mBatteryStats.noteStopGps(mReportedGpsUids.keyAt(i));
2245 } catch (RemoteException e) {
2246 }
2247 mReportedGpsUids.removeAt(i);
2248 }
2249 }
2250 }
2251 }
2252
2253 private void reportStopGpsLocked() {
2254 int curSeq = mReportedGpsSeq;
2255 for (int i=mReportedGpsUids.size()-1; i>=0; i--) {
2256 if (mReportedGpsUids.valueAt(i) == curSeq) {
2257 try {
2258 mBatteryStats.noteStopGps(mReportedGpsUids.keyAt(i));
2259 } catch (RemoteException e) {
2260 }
2261 }
2262 }
2263 curSeq++;
2264 if (curSeq < 0) curSeq = 0;
2265 mReportedGpsSeq = curSeq;
2266 mReportedGpsUids.clear();
2267 }
2268
2269 private void startGpsLocked() {
2270 boolean gpsActive = (mGpsLocationProvider != null)
2271 && mGpsLocationProvider.isLocationTracking();
2272 if (gpsActive) {
2273 mGpsLocationProvider.startNavigating();
2274 }
2275 }
2276
2277 private void stopGpsLocked() {
2278 boolean gpsActive = mGpsLocationProvider != null
2279 && mGpsLocationProvider.isLocationTracking();
2280 if (gpsActive) {
2281 mGpsLocationProvider.stopNavigating();
2282 }
2283 }
2284
2285 private void releaseWakeLockLocked() {
2286 try {
2287 releaseWakeLockXLocked();
2288 } catch (Exception e) {
2289 // This is to catch a runtime exception thrown when we try to release an
2290 // already released lock.
2291 Log.e(TAG, "exception in releaseWakeLock()", e);
2292 }
2293 }
2294
2295 private void releaseWakeLockXLocked() {
2296 // Release wifi lock
2297 WifiManager.WifiLock wifiLock = getWifiWakelockLocked();
2298 if (wifiLock != null) {
2299 if (mWifiWakeLockAcquired) {
2300 wifiLock.release();
2301 mWifiWakeLockAcquired = false;
2302 }
2303 }
2304
2305 if (!mScreenOn) {
2306 // Stop the gps
2307 stopGpsLocked();
2308 }
2309
2310 // Release cell lock
2311 if (mCellWakeLockAcquired) {
2312 mTelephonyManager.disableLocationUpdates();
2313 mCellWakeLockAcquired = false;
2314 }
2315
2316 // Notify NetworkLocationProvider
2317 if (mNetworkLocationInterface != null) {
2318 mNetworkLocationInterface.updateCellLockStatus(mCellWakeLockAcquired);
2319 }
2320
2321 // Release wake lock
2322 mWakeLockAcquireTime = 0;
2323 if (mWakeLock.isHeld()) {
2324 log("Released wakelock");
2325 mWakeLock.release();
2326 } else {
2327 log("Can't release wakelock again!");
2328 }
2329 }
2330
2331 // Geocoder
2332
2333 public String getFromLocation(double latitude, double longitude, int maxResults,
2334 String language, String country, String variant, String appName, List<Address> addrs) {
2335 synchronized (mLocationListeners) {
2336 if (mNetworkLocationInterface != null) {
2337 return mNetworkLocationInterface.getFromLocation(latitude, longitude, maxResults,
2338 language, country, variant, appName, addrs);
2339 } else {
2340 return null;
2341 }
2342 }
2343 }
2344
2345 public String getFromLocationName(String locationName,
2346 double lowerLeftLatitude, double lowerLeftLongitude,
2347 double upperRightLatitude, double upperRightLongitude, int maxResults,
2348 String language, String country, String variant, String appName, List<Address> addrs) {
2349 synchronized (mLocationListeners) {
2350 if (mNetworkLocationInterface != null) {
2351 return mNetworkLocationInterface.getFromLocationName(locationName, lowerLeftLatitude,
2352 lowerLeftLongitude, upperRightLatitude, upperRightLongitude, maxResults,
2353 language, country, variant, appName, addrs);
2354 } else {
2355 return null;
2356 }
2357 }
2358 }
2359
2360 // Mock Providers
2361
2362 class MockProvider extends LocationProviderImpl {
2363 boolean mRequiresNetwork;
2364 boolean mRequiresSatellite;
2365 boolean mRequiresCell;
2366 boolean mHasMonetaryCost;
2367 boolean mSupportsAltitude;
2368 boolean mSupportsSpeed;
2369 boolean mSupportsBearing;
2370 int mPowerRequirement;
2371 int mAccuracy;
2372
2373 public MockProvider(String name, boolean requiresNetwork, boolean requiresSatellite,
2374 boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude,
2375 boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) {
2376 super(name);
2377
2378 mRequiresNetwork = requiresNetwork;
2379 mRequiresSatellite = requiresSatellite;
2380 mRequiresCell = requiresCell;
2381 mHasMonetaryCost = hasMonetaryCost;
2382 mSupportsAltitude = supportsAltitude;
2383 mSupportsBearing = supportsBearing;
2384 mSupportsSpeed = supportsSpeed;
2385 mPowerRequirement = powerRequirement;
2386 mAccuracy = accuracy;
2387 }
2388
2389 @Override
2390 public void disable() {
2391 String name = getName();
2392 // We shouldn't normally need to lock, since this should only be called
2393 // by the service with the lock held, but let's be paranid.
2394 synchronized (mLocationListeners) {
2395 mEnabledProviders.remove(name);
2396 mDisabledProviders.add(name);
2397 }
2398 }
2399
2400 @Override
2401 public void enable() {
2402 String name = getName();
2403 // We shouldn't normally need to lock, since this should only be called
2404 // by the service with the lock held, but let's be paranid.
2405 synchronized (mLocationListeners) {
2406 mEnabledProviders.add(name);
2407 mDisabledProviders.remove(name);
2408 }
2409 }
2410
2411 @Override
2412 public boolean getLocation(Location l) {
2413 // We shouldn't normally need to lock, since this should only be called
2414 // by the service with the lock held, but let's be paranid.
2415 synchronized (mLocationListeners) {
2416 Location loc = mMockProviderLocation.get(getName());
2417 if (loc == null) {
2418 return false;
2419 }
2420 l.set(loc);
2421 return true;
2422 }
2423 }
2424
2425 @Override
2426 public int getStatus(Bundle extras) {
2427 // We shouldn't normally need to lock, since this should only be called
2428 // by the service with the lock held, but let's be paranid.
2429 synchronized (mLocationListeners) {
2430 String name = getName();
2431 Integer s = mMockProviderStatus.get(name);
2432 int status = (s == null) ? AVAILABLE : s.intValue();
2433 Bundle newExtras = mMockProviderStatusExtras.get(name);
2434 if (newExtras != null) {
2435 extras.clear();
2436 extras.putAll(newExtras);
2437 }
2438 return status;
2439 }
2440 }
2441
2442 @Override
2443 public boolean isEnabled() {
2444 // We shouldn't normally need to lock, since this should only be called
2445 // by the service with the lock held, but let's be paranid.
2446 synchronized (mLocationListeners) {
2447 return mEnabledProviders.contains(getName());
2448 }
2449 }
2450
2451 @Override
2452 public int getAccuracy() {
2453 return mAccuracy;
2454 }
2455
2456 @Override
2457 public int getPowerRequirement() {
2458 return mPowerRequirement;
2459 }
2460
2461 @Override
2462 public boolean hasMonetaryCost() {
2463 return mHasMonetaryCost;
2464 }
2465
2466 @Override
2467 public boolean requiresCell() {
2468 return mRequiresCell;
2469 }
2470
2471 @Override
2472 public boolean requiresNetwork() {
2473 return mRequiresNetwork;
2474 }
2475
2476 @Override
2477 public boolean requiresSatellite() {
2478 return mRequiresSatellite;
2479 }
2480
2481 @Override
2482 public boolean supportsAltitude() {
2483 return mSupportsAltitude;
2484 }
2485
2486 @Override
2487 public boolean supportsBearing() {
2488 return mSupportsBearing;
2489 }
2490
2491 @Override
2492 public boolean supportsSpeed() {
2493 return mSupportsSpeed;
2494 }
2495 }
2496
2497 private void checkMockPermissionsSafe() {
2498 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2499 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2500 if (!allowMocks) {
2501 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2502 }
2503
2504 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
2505 PackageManager.PERMISSION_GRANTED) {
2506 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
2507 }
2508 }
2509
2510 public void addTestProvider(String name, boolean requiresNetwork, boolean requiresSatellite,
2511 boolean requiresCell, boolean hasMonetaryCost, boolean supportsAltitude,
2512 boolean supportsSpeed, boolean supportsBearing, int powerRequirement, int accuracy) {
2513 checkMockPermissionsSafe();
2514
2515 synchronized (mLocationListeners) {
2516 MockProvider provider = new MockProvider(name, requiresNetwork, requiresSatellite,
2517 requiresCell, hasMonetaryCost, supportsAltitude,
2518 supportsSpeed, supportsBearing, powerRequirement, accuracy);
2519 if (LocationProviderImpl.getProvider(name) != null) {
2520 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2521 }
2522 LocationProviderImpl.addProvider(provider);
2523 updateProvidersLocked();
2524 }
2525 }
2526
2527 public void removeTestProvider(String provider) {
2528 checkMockPermissionsSafe();
2529 synchronized (mLocationListeners) {
2530 LocationProviderImpl p = LocationProviderImpl.getProvider(provider);
2531 if (p == null) {
2532 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2533 }
2534 LocationProviderImpl.removeProvider(p);
2535 updateProvidersLocked();
2536 }
2537 }
2538
2539 public void setTestProviderLocation(String provider, Location loc) {
2540 checkMockPermissionsSafe();
2541 synchronized (mLocationListeners) {
2542 if (LocationProviderImpl.getProvider(provider) == null) {
2543 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2544 }
2545 mMockProviderLocation.put(provider, loc);
2546 }
2547 }
2548
2549 public void clearTestProviderLocation(String provider) {
2550 checkMockPermissionsSafe();
2551 synchronized (mLocationListeners) {
2552 if (LocationProviderImpl.getProvider(provider) == null) {
2553 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2554 }
2555 mMockProviderLocation.remove(provider);
2556 }
2557 }
2558
2559 public void setTestProviderEnabled(String provider, boolean enabled) {
2560 checkMockPermissionsSafe();
2561 synchronized (mLocationListeners) {
2562 if (LocationProviderImpl.getProvider(provider) == null) {
2563 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2564 }
2565 if (enabled) {
2566 mEnabledProviders.add(provider);
2567 mDisabledProviders.remove(provider);
2568 } else {
2569 mEnabledProviders.remove(provider);
2570 mDisabledProviders.add(provider);
2571 }
2572 updateProvidersLocked();
2573 }
2574 }
2575
2576 public void clearTestProviderEnabled(String provider) {
2577 checkMockPermissionsSafe();
2578 synchronized (mLocationListeners) {
2579 if (LocationProviderImpl.getProvider(provider) == null) {
2580 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2581 }
2582 mEnabledProviders.remove(provider);
2583 mDisabledProviders.remove(provider);
2584 updateProvidersLocked();
2585 }
2586 }
2587
2588 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2589 checkMockPermissionsSafe();
2590 synchronized (mLocationListeners) {
2591 if (LocationProviderImpl.getProvider(provider) == null) {
2592 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2593 }
2594 mMockProviderStatus.put(provider, new Integer(status));
2595 mMockProviderStatusExtras.put(provider, extras);
2596 mMockProviderStatusUpdateTime.put(provider, new Long(updateTime));
2597 }
2598 }
2599
2600 public void clearTestProviderStatus(String provider) {
2601 checkMockPermissionsSafe();
2602 synchronized (mLocationListeners) {
2603 if (LocationProviderImpl.getProvider(provider) == null) {
2604 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2605 }
2606 mMockProviderStatus.remove(provider);
2607 mMockProviderStatusExtras.remove(provider);
2608 mMockProviderStatusUpdateTime.remove(provider);
2609 }
2610 }
2611
2612 private void log(String log) {
2613 if (Log.isLoggable(TAG, Log.VERBOSE)) {
2614 Log.d(TAG, log);
2615 }
2616 }
2617
2618 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2619 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2620 != PackageManager.PERMISSION_GRANTED) {
2621 pw.println("Permission Denial: can't dump AlarmManager from from pid="
2622 + Binder.getCallingPid()
2623 + ", uid=" + Binder.getCallingUid());
2624 return;
2625 }
2626
2627 synchronized (mLocationListeners) {
2628 pw.println("Current Location Manager state:");
2629 pw.println(" sProvidersLoaded=" + sProvidersLoaded);
2630 pw.println(" mGpsLocationProvider=" + mGpsLocationProvider);
2631 pw.println(" mGpsNavigating=" + mGpsNavigating);
2632 pw.println(" mNetworkLocationProvider=" + mNetworkLocationProvider);
2633 pw.println(" mNetworkLocationInterface=" + mNetworkLocationInterface);
2634 pw.println(" mLastSignalStrength=" + mLastSignalStrength
2635 + " mLastRadioType=" + mLastRadioType);
2636 pw.println(" mCellLocationUpdater=" + mCellLocationUpdater);
2637 pw.println(" mLastCellState=" + mLastCellState);
2638 pw.println(" mCollector=" + mCollector);
2639 pw.println(" mAlarmInterval=" + mAlarmInterval
2640 + " mScreenOn=" + mScreenOn
2641 + " mWakeLockAcquireTime=" + mWakeLockAcquireTime);
2642 pw.println(" mWakeLockGpsReceived=" + mWakeLockGpsReceived
2643 + " mWakeLockNetworkReceived=" + mWakeLockNetworkReceived);
2644 pw.println(" mWifiWakeLockAcquired=" + mWifiWakeLockAcquired
2645 + " mCellWakeLockAcquired=" + mCellWakeLockAcquired);
2646 pw.println(" Listeners:");
2647 int N = mListeners.size();
2648 for (int i=0; i<N; i++) {
2649 pw.println(" " + mListeners.get(i));
2650 }
2651 pw.println(" Location Listeners:");
2652 for (Map.Entry<Receiver, HashMap<String,UpdateRecord>> i
2653 : mLocationListeners.entrySet()) {
2654 pw.println(" " + i.getKey() + ":");
2655 for (Map.Entry<String,UpdateRecord> j : i.getValue().entrySet()) {
2656 pw.println(" " + j.getKey() + ":");
2657 j.getValue().dump(pw, " ");
2658 }
2659 }
2660 pw.println(" Last Fix Broadcasts:");
2661 for (Map.Entry<Receiver, HashMap<String,Location>> i
2662 : mLastFixBroadcast.entrySet()) {
2663 pw.println(" " + i.getKey() + ":");
2664 for (Map.Entry<String,Location> j : i.getValue().entrySet()) {
2665 pw.println(" " + j.getKey() + ":");
2666 j.getValue().dump(new PrintWriterPrinter(pw), " ");
2667 }
2668 }
2669 pw.println(" Last Status Broadcasts:");
2670 for (Map.Entry<Receiver, HashMap<String,Long>> i
2671 : mLastStatusBroadcast.entrySet()) {
2672 pw.println(" " + i.getKey() + ":");
2673 for (Map.Entry<String,Long> j : i.getValue().entrySet()) {
2674 pw.println(" " + j.getKey() + " -> 0x"
2675 + Long.toHexString(j.getValue()));
2676 }
2677 }
2678 pw.println(" Records by Provider:");
2679 for (Map.Entry<String, ArrayList<UpdateRecord>> i
2680 : mRecordsByProvider.entrySet()) {
2681 pw.println(" " + i.getKey() + ":");
2682 for (UpdateRecord j : i.getValue()) {
2683 pw.println(" " + j + ":");
2684 j.dump(pw, " ");
2685 }
2686 }
2687 pw.println(" Locations by Provider:");
2688 for (Map.Entry<String, Location> i
2689 : mLocationsByProvider.entrySet()) {
2690 pw.println(" " + i.getKey() + ":");
2691 i.getValue().dump(new PrintWriterPrinter(pw), " ");
2692 }
2693 pw.println(" Last Known Locations:");
2694 for (Map.Entry<String, Location> i
2695 : mLastKnownLocation.entrySet()) {
2696 pw.println(" " + i.getKey() + ":");
2697 i.getValue().dump(new PrintWriterPrinter(pw), " ");
2698 }
2699 if (mProximityAlerts.size() > 0) {
2700 pw.println(" Proximity Alerts:");
2701 for (Map.Entry<PendingIntent, ProximityAlert> i
2702 : mProximityAlerts.entrySet()) {
2703 pw.println(" " + i.getKey() + ":");
2704 i.getValue().dump(pw, " ");
2705 }
2706 }
2707 if (mProximitiesEntered.size() > 0) {
2708 pw.println(" Proximities Entered:");
2709 for (ProximityAlert i : mProximitiesEntered) {
2710 pw.println(" " + i + ":");
2711 i.dump(pw, " ");
2712 }
2713 }
2714 pw.println(" mProximityListener=" + mProximityListener);
2715 if (mEnabledProviders.size() > 0) {
2716 pw.println(" Enabled Providers:");
2717 for (String i : mEnabledProviders) {
2718 pw.println(" " + i);
2719 }
2720
2721 }
2722 if (mDisabledProviders.size() > 0) {
2723 pw.println(" Disabled Providers:");
2724 for (String i : mDisabledProviders) {
2725 pw.println(" " + i);
2726 }
2727
2728 }
2729 if (mMockProviders.size() > 0) {
2730 pw.println(" Mock Providers:");
2731 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
2732 pw.println(" " + i.getKey() + " -> " + i.getValue());
2733 }
2734 }
2735 if (mMockProviderLocation.size() > 0) {
2736 pw.println(" Mock Provider Location:");
2737 for (Map.Entry<String, Location> i : mMockProviderLocation.entrySet()) {
2738 pw.println(" " + i.getKey() + ":");
2739 i.getValue().dump(new PrintWriterPrinter(pw), " ");
2740 }
2741 }
2742 if (mMockProviderStatus.size() > 0) {
2743 pw.println(" Mock Provider Status:");
2744 for (Map.Entry<String, Integer> i : mMockProviderStatus.entrySet()) {
2745 pw.println(" " + i.getKey() + " -> 0x"
2746 + Integer.toHexString(i.getValue()));
2747 }
2748 }
2749 if (mMockProviderStatusExtras.size() > 0) {
2750 pw.println(" Mock Provider Status Extras:");
2751 for (Map.Entry<String, Bundle> i : mMockProviderStatusExtras.entrySet()) {
2752 pw.println(" " + i.getKey() + " -> " + i.getValue());
2753 }
2754 }
2755 if (mMockProviderStatusUpdateTime.size() > 0) {
2756 pw.println(" Mock Provider Status Update Time:");
2757 for (Map.Entry<String, Long> i : mMockProviderStatusUpdateTime.entrySet()) {
2758 pw.println(" " + i.getKey() + " -> " + i.getValue());
2759 }
2760 }
2761 pw.println(" Reported GPS UIDs @ seq " + mReportedGpsSeq + ":");
2762 N = mReportedGpsUids.size();
2763 for (int i=0; i<N; i++) {
2764 pw.println(" UID " + mReportedGpsUids.keyAt(i)
2765 + " seq=" + mReportedGpsUids.valueAt(i));
2766 }
2767 }
2768 }
2769}
2770