blob: c4ed4655147e81217832f17df3ec9dc78c7863d8 [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
Dianne Hackborna06de0f2012-12-11 16:34:47 -080019import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070021import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070025import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070026import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050027import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070029import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050030import android.content.pm.ResolveInfo;
31import android.content.pm.Signature;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050032import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070033import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070035import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050036import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070037import android.location.Geofence;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.location.IGpsStatusListener;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -040039import android.location.IGpsStatusProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.location.ILocationListener;
41import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040042import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.location.Location;
44import android.location.LocationManager;
45import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070046import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Binder;
48import android.os.Bundle;
49import android.os.Handler;
Victoria Lease5cd731a2012-12-19 15:04:21 -080050import android.os.HandlerThread;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070052import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Message;
54import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070055import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070057import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070058import android.os.UserHandle;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070059import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080062import android.util.Slog;
Mike Lockwoode97ae402010-09-29 15:23:46 -040063import com.android.internal.content.PackageMonitor;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070064import com.android.internal.location.ProviderProperties;
65import com.android.internal.location.ProviderRequest;
Mike Lockwood43e33f22010-03-26 10:41:48 -040066import com.android.server.location.GeocoderProxy;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070067import com.android.server.location.GeofenceProxy;
Nick Pellye0fd6932012-07-11 10:26:13 -070068import com.android.server.location.GeofenceManager;
Mike Lockwood43e33f22010-03-26 10:41:48 -040069import com.android.server.location.GpsLocationProvider;
Nick Pelly4035f5a2012-08-17 14:43:49 -070070import com.android.server.location.LocationBlacklist;
Nick Pelly74fa7ea2012-08-13 19:36:38 -070071import com.android.server.location.LocationFudger;
Mike Lockwood43e33f22010-03-26 10:41:48 -040072import com.android.server.location.LocationProviderInterface;
73import com.android.server.location.LocationProviderProxy;
74import com.android.server.location.MockProvider;
75import com.android.server.location.PassiveProvider;
76
77import java.io.FileDescriptor;
78import java.io.PrintWriter;
79import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070080import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040081import java.util.HashMap;
82import java.util.HashSet;
83import java.util.List;
84import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -040085import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
87/**
88 * The service class that manages LocationProviders and issues location
89 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090 */
Victoria Lease5cd731a2012-12-19 15:04:21 -080091public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -080093 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -070094
95 private static final String WAKELOCK_KEY = TAG;
96 private static final String THREAD_NAME = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097
Victoria Lease37425c32012-10-16 16:08:48 -070098 // Location resolution level: no location data whatsoever
99 private static final int RESOLUTION_LEVEL_NONE = 0;
100 // Location resolution level: coarse location data only
101 private static final int RESOLUTION_LEVEL_COARSE = 1;
102 // Location resolution level: fine location data
103 private static final int RESOLUTION_LEVEL_FINE = 2;
104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700106 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700108 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400109 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700110 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
111
112 private static final String NETWORK_LOCATION_SERVICE_ACTION =
113 "com.android.location.service.v2.NetworkLocationProvider";
114 private static final String FUSED_LOCATION_SERVICE_ACTION =
115 "com.android.location.service.FusedLocationProvider";
116
117 private static final int MSG_LOCATION_CHANGED = 1;
118
David Christie1b9b7b12013-04-15 15:31:11 -0700119 private static final long NANOS_PER_MILLI = 1000000L;
120
Nick Pellyf1be6862012-05-15 10:53:42 -0700121 // Location Providers may sometimes deliver location updates
122 // slightly faster that requested - provide grace period so
123 // we don't unnecessarily filter events that are otherwise on
124 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700125 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700126
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700127 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
128
129 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800130 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700131
132 // used internally for synchronization
133 private final Object mLock = new Object();
134
Victoria Lease5cd731a2012-12-19 15:04:21 -0800135 // --- fields below are final after systemReady() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700136 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700137 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700138 private PackageManager mPackageManager;
Victoria Leasea9770e42013-05-29 15:28:26 -0700139 private PowerManager mPowerManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700140 private GeocoderProxy mGeocodeProvider;
141 private IGpsStatusProvider mGpsStatusProvider;
142 private INetInitiatedListener mNetInitiatedListener;
143 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700144 private PassiveProvider mPassiveProvider; // track passive provider for special cases
145 private LocationBlacklist mBlacklist;
Victoria Lease5cd731a2012-12-19 15:04:21 -0800146 private HandlerThread mHandlerThread;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700147
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700148 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149 // Set of providers that are explicitly enabled
150 private final Set<String> mEnabledProviders = new HashSet<String>();
151
152 // Set of providers that are explicitly disabled
153 private final Set<String> mDisabledProviders = new HashSet<String>();
154
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700155 // Mock (test) providers
156 private final HashMap<String, MockProvider> mMockProviders =
157 new HashMap<String, MockProvider>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700159 // all receivers
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400160 private final HashMap<Object, Receiver> mReceivers = new HashMap<Object, Receiver>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700162 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500163 private final ArrayList<LocationProviderInterface> mProviders =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700164 new ArrayList<LocationProviderInterface>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400165
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700166 // real providers, saved here when mocked out
167 private final HashMap<String, LocationProviderInterface> mRealProviders =
168 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700170 // mapping from provider name to provider
171 private final HashMap<String, LocationProviderInterface> mProvidersByName =
172 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700174 // mapping from provider name to all its UpdateRecords
175 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
176 new HashMap<String, ArrayList<UpdateRecord>>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700177
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700178 // mapping from provider name to last known location
179 private final HashMap<String, Location> mLastLocation = new HashMap<String, Location>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
David Christie1b9b7b12013-04-15 15:31:11 -0700181 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
182 // locations stored here are not fudged for coarse permissions.
183 private final HashMap<String, Location> mLastLocationCoarseInterval =
184 new HashMap<String, Location>();
185
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 // all providers that operate over proxy, for authorizing incoming location
187 private final ArrayList<LocationProviderProxy> mProxyProviders =
188 new ArrayList<LocationProviderProxy>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Victoria Lease38389b62012-09-30 11:44:22 -0700190 // current active user on the device - other users are denied location data
191 private int mCurrentUserId = UserHandle.USER_OWNER;
192
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700193 public LocationManagerService(Context context) {
194 super();
195 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800196 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800197
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700198 if (D) Log.d(TAG, "Constructed");
199
200 // most startup is deferred until systemReady()
201 }
202
203 public void systemReady() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700204 synchronized (mLock) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800205 if (D) Log.d(TAG, "systemReady()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700206
Victoria Lease5cd731a2012-12-19 15:04:21 -0800207 // fetch package manager
208 mPackageManager = mContext.getPackageManager();
209
Victoria Leasea9770e42013-05-29 15:28:26 -0700210 // fetch power manager
211 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800212
213 // prepare worker thread
214 mHandlerThread = new HandlerThread(THREAD_NAME, Process.THREAD_PRIORITY_BACKGROUND);
215 mHandlerThread.start();
216 mLocationHandler = new LocationWorkerHandler(mHandlerThread.getLooper());
217
218 // prepare mLocationHandler's dependents
219 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
220 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
221 mBlacklist.init();
222 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
223
Dianne Hackbornc2293022013-02-06 23:14:49 -0800224 // Monitor for app ops mode changes.
225 AppOpsManager.Callback callback = new AppOpsManager.Callback() {
226 public void opChanged(int op, String packageName) {
227 synchronized (mLock) {
228 applyAllProviderRequirementsLocked();
229 }
230 }
231 };
232 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
233
Victoria Lease5cd731a2012-12-19 15:04:21 -0800234 // prepare providers
235 loadProvidersLocked();
236 updateProvidersLocked();
237 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700238
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700239 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700240 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700241 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700242 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800243 @Override
244 public void onChange(boolean selfChange) {
245 synchronized (mLock) {
246 updateProvidersLocked();
247 }
248 }
249 }, UserHandle.USER_ALL);
250 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700251
Victoria Lease38389b62012-09-30 11:44:22 -0700252 // listen for user change
253 IntentFilter intentFilter = new IntentFilter();
254 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
255
256 mContext.registerReceiverAsUser(new BroadcastReceiver() {
257 @Override
258 public void onReceive(Context context, Intent intent) {
259 String action = intent.getAction();
260 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
261 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
262 }
263 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800264 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700265 }
266
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500267 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
268 PackageManager pm = mContext.getPackageManager();
269 String systemPackageName = mContext.getPackageName();
270 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
271
272 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
273 new Intent(FUSED_LOCATION_SERVICE_ACTION),
274 PackageManager.GET_META_DATA, mCurrentUserId);
275 for (ResolveInfo rInfo : rInfos) {
276 String packageName = rInfo.serviceInfo.packageName;
277
278 // Check that the signature is in the list of supported sigs. If it's not in
279 // this list the standard provider binding logic won't bind to it.
280 try {
281 PackageInfo pInfo;
282 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
283 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
284 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
285 ", but has wrong signature, ignoring");
286 continue;
287 }
288 } catch (NameNotFoundException e) {
289 Log.e(TAG, "missing package: " + packageName);
290 continue;
291 }
292
293 // Get the version info
294 if (rInfo.serviceInfo.metaData == null) {
295 Log.w(TAG, "Found fused provider without metadata: " + packageName);
296 continue;
297 }
298
299 int version = rInfo.serviceInfo.metaData.getInt(
300 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
301 if (version == 0) {
302 // This should be the fallback fused location provider.
303
304 // Make sure it's in the system partition.
305 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
306 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
307 continue;
308 }
309
310 // Check that the fallback is signed the same as the OS
311 // as a proxy for coreApp="true"
312 if (pm.checkSignatures(systemPackageName, packageName)
313 != PackageManager.SIGNATURE_MATCH) {
314 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
315 + packageName);
316 continue;
317 }
318
319 // Found a valid fallback.
320 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
321 return;
322 } else {
323 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
324 }
325 }
326
327 throw new IllegalStateException("Unable to find a fused location provider that is in the "
328 + "system partition with version 0 and signed with the platform certificate. "
329 + "Such a package is needed to provide a default fused location provider in the "
330 + "event that no other fused location provider has been installed or is currently "
331 + "available. For example, coreOnly boot mode when decrypting the data "
332 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
333 }
334
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700335 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700336 // create a passive location provider, which is always enabled
337 PassiveProvider passiveProvider = new PassiveProvider(this);
338 addProviderLocked(passiveProvider);
339 mEnabledProviders.add(passiveProvider.getName());
340 mPassiveProvider = passiveProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700341 // Create a gps location provider
342 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
343 mLocationHandler.getLooper());
Victoria Lease5c24fd02012-10-01 11:00:50 -0700344
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700345 if (GpsLocationProvider.isSupported()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700346 mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
347 mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
348 addProviderLocked(gpsProvider);
349 mRealProviders.put(LocationManager.GPS_PROVIDER, gpsProvider);
350 }
351
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700352 /*
353 Load package name(s) containing location provider support.
354 These packages can contain services implementing location providers:
355 Geocoder Provider, Network Location Provider, and
356 Fused Location Provider. They will each be searched for
357 service components implementing these providers.
358 The location framework also has support for installation
359 of new location providers at run-time. The new package does not
360 have to be explicitly listed here, however it must have a signature
361 that matches the signature of at least one package on this list.
362 */
363 Resources resources = mContext.getResources();
364 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500365 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700366 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500367 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
368 Arrays.toString(pkgs));
369 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
370
371 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700372
373 // bind to network provider
374 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
375 mContext,
376 LocationManager.NETWORK_PROVIDER,
377 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700378 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
379 com.android.internal.R.string.config_networkLocationProviderPackageName,
380 com.android.internal.R.array.config_locationProviderPackageNames,
381 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700382 if (networkProvider != null) {
383 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
384 mProxyProviders.add(networkProvider);
385 addProviderLocked(networkProvider);
386 } else {
387 Slog.w(TAG, "no network location provider found");
388 }
389
390 // bind to fused provider
391 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
392 mContext,
393 LocationManager.FUSED_PROVIDER,
394 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700395 com.android.internal.R.bool.config_enableFusedLocationOverlay,
396 com.android.internal.R.string.config_fusedLocationProviderPackageName,
397 com.android.internal.R.array.config_locationProviderPackageNames,
398 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700399 if (fusedLocationProvider != null) {
400 addProviderLocked(fusedLocationProvider);
401 mProxyProviders.add(fusedLocationProvider);
402 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700403 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700404 } else {
405 Slog.e(TAG, "no fused location provider found",
406 new IllegalStateException("Location service needs a fused location provider"));
407 }
408
409 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700410 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
411 com.android.internal.R.bool.config_enableGeocoderOverlay,
412 com.android.internal.R.string.config_geocoderProviderPackageName,
413 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800414 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700415 if (mGeocodeProvider == null) {
416 Slog.e(TAG, "no geocoder provider found");
417 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700418
419 // bind to geofence provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700420 GeofenceProxy provider = GeofenceProxy.createAndBind(mContext,
421 com.android.internal.R.bool.config_enableGeofenceOverlay,
422 com.android.internal.R.string.config_geofenceProviderPackageName,
423 com.android.internal.R.array.config_locationProviderPackageNames,
424 mLocationHandler,
425 gpsProvider.getGpsGeofenceProxy());
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700426 if (provider == null) {
427 Slog.e(TAG, "no geofence provider found");
428 }
429
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700430 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700431
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800432 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700433 * Called when the device's active user changes.
434 * @param userId the new active user's UserId
435 */
436 private void switchUser(int userId) {
Victoria Lease83762d22012-10-03 13:51:17 -0700437 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800438 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700439 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700440 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700441 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700442 for (LocationProviderInterface p : mProviders) {
443 updateProviderListenersLocked(p.getName(), false, mCurrentUserId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700444 }
Victoria Lease38389b62012-09-30 11:44:22 -0700445 mCurrentUserId = userId;
Victoria Leaseb711d572012-10-02 13:14:11 -0700446 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700447 }
448 }
449
450 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
452 * location updates.
453 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700454 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700455 final int mUid; // uid of receiver
456 final int mPid; // pid of receiver
457 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700458 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700459
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800460 final ILocationListener mListener;
461 final PendingIntent mPendingIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800462 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700463
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400464 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700465
Mike Lockwood48f17512009-04-23 09:12:08 -0700466 int mPendingBroadcasts;
Victoria Leasea9770e42013-05-29 15:28:26 -0700467 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700469 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
470 String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800472 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700473 if (listener != null) {
474 mKey = listener.asBinder();
475 } else {
476 mKey = intent;
477 }
Victoria Lease37425c32012-10-16 16:08:48 -0700478 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700479 mUid = uid;
480 mPid = pid;
481 mPackageName = packageName;
Victoria Leasea9770e42013-05-29 15:28:26 -0700482
483 // construct/configure wakelock
484 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
485 mWakeLock.setWorkSource(new WorkSource(mUid, mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800486 }
487
488 @Override
489 public boolean equals(Object otherObj) {
490 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700491 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800492 }
493 return false;
494 }
495
496 @Override
497 public int hashCode() {
498 return mKey.hashCode();
499 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800501 @Override
502 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700503 StringBuilder s = new StringBuilder();
504 s.append("Reciever[");
505 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700507 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800508 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700509 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800510 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700511 for (String p : mUpdateRecords.keySet()) {
512 s.append(" ").append(mUpdateRecords.get(p).toString());
513 }
514 s.append("]");
515 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800516 }
517
518 public boolean isListener() {
519 return mListener != null;
520 }
521
522 public boolean isPendingIntent() {
523 return mPendingIntent != null;
524 }
525
526 public ILocationListener getListener() {
527 if (mListener != null) {
528 return mListener;
529 }
530 throw new IllegalStateException("Request for non-existent listener");
531 }
532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800533 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
534 if (mListener != null) {
535 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700536 synchronized (this) {
537 // synchronize to ensure incrementPendingBroadcastsLocked()
538 // is called before decrementPendingBroadcasts()
539 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700540 // call this after broadcasting so we do not increment
541 // if we throw an exeption.
542 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700543 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800544 } catch (RemoteException e) {
545 return false;
546 }
547 } else {
548 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800549 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
551 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700552 synchronized (this) {
553 // synchronize to ensure incrementPendingBroadcastsLocked()
554 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700555 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700556 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700557 // call this after broadcasting so we do not increment
558 // if we throw an exeption.
559 incrementPendingBroadcastsLocked();
560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800561 } catch (PendingIntent.CanceledException e) {
562 return false;
563 }
564 }
565 return true;
566 }
567
568 public boolean callLocationChangedLocked(Location location) {
569 if (mListener != null) {
570 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700571 synchronized (this) {
572 // synchronize to ensure incrementPendingBroadcastsLocked()
573 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800574 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700575 // call this after broadcasting so we do not increment
576 // if we throw an exeption.
577 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 } catch (RemoteException e) {
580 return false;
581 }
582 } else {
583 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800584 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800585 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700586 synchronized (this) {
587 // synchronize to ensure incrementPendingBroadcastsLocked()
588 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700589 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700590 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700591 // call this after broadcasting so we do not increment
592 // if we throw an exeption.
593 incrementPendingBroadcastsLocked();
594 }
595 } catch (PendingIntent.CanceledException e) {
596 return false;
597 }
598 }
599 return true;
600 }
601
602 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
603 if (mListener != null) {
604 try {
605 synchronized (this) {
606 // synchronize to ensure incrementPendingBroadcastsLocked()
607 // is called before decrementPendingBroadcasts()
608 if (enabled) {
609 mListener.onProviderEnabled(provider);
610 } else {
611 mListener.onProviderDisabled(provider);
612 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700613 // call this after broadcasting so we do not increment
614 // if we throw an exeption.
615 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700616 }
617 } catch (RemoteException e) {
618 return false;
619 }
620 } else {
621 Intent providerIntent = new Intent();
622 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
623 try {
624 synchronized (this) {
625 // synchronize to ensure incrementPendingBroadcastsLocked()
626 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700627 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700628 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700629 // call this after broadcasting so we do not increment
630 // if we throw an exeption.
631 incrementPendingBroadcastsLocked();
632 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 } catch (PendingIntent.CanceledException e) {
634 return false;
635 }
636 }
637 return true;
638 }
639
Nick Pellyf1be6862012-05-15 10:53:42 -0700640 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700642 if (D) Log.d(TAG, "Location listener died");
643
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400644 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800645 removeUpdatesLocked(this);
646 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700647 synchronized (this) {
Victoria Leasea9770e42013-05-29 15:28:26 -0700648 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700649 }
650 }
651
Nick Pellye0fd6932012-07-11 10:26:13 -0700652 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700653 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
654 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400655 synchronized (this) {
656 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700657 }
658 }
659
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400660 // this must be called while synchronized by caller in a synchronized block
661 // containing the sending of the broadcaset
662 private void incrementPendingBroadcastsLocked() {
663 if (mPendingBroadcasts++ == 0) {
Victoria Leasea9770e42013-05-29 15:28:26 -0700664 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400665 }
666 }
667
668 private void decrementPendingBroadcastsLocked() {
669 if (--mPendingBroadcasts == 0) {
Victoria Leasea9770e42013-05-29 15:28:26 -0700670 if (mWakeLock.isHeld()) {
671 mWakeLock.release();
672 }
673 }
674 }
675
676 public void clearPendingBroadcastsLocked() {
677 if (mPendingBroadcasts > 0) {
678 mPendingBroadcasts = 0;
679 if (mWakeLock.isHeld()) {
680 mWakeLock.release();
681 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700682 }
683 }
684 }
685
Nick Pellye0fd6932012-07-11 10:26:13 -0700686 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700687 public void locationCallbackFinished(ILocationListener listener) {
Joshua Bartel080b61b2009-10-05 12:44:46 -0400688 //Do not use getReceiver here as that will add the ILocationListener to
689 //the receiver list if it is not found. If it is not found then the
690 //LocationListener was removed when it had a pending broadcast and should
691 //not be added back.
692 IBinder binder = listener.asBinder();
693 Receiver receiver = mReceivers.get(binder);
Mike Lockwood48f17512009-04-23 09:12:08 -0700694 if (receiver != null) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400695 synchronized (receiver) {
696 // so wakelock calls will succeed
697 long identity = Binder.clearCallingIdentity();
698 receiver.decrementPendingBroadcastsLocked();
699 Binder.restoreCallingIdentity(identity);
700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800701 }
702 }
703
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700704 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400705 mProviders.add(provider);
706 mProvidersByName.put(provider.getName(), provider);
707 }
708
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700709 private void removeProviderLocked(LocationProviderInterface provider) {
710 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400711 mProviders.remove(provider);
712 mProvidersByName.remove(provider.getName());
713 }
714
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800715 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800716 * Returns "true" if access to the specified location provider is allowed by the current
717 * user's settings. Access to all location providers is forbidden to non-location-provider
718 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800719 *
720 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800721 * @return
722 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800723 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 if (mEnabledProviders.contains(provider)) {
725 return true;
726 }
727 if (mDisabledProviders.contains(provider)) {
728 return false;
729 }
730 // Use system settings
731 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800732
Victoria Leaseb711d572012-10-02 13:14:11 -0700733 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800734 }
735
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700736 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800737 * Returns "true" if access to the specified location provider is allowed by the specified
738 * user's settings. Access to all location providers is forbidden to non-location-provider
739 * processes belonging to background users.
740 *
741 * @param provider the name of the location provider
742 * @param uid the requestor's UID
743 * @return
744 */
745 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
746 if (UserHandle.getUserId(uid) != mCurrentUserId && !isUidALocationProvider(uid)) {
747 return false;
748 }
749 return isAllowedByCurrentUserSettingsLocked(provider);
750 }
751
752 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700753 * Returns the permission string associated with the specified resolution level.
754 *
755 * @param resolutionLevel the resolution level
756 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700757 */
Victoria Lease37425c32012-10-16 16:08:48 -0700758 private String getResolutionPermission(int resolutionLevel) {
759 switch (resolutionLevel) {
760 case RESOLUTION_LEVEL_FINE:
761 return android.Manifest.permission.ACCESS_FINE_LOCATION;
762 case RESOLUTION_LEVEL_COARSE:
763 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
764 default:
765 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800766 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700767 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700768
Victoria Leaseda479c52012-10-15 15:24:16 -0700769 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700770 * Returns the resolution level allowed to the given PID/UID pair.
771 *
772 * @param pid the PID
773 * @param uid the UID
774 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -0700775 */
Victoria Lease37425c32012-10-16 16:08:48 -0700776 private int getAllowedResolutionLevel(int pid, int uid) {
777 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
778 pid, uid) == PackageManager.PERMISSION_GRANTED) {
779 return RESOLUTION_LEVEL_FINE;
780 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
781 pid, uid) == PackageManager.PERMISSION_GRANTED) {
782 return RESOLUTION_LEVEL_COARSE;
783 } else {
784 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -0700785 }
Victoria Lease4fab68b2012-09-13 13:20:59 -0700786 }
787
788 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700789 * Returns the resolution level allowed to the caller
790 *
791 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -0700792 */
Victoria Lease37425c32012-10-16 16:08:48 -0700793 private int getCallerAllowedResolutionLevel() {
794 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
795 }
796
797 /**
798 * Throw SecurityException if specified resolution level is insufficient to use geofences.
799 *
800 * @param allowedResolutionLevel resolution level allowed to caller
801 */
802 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
803 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -0700804 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 }
807
Victoria Lease37425c32012-10-16 16:08:48 -0700808 /**
809 * Return the minimum resolution level required to use the specified location provider.
810 *
811 * @param provider the name of the location provider
812 * @return minimum resolution level required for provider
813 */
814 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -0700815 if (LocationManager.GPS_PROVIDER.equals(provider) ||
816 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
817 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -0700818 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -0700819 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
820 LocationManager.FUSED_PROVIDER.equals(provider)) {
821 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -0700822 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -0700823 } else {
824 // mock providers
825 LocationProviderInterface lp = mMockProviders.get(provider);
826 if (lp != null) {
827 ProviderProperties properties = lp.getProperties();
828 if (properties != null) {
829 if (properties.mRequiresSatellite) {
830 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -0700831 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -0700832 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
833 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -0700834 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -0700835 }
836 }
837 }
Victoria Lease8dbb6342012-09-21 16:55:53 -0700838 }
Victoria Lease37425c32012-10-16 16:08:48 -0700839 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -0700840 }
841
Victoria Lease37425c32012-10-16 16:08:48 -0700842 /**
843 * Throw SecurityException if specified resolution level is insufficient to use the named
844 * location provider.
845 *
846 * @param allowedResolutionLevel resolution level allowed to caller
847 * @param providerName the name of the location provider
848 */
849 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
850 String providerName) {
851 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
852 if (allowedResolutionLevel < requiredResolutionLevel) {
853 switch (requiredResolutionLevel) {
854 case RESOLUTION_LEVEL_FINE:
855 throw new SecurityException("\"" + providerName + "\" location provider " +
856 "requires ACCESS_FINE_LOCATION permission.");
857 case RESOLUTION_LEVEL_COARSE:
858 throw new SecurityException("\"" + providerName + "\" location provider " +
859 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
860 default:
861 throw new SecurityException("Insufficient permission for \"" + providerName +
862 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -0700863 }
864 }
Victoria Lease8dbb6342012-09-21 16:55:53 -0700865 }
866
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800867 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800868 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
869 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800870 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800871 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800872 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800873 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800874 }
875 return -1;
876 }
877
878 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
879 int op = resolutionLevelToOp(allowedResolutionLevel);
880 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800881 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
882 return false;
883 }
884 }
885 return true;
886 }
887
888 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800889 int op = resolutionLevelToOp(allowedResolutionLevel);
890 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800891 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
892 return false;
893 }
894 }
895 return true;
896 }
897
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700898 /**
899 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -0700900 * fused, also including ones that are not permitted to
901 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700902 */
Nick Pellye0fd6932012-07-11 10:26:13 -0700903 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800904 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700905 ArrayList<String> out;
906 synchronized (mLock) {
907 out = new ArrayList<String>(mProviders.size());
908 for (LocationProviderInterface provider : mProviders) {
909 String name = provider.getName();
910 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -0700911 continue;
912 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 out.add(name);
914 }
915 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700916
917 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 return out;
919 }
920
Mike Lockwood03ca2162010-04-01 08:10:09 -0700921 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700922 * Return all providers by name, that match criteria and are optionally
923 * enabled.
924 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -0700925 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700926 @Override
927 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -0700928 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700929 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800930 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -0700931 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -0700932 try {
933 synchronized (mLock) {
934 out = new ArrayList<String>(mProviders.size());
935 for (LocationProviderInterface provider : mProviders) {
936 String name = provider.getName();
937 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -0700938 continue;
939 }
Victoria Lease37425c32012-10-16 16:08:48 -0700940 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800941 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700942 continue;
943 }
944 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
945 name, provider.getProperties(), criteria)) {
946 continue;
947 }
948 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -0700949 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700950 }
Mike Lockwood03ca2162010-04-01 08:10:09 -0700951 }
Victoria Leaseb711d572012-10-02 13:14:11 -0700952 } finally {
953 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -0700954 }
955
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700956 if (D) Log.d(TAG, "getProviders()=" + out);
957 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -0700958 }
959
960 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700961 * Return the name of the best provider given a Criteria object.
962 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -0700963 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700964 * has been deprecated as well. So this method now uses
965 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -0700966 */
Nick Pellye0fd6932012-07-11 10:26:13 -0700967 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -0700968 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700969 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700970
971 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -0700972 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700973 result = pickBest(providers);
974 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
975 return result;
976 }
977 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -0700978 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700979 result = pickBest(providers);
980 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
981 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -0700982 }
983
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700984 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -0700985 return null;
986 }
987
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700988 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -0700989 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700990 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -0700991 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
992 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700993 } else {
994 return providers.get(0);
995 }
996 }
997
Nick Pellye0fd6932012-07-11 10:26:13 -0700998 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -0700999 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1000 LocationProviderInterface p = mProvidersByName.get(provider);
1001 if (p == null) {
1002 throw new IllegalArgumentException("provider=" + provider);
1003 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001004
1005 boolean result = LocationProvider.propertiesMeetCriteria(
1006 p.getName(), p.getProperties(), criteria);
1007 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1008 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001009 }
1010
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001012 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001013 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001014 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 boolean isEnabled = p.isEnabled();
1016 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001017 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 if (isEnabled && !shouldBeEnabled) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001019 updateProviderListenersLocked(name, false, mCurrentUserId);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001020 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 } else if (!isEnabled && shouldBeEnabled) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001022 updateProviderListenersLocked(name, true, mCurrentUserId);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001023 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001024 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001025 }
1026 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001027 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1028 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
1030 }
1031
Victoria Leaseb711d572012-10-02 13:14:11 -07001032 private void updateProviderListenersLocked(String provider, boolean enabled, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001033 int listeners = 0;
1034
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001035 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001036 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001037
1038 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001039
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001040 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1041 if (records != null) {
1042 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001043 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 UpdateRecord record = records.get(i);
Victoria Lease269518e2012-10-29 08:25:39 -07001045 if (UserHandle.getUserId(record.mReceiver.mUid) == userId) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001046 // Sends a notification message to the receiver
1047 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1048 if (deadReceivers == null) {
1049 deadReceivers = new ArrayList<Receiver>();
1050 }
1051 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001053 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
1056 }
1057
1058 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001059 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 removeUpdatesLocked(deadReceivers.get(i));
1061 }
1062 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 if (enabled) {
1065 p.enable();
1066 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001067 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001074 private void applyRequirementsLocked(String provider) {
1075 LocationProviderInterface p = mProvidersByName.get(provider);
1076 if (p == null) return;
1077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001078 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001079 WorkSource worksource = new WorkSource();
1080 ProviderRequest providerRequest = new ProviderRequest();
1081
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001083 for (UpdateRecord record : records) {
Victoria Lease269518e2012-10-29 08:25:39 -07001084 if (UserHandle.getUserId(record.mReceiver.mUid) == mCurrentUserId) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001085 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1086 record.mReceiver.mAllowedResolutionLevel)) {
1087 LocationRequest locationRequest = record.mRequest;
1088 providerRequest.locationRequests.add(locationRequest);
1089 if (locationRequest.getInterval() < providerRequest.interval) {
1090 providerRequest.reportLocation = true;
1091 providerRequest.interval = locationRequest.getInterval();
1092 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001093 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001094 }
1095 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001096
1097 if (providerRequest.reportLocation) {
1098 // calculate who to blame for power
1099 // This is somewhat arbitrary. We pick a threshold interval
1100 // that is slightly higher that the minimum interval, and
1101 // spread the blame across all applications with a request
1102 // under that threshold.
1103 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1104 for (UpdateRecord record : records) {
Victoria Lease269518e2012-10-29 08:25:39 -07001105 if (UserHandle.getUserId(record.mReceiver.mUid) == mCurrentUserId) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001106 LocationRequest locationRequest = record.mRequest;
1107 if (locationRequest.getInterval() <= thresholdInterval) {
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001108 worksource.add(record.mReceiver.mUid, record.mReceiver.mPackageName);
Victoria Leaseb711d572012-10-02 13:14:11 -07001109 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001110 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001114
1115 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1116 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118
1119 private class UpdateRecord {
1120 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001121 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001122 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001123 Location mLastFixBroadcast;
1124 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125
1126 /**
1127 * Note: must be constructed with lock held.
1128 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001129 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001131 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133
1134 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1135 if (records == null) {
1136 records = new ArrayList<UpdateRecord>();
1137 mRecordsByProvider.put(provider, records);
1138 }
1139 if (!records.contains(this)) {
1140 records.add(this);
1141 }
1142 }
1143
1144 /**
1145 * Method to be called when a record will no longer be used. Calling this multiple times
1146 * must have the same effect as calling it once.
1147 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001148 void disposeLocked(boolean removeReceiver) {
1149 // remove from mRecordsByProvider
1150 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1151 if (globalRecords != null) {
1152 globalRecords.remove(this);
1153 }
1154
1155 if (!removeReceiver) return; // the caller will handle the rest
1156
1157 // remove from Receiver#mUpdateRecords
1158 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1159 if (receiverRecords != null) {
1160 receiverRecords.remove(this.mProvider);
1161
1162 // and also remove the Receiver if it has no more update records
1163 if (removeReceiver && receiverRecords.size() == 0) {
1164 removeUpdatesLocked(mReceiver);
1165 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001167 }
1168
1169 @Override
1170 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001171 StringBuilder s = new StringBuilder();
1172 s.append("UpdateRecord[");
1173 s.append(mProvider);
1174 s.append(' ').append(mReceiver.mPackageName).append('(');
1175 s.append(mReceiver.mUid).append(')');
1176 s.append(' ').append(mRequest);
1177 s.append(']');
1178 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 }
1181
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001182 private Receiver getReceiver(ILocationListener listener, int pid, int uid, String packageName) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001183 IBinder binder = listener.asBinder();
1184 Receiver receiver = mReceivers.get(binder);
1185 if (receiver == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001186 receiver = new Receiver(listener, null, pid, uid, packageName);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001187 mReceivers.put(binder, receiver);
1188
1189 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001190 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001191 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001192 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001193 return null;
1194 }
1195 }
1196 return receiver;
1197 }
1198
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001199 private Receiver getReceiver(PendingIntent intent, int pid, int uid, String packageName) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001200 Receiver receiver = mReceivers.get(intent);
1201 if (receiver == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001202 receiver = new Receiver(null, intent, pid, uid, packageName);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001203 mReceivers.put(intent, receiver);
1204 }
1205 return receiver;
1206 }
1207
Victoria Lease37425c32012-10-16 16:08:48 -07001208 /**
1209 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1210 * and consistency requirements.
1211 *
1212 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001213 * @return a version of request that meets the given resolution and consistency requirements
1214 * @hide
1215 */
1216 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1217 LocationRequest sanitizedRequest = new LocationRequest(request);
1218 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1219 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001220 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001221 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001222 break;
1223 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001224 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001225 break;
1226 }
1227 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001228 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1229 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001230 }
Victoria Lease37425c32012-10-16 16:08:48 -07001231 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1232 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001233 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001234 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001235 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001236 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001237 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001238 }
Victoria Lease37425c32012-10-16 16:08:48 -07001239 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001240 }
1241
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001242 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001243 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001244 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001245 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001246 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001247 String[] packages = mPackageManager.getPackagesForUid(uid);
1248 if (packages == null) {
1249 throw new SecurityException("invalid UID " + uid);
1250 }
1251 for (String pkg : packages) {
1252 if (packageName.equals(pkg)) return;
1253 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001254 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001255 }
1256
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001257 private void checkPendingIntent(PendingIntent intent) {
1258 if (intent == null) {
1259 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001260 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001261 }
1262
1263 private Receiver checkListenerOrIntent(ILocationListener listener, PendingIntent intent,
1264 int pid, int uid, String packageName) {
1265 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001266 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001267 } else if (intent != null && listener != null) {
1268 throw new IllegalArgumentException("cannot register both listener and intent");
1269 } else if (intent != null) {
1270 checkPendingIntent(intent);
1271 return getReceiver(intent, pid, uid, packageName);
1272 } else {
1273 return getReceiver(listener, pid, uid, packageName);
1274 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001275 }
1276
Nick Pellye0fd6932012-07-11 10:26:13 -07001277 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001278 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1279 PendingIntent intent, String packageName) {
1280 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1281 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001282 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1283 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1284 request.getProvider());
1285 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001287 final int pid = Binder.getCallingPid();
1288 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001289 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 long identity = Binder.clearCallingIdentity();
1291 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001292 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1293 // a location.
Dianne Hackborn35654b62013-01-14 17:38:02 -08001294 checkLocationAccess(uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001295 Receiver recevier = checkListenerOrIntent(listener, intent, pid, uid, packageName);
1296
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001297 synchronized (mLock) {
Victoria Lease37425c32012-10-16 16:08:48 -07001298 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001299 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 } finally {
1301 Binder.restoreCallingIdentity(identity);
1302 }
1303 }
1304
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001305 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1306 int pid, int uid, String packageName) {
1307 // Figure out the provider. Either its explicitly request (legacy use cases), or
1308 // use the fused provider
1309 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1310 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001311 if (name == null) {
1312 throw new IllegalArgumentException("provider name must not be null");
1313 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001314
1315 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1316 + " " + name + " " + request + " from " + packageName + "(" + uid + ")");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001317 LocationProviderInterface provider = mProvidersByName.get(name);
1318 if (provider == null) {
1319 throw new IllegalArgumentException("provider doesn't exisit: " + provider);
1320 }
1321
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001322 UpdateRecord record = new UpdateRecord(name, request, receiver);
1323 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1324 if (oldRecord != null) {
1325 oldRecord.disposeLocked(false);
1326 }
1327
Victoria Lease09eeaec2013-02-05 11:34:13 -08001328 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001329 if (isProviderEnabled) {
1330 applyRequirementsLocked(name);
1331 } else {
1332 // Notify the listener that updates are currently disabled
1333 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001334 }
1335 }
1336
Nick Pellye0fd6932012-07-11 10:26:13 -07001337 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001338 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1339 String packageName) {
1340 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001341
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001342 final int pid = Binder.getCallingPid();
1343 final int uid = Binder.getCallingUid();
1344 Receiver receiver = checkListenerOrIntent(listener, intent, pid, uid, packageName);
1345
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001346 // providers may use public location API's, need to clear identity
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001347 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 try {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001349 synchronized (mLock) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001350 removeUpdatesLocked(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001352 } finally {
1353 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 }
1355 }
1356
1357 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001358 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001359
1360 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1361 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1362 synchronized (receiver) {
Victoria Leasea9770e42013-05-29 15:28:26 -07001363 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 }
1366
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001367 // Record which providers were associated with this listener
1368 HashSet<String> providers = new HashSet<String>();
1369 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1370 if (oldRecords != null) {
1371 // Call dispose() on the obsolete update records.
1372 for (UpdateRecord record : oldRecords.values()) {
1373 record.disposeLocked(false);
1374 }
1375 // Accumulate providers
1376 providers.addAll(oldRecords.keySet());
1377 }
1378
1379 // update provider
1380 for (String provider : providers) {
1381 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001382 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001383 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001386 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
1388 }
1389
Dianne Hackbornc2293022013-02-06 23:14:49 -08001390 private void applyAllProviderRequirementsLocked() {
1391 for (LocationProviderInterface p : mProviders) {
1392 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001393 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001394 continue;
1395 }
1396
1397 applyRequirementsLocked(p.getName());
1398 }
1399 }
1400
Nick Pellye0fd6932012-07-11 10:26:13 -07001401 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001402 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001403 if (D) Log.d(TAG, "getLastLocation: " + request);
1404 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001405 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001406 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001407 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1408 request.getProvider());
1409 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001410
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001411 final int uid = Binder.getCallingUid();
1412 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001413 try {
1414 if (mBlacklist.isBlacklisted(packageName)) {
1415 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1416 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001417 return null;
1418 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001419
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001420 if (!reportLocationAccessNoThrow(uid, packageName, allowedResolutionLevel)) {
1421 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1422 packageName);
1423 return null;
1424 }
1425
Victoria Leaseb711d572012-10-02 13:14:11 -07001426 synchronized (mLock) {
1427 // Figure out the provider. Either its explicitly request (deprecated API's),
1428 // or use the fused provider
1429 String name = request.getProvider();
1430 if (name == null) name = LocationManager.FUSED_PROVIDER;
1431 LocationProviderInterface provider = mProvidersByName.get(name);
1432 if (provider == null) return null;
1433
Victoria Lease09eeaec2013-02-05 11:34:13 -08001434 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001435
David Christie1b9b7b12013-04-15 15:31:11 -07001436 Location location;
1437 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1438 // Make sure that an app with coarse permissions can't get frequent location
1439 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1440 location = mLastLocationCoarseInterval.get(name);
1441 } else {
1442 location = mLastLocation.get(name);
1443 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001444 if (location == null) {
1445 return null;
1446 }
Victoria Lease37425c32012-10-16 16:08:48 -07001447 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001448 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1449 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001450 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001451 }
Victoria Lease37425c32012-10-16 16:08:48 -07001452 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001453 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001454 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001455 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001456 return null;
1457 } finally {
1458 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001459 }
1460 }
1461
1462 @Override
1463 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1464 String packageName) {
1465 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001466 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1467 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001468 checkPendingIntent(intent);
1469 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001470 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1471 request.getProvider());
1472 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001473
Victoria Lease37425c32012-10-16 16:08:48 -07001474 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001475
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001476 // geo-fence manager uses the public location API, need to clear identity
1477 int uid = Binder.getCallingUid();
Victoria Lease56e675b2012-11-05 19:25:06 -08001478 if (UserHandle.getUserId(uid) != UserHandle.USER_OWNER) {
1479 // temporary measure until geofences work for secondary users
1480 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1481 return;
1482 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001483 long identity = Binder.clearCallingIdentity();
1484 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001485 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1486 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001487 } finally {
1488 Binder.restoreCallingIdentity(identity);
1489 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001490 }
1491
1492 @Override
1493 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Victoria Lease37425c32012-10-16 16:08:48 -07001494 checkResolutionLevelIsSufficientForGeofenceUse(getCallerAllowedResolutionLevel());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001495 checkPendingIntent(intent);
1496 checkPackageName(packageName);
1497
1498 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1499
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001500 // geo-fence manager uses the public location API, need to clear identity
1501 long identity = Binder.clearCallingIdentity();
1502 try {
1503 mGeofenceManager.removeFence(geofence, intent);
1504 } finally {
1505 Binder.restoreCallingIdentity(identity);
1506 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001507 }
1508
1509
1510 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001511 public boolean addGpsStatusListener(IGpsStatusListener listener, String packageName) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001512 if (mGpsStatusProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001513 return false;
1514 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001515 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1516 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001517 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001519 final int uid = Binder.getCallingUid();
1520 final long ident = Binder.clearCallingIdentity();
1521 try {
Victoria Lease3d5173d2013-02-05 16:07:32 -08001522 if (!checkLocationAccess(uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001523 return false;
1524 }
1525 } finally {
1526 Binder.restoreCallingIdentity(ident);
1527 }
1528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 try {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001530 mGpsStatusProvider.addGpsStatusListener(listener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001532 Slog.e(TAG, "mGpsStatusProvider.addGpsStatusListener failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 return false;
1534 }
1535 return true;
1536 }
1537
Nick Pellye0fd6932012-07-11 10:26:13 -07001538 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 public void removeGpsStatusListener(IGpsStatusListener listener) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001540 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001541 try {
1542 mGpsStatusProvider.removeGpsStatusListener(listener);
1543 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001544 Slog.e(TAG, "mGpsStatusProvider.removeGpsStatusListener failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001545 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001546 }
1547 }
1548
Nick Pellye0fd6932012-07-11 10:26:13 -07001549 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001551 if (provider == null) {
1552 // throw NullPointerException to remain compatible with previous implementation
1553 throw new NullPointerException();
1554 }
Victoria Lease37425c32012-10-16 16:08:48 -07001555 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1556 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001559 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 != PackageManager.PERMISSION_GRANTED)) {
1561 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1562 }
1563
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001564 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001565 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001566 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001567
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001568 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 }
1570 }
1571
Nick Pellye0fd6932012-07-11 10:26:13 -07001572 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001573 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001574 if (Binder.getCallingUid() != Process.myUid()) {
1575 throw new SecurityException(
1576 "calling sendNiResponse from outside of the system is not allowed");
1577 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001578 try {
1579 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001580 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001581 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001582 return false;
1583 }
1584 }
1585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001586 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001587 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001588 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 * accessed by the caller
1590 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001591 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001592 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001593 if (mProvidersByName.get(provider) == null) {
1594 return null;
1595 }
1596
Victoria Lease37425c32012-10-16 16:08:48 -07001597 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1598 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001600 LocationProviderInterface p;
1601 synchronized (mLock) {
1602 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001603 }
1604
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001605 if (p == null) return null;
1606 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
1608
Nick Pellye0fd6932012-07-11 10:26:13 -07001609 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 public boolean isProviderEnabled(String provider) {
Victoria Lease37425c32012-10-16 16:08:48 -07001611 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1612 provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1614
Victoria Lease09eeaec2013-02-05 11:34:13 -08001615 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001616 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001617 try {
1618 synchronized (mLock) {
1619 LocationProviderInterface p = mProvidersByName.get(provider);
1620 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001621
Victoria Lease09eeaec2013-02-05 11:34:13 -08001622 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001623 }
1624 } finally {
1625 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001626 }
1627 }
1628
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001629 /**
1630 * Returns "true" if the UID belongs to a bound location provider.
1631 *
1632 * @param uid the uid
1633 * @return true if uid belongs to a bound location provider
1634 */
1635 private boolean isUidALocationProvider(int uid) {
1636 if (uid == Process.SYSTEM_UID) {
1637 return true;
1638 }
1639 if (mGeocodeProvider != null) {
1640 if (doesPackageHaveUid(uid, mGeocodeProvider.getConnectedPackageName())) return true;
1641 }
1642 for (LocationProviderProxy proxy : mProxyProviders) {
1643 if (doesPackageHaveUid(uid, proxy.getConnectedPackageName())) return true;
1644 }
1645 return false;
1646 }
1647
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001648 private void checkCallerIsProvider() {
1649 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
1650 == PackageManager.PERMISSION_GRANTED) {
1651 return;
1652 }
1653
1654 // Previously we only used the INSTALL_LOCATION_PROVIDER
1655 // check. But that is system or signature
1656 // protection level which is not flexible enough for
1657 // providers installed oustide the system image. So
1658 // also allow providers with a UID matching the
1659 // currently bound package name
1660
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001661 if (isUidALocationProvider(Binder.getCallingUid())) {
1662 return;
1663 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001664
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001665 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
1666 "or UID of a currently bound location provider");
1667 }
1668
1669 private boolean doesPackageHaveUid(int uid, String packageName) {
1670 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 return false;
1672 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001673 try {
1674 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(packageName, 0);
1675 if (appInfo.uid != uid) {
1676 return false;
1677 }
1678 } catch (NameNotFoundException e) {
1679 return false;
1680 }
1681 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001682 }
1683
Nick Pellye0fd6932012-07-11 10:26:13 -07001684 @Override
Mike Lockwooda4903f252010-02-17 06:42:23 -05001685 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001686 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04001687
Nick Pelly2eeeec22012-07-18 13:13:37 -07001688 if (!location.isComplete()) {
1689 Log.w(TAG, "Dropping incomplete location: " + location);
1690 return;
1691 }
1692
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001693 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
1694 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f252010-02-17 06:42:23 -05001695 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07001696 mLocationHandler.sendMessageAtFrontOfQueue(m);
1697 }
1698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699
Laurent Tu75defb62012-11-01 16:21:52 -07001700 private static boolean shouldBroadcastSafe(
1701 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 // Always broadcast the first update
1703 if (lastLoc == null) {
1704 return true;
1705 }
1706
Nick Pellyf1be6862012-05-15 10:53:42 -07001707 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001708 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07001709 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
1710 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001711 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 return false;
1713 }
1714
1715 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001716 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 if (minDistance > 0.0) {
1718 if (loc.distanceTo(lastLoc) <= minDistance) {
1719 return false;
1720 }
1721 }
1722
Laurent Tu75defb62012-11-01 16:21:52 -07001723 // Check whether sufficient number of udpates is left
1724 if (record.mRequest.getNumUpdates() <= 0) {
1725 return false;
1726 }
1727
1728 // Check whether the expiry date has passed
1729 if (record.mRequest.getExpireAt() < now) {
1730 return false;
1731 }
1732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001733 return true;
1734 }
1735
Mike Lockwooda4903f252010-02-17 06:42:23 -05001736 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001737 if (D) Log.d(TAG, "incoming location: " + location);
1738
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001739 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f252010-02-17 06:42:23 -05001740 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741
Laurent Tu60ec50a2012-10-04 17:00:10 -07001742 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001743 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001744 if (p == null) return;
1745
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001746 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07001747 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1748 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001749 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07001750 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001751 lastLocation = new Location(provider);
1752 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07001753 } else {
1754 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1755 if (noGPSLocation == null && lastNoGPSLocation != null) {
1756 // New location has no no-GPS location: adopt last no-GPS location. This is set
1757 // directly into location because we do not want to notify COARSE clients.
1758 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
1759 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07001760 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001761 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762
David Christie1b9b7b12013-04-15 15:31:11 -07001763 // Update last known coarse interval location if enough time has passed.
1764 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
1765 if (lastLocationCoarseInterval == null) {
1766 lastLocationCoarseInterval = new Location(location);
1767 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
1768 }
1769 long timeDiffNanos = location.getElapsedRealtimeNanos()
1770 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
1771 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
1772 lastLocationCoarseInterval.set(location);
1773 }
1774 // Don't ever return a coarse location that is more recent than the allowed update
1775 // interval (i.e. don't allow an app to keep registering and unregistering for
1776 // location updates to overcome the minimum interval).
1777 noGPSLocation =
1778 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1779
Laurent Tu60ec50a2012-10-04 17:00:10 -07001780 // Skip if there are no UpdateRecords for this provider.
1781 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1782 if (records == null || records.size() == 0) return;
1783
Victoria Lease09016ab2012-09-16 12:33:15 -07001784 // Fetch coarse location
1785 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07001786 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001787 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
1788 }
1789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 // Fetch latest status update time
1791 long newStatusUpdateTime = p.getStatusUpdateTime();
1792
Mike Lockwood7ec434e2009-03-27 07:46:48 -07001793 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 Bundle extras = new Bundle();
1795 int status = p.getStatus(extras);
1796
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001798 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001801 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001803 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07001804
Victoria Lease269518e2012-10-29 08:25:39 -07001805 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Victoria Leased9ba79e2013-05-07 14:22:02 -07001806 if (receiverUserId != mCurrentUserId && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001807 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07001808 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07001809 " (current user: " + mCurrentUserId + ", app: " +
1810 receiver.mPackageName + ")");
1811 }
1812 continue;
1813 }
1814
Nick Pelly4035f5a2012-08-17 14:43:49 -07001815 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
1816 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
1817 receiver.mPackageName);
1818 continue;
1819 }
1820
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001821 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
1822 receiver.mAllowedResolutionLevel)) {
1823 if (D) Log.d(TAG, "skipping loc update for no op app: " +
1824 receiver.mPackageName);
1825 continue;
1826 }
1827
Victoria Lease09016ab2012-09-16 12:33:15 -07001828 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07001829 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1830 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001831 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07001832 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001833 }
Victoria Lease09016ab2012-09-16 12:33:15 -07001834 if (notifyLocation != null) {
1835 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07001836 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001837 if (lastLoc == null) {
1838 lastLoc = new Location(notifyLocation);
1839 r.mLastFixBroadcast = lastLoc;
1840 } else {
1841 lastLoc.set(notifyLocation);
1842 }
1843 if (!receiver.callLocationChangedLocked(notifyLocation)) {
1844 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
1845 receiverDead = true;
1846 }
Laurent Tu75defb62012-11-01 16:21:52 -07001847 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 }
1849 }
1850
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001851 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07001853 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001855 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001857 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001858 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001859 }
1860 }
1861
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001862 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07001863 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001864 if (deadUpdateRecords == null) {
1865 deadUpdateRecords = new ArrayList<UpdateRecord>();
1866 }
1867 deadUpdateRecords.add(r);
1868 }
1869 // track dead receivers
1870 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001871 if (deadReceivers == null) {
1872 deadReceivers = new ArrayList<Receiver>();
1873 }
1874 if (!deadReceivers.contains(receiver)) {
1875 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001876 }
1877 }
1878 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001879
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001880 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001882 for (Receiver receiver : deadReceivers) {
1883 removeUpdatesLocked(receiver);
1884 }
1885 }
1886 if (deadUpdateRecords != null) {
1887 for (UpdateRecord r : deadUpdateRecords) {
1888 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001889 }
Victoria Lease8b38b292012-12-04 15:04:43 -08001890 applyRequirementsLocked(provider);
1891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
1894 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08001895 public LocationWorkerHandler(Looper looper) {
1896 super(looper, null, true);
1897 }
1898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 @Override
1900 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001901 switch (msg.what) {
1902 case MSG_LOCATION_CHANGED:
1903 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
1904 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 }
1906 }
1907 }
1908
Victoria Lease54ca7aef22013-01-08 09:39:50 -08001909 private boolean isMockProvider(String provider) {
1910 synchronized (mLock) {
1911 return mMockProviders.containsKey(provider);
1912 }
1913 }
1914
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001915 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7aef22013-01-08 09:39:50 -08001916 // create a working copy of the incoming Location so that the service can modify it without
1917 // disturbing the caller's copy
1918 Location myLocation = new Location(location);
1919 String provider = myLocation.getProvider();
1920
1921 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
1922 // bit if location did not come from a mock provider because passive/fused providers can
1923 // forward locations from mock providers, and should not grant them legitimacy in doing so.
1924 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
1925 myLocation.setIsFromMockProvider(true);
1926 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08001927
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001928 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001929 if (isAllowedByCurrentUserSettingsLocked(provider)) {
1930 if (!passive) {
1931 // notify passive provider of the new location
1932 mPassiveProvider.updateLocation(myLocation);
1933 }
Victoria Lease54ca7aef22013-01-08 09:39:50 -08001934 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938
Mike Lockwoode97ae402010-09-29 15:23:46 -04001939 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
1940 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001941 public void onPackageDisappeared(String packageName, int reason) {
1942 // remove all receivers associated with this package name
1943 synchronized (mLock) {
1944 ArrayList<Receiver> deadReceivers = null;
1945
1946 for (Receiver receiver : mReceivers.values()) {
1947 if (receiver.mPackageName.equals(packageName)) {
1948 if (deadReceivers == null) {
1949 deadReceivers = new ArrayList<Receiver>();
1950 }
1951 deadReceivers.add(receiver);
1952 }
1953 }
1954
1955 // perform removal outside of mReceivers loop
1956 if (deadReceivers != null) {
1957 for (Receiver receiver : deadReceivers) {
1958 removeUpdatesLocked(receiver);
1959 }
1960 }
1961 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001962 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04001963 };
1964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 // Geocoder
1966
Nick Pellye0fd6932012-07-11 10:26:13 -07001967 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04001968 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07001969 return mGeocodeProvider != null;
1970 }
1971
Nick Pellye0fd6932012-07-11 10:26:13 -07001972 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05001974 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04001975 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001976 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
1977 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04001979 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
1981
Mike Lockwooda55c3212009-04-15 11:10:11 -04001982
Nick Pellye0fd6932012-07-11 10:26:13 -07001983 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04001985 double lowerLeftLatitude, double lowerLeftLongitude,
1986 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05001987 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04001988
1989 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001990 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
1991 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
1992 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04001994 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 }
1996
1997 // Mock Providers
1998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001999 private void checkMockPermissionsSafe() {
2000 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2001 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2002 if (!allowMocks) {
2003 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2004 }
2005
2006 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
2007 PackageManager.PERMISSION_GRANTED) {
2008 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
Nick Pellye0fd6932012-07-11 10:26:13 -07002009 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002010 }
2011
Nick Pellye0fd6932012-07-11 10:26:13 -07002012 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002013 public void addTestProvider(String name, ProviderProperties properties) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002014 checkMockPermissionsSafe();
2015
Mike Lockwooda4903f252010-02-17 06:42:23 -05002016 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2017 throw new IllegalArgumentException("Cannot mock the passive location provider");
2018 }
2019
Mike Lockwood86328a92009-10-23 08:38:25 -04002020 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002021 synchronized (mLock) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002022 MockProvider provider = new MockProvider(name, this, properties);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002023 // remove the real provider if we are replacing GPS or network provider
2024 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002025 || LocationManager.NETWORK_PROVIDER.equals(name)
2026 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002027 LocationProviderInterface p = mProvidersByName.get(name);
2028 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002029 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002030 }
2031 }
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002032 if (mProvidersByName.get(name) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002033 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2034 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002035 addProviderLocked(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002036 mMockProviders.put(name, provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002037 mLastLocation.put(name, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002038 mLastLocationCoarseInterval.put(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 updateProvidersLocked();
2040 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002041 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002042 }
2043
Nick Pellye0fd6932012-07-11 10:26:13 -07002044 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002045 public void removeTestProvider(String provider) {
2046 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002047 synchronized (mLock) {
You Kima6d0b6f2012-10-28 03:58:44 +09002048 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002049 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002050 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2051 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002052 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002053 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002054
2055 // reinstate real provider if available
2056 LocationProviderInterface realProvider = mRealProviders.get(provider);
2057 if (realProvider != null) {
2058 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002059 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002060 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002061 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002063 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065 }
2066
Nick Pellye0fd6932012-07-11 10:26:13 -07002067 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 public void setTestProviderLocation(String provider, Location loc) {
2069 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002070 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002071 MockProvider mockProvider = mMockProviders.get(provider);
2072 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2074 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002075 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2076 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002077 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002078 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 }
2081
Nick Pellye0fd6932012-07-11 10:26:13 -07002082 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 public void clearTestProviderLocation(String provider) {
2084 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002085 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002086 MockProvider mockProvider = mMockProviders.get(provider);
2087 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002088 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2089 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002090 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002091 }
2092 }
2093
Nick Pellye0fd6932012-07-11 10:26:13 -07002094 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 public void setTestProviderEnabled(String provider, boolean enabled) {
2096 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002097 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002098 MockProvider mockProvider = mMockProviders.get(provider);
2099 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002100 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2101 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002102 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002103 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002104 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 mEnabledProviders.add(provider);
2106 mDisabledProviders.remove(provider);
2107 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002108 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 mEnabledProviders.remove(provider);
2110 mDisabledProviders.add(provider);
2111 }
2112 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002113 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 }
2115 }
2116
Nick Pellye0fd6932012-07-11 10:26:13 -07002117 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118 public void clearTestProviderEnabled(String provider) {
2119 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002120 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002121 MockProvider mockProvider = mMockProviders.get(provider);
2122 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2124 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002125 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 mEnabledProviders.remove(provider);
2127 mDisabledProviders.remove(provider);
2128 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002129 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131 }
2132
Nick Pellye0fd6932012-07-11 10:26:13 -07002133 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2135 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002136 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002137 MockProvider mockProvider = mMockProviders.get(provider);
2138 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2140 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002141 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143 }
2144
Nick Pellye0fd6932012-07-11 10:26:13 -07002145 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 public void clearTestProviderStatus(String provider) {
2147 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002148 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002149 MockProvider mockProvider = mMockProviders.get(provider);
2150 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2152 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002153 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155 }
2156
2157 private void log(String log) {
2158 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002159 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
2161 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002162
2163 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2165 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2166 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002167 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002168 + Binder.getCallingPid()
2169 + ", uid=" + Binder.getCallingUid());
2170 return;
2171 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002172
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002173 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002174 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002175 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002176 for (Receiver receiver : mReceivers.values()) {
2177 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 pw.println(" Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002180 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2181 pw.println(" " + entry.getKey() + ":");
2182 for (UpdateRecord record : entry.getValue()) {
2183 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
2185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002187 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2188 String provider = entry.getKey();
2189 Location location = entry.getValue();
2190 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002191 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002192
David Christie1b9b7b12013-04-15 15:31:11 -07002193 pw.println(" Last Known Locations Coarse Intervals:");
2194 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2195 String provider = entry.getKey();
2196 Location location = entry.getValue();
2197 pw.println(" " + provider + ": " + location);
2198 }
2199
Nick Pellye0fd6932012-07-11 10:26:13 -07002200 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002201
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002202 if (mEnabledProviders.size() > 0) {
2203 pw.println(" Enabled Providers:");
2204 for (String i : mEnabledProviders) {
2205 pw.println(" " + i);
2206 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002207
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
2209 if (mDisabledProviders.size() > 0) {
2210 pw.println(" Disabled Providers:");
2211 for (String i : mDisabledProviders) {
2212 pw.println(" " + i);
2213 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002214 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002215 pw.append(" ");
2216 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002217 if (mMockProviders.size() > 0) {
2218 pw.println(" Mock Providers:");
2219 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002220 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 }
2222 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002223
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002224 pw.append(" fudger: ");
2225 mLocationFudger.dump(fd, pw, args);
2226
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002227 if (args.length > 0 && "short".equals(args[0])) {
2228 return;
2229 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002230 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002231 pw.print(provider.getName() + " Internal State");
2232 if (provider instanceof LocationProviderProxy) {
2233 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2234 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002235 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002236 pw.println(":");
2237 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
2240 }
2241}