blob: 231cfe14c0c871fb9e7036f8c9033197b388860c [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;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070066import com.android.internal.os.BackgroundThread;
Mike Lockwood43e33f22010-03-26 10:41:48 -040067import com.android.server.location.GeocoderProxy;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070068import com.android.server.location.GeofenceProxy;
Nick Pellye0fd6932012-07-11 10:26:13 -070069import com.android.server.location.GeofenceManager;
Mike Lockwood43e33f22010-03-26 10:41:48 -040070import com.android.server.location.GpsLocationProvider;
Nick Pelly4035f5a2012-08-17 14:43:49 -070071import com.android.server.location.LocationBlacklist;
Nick Pelly74fa7ea2012-08-13 19:36:38 -070072import com.android.server.location.LocationFudger;
Mike Lockwood43e33f22010-03-26 10:41:48 -040073import com.android.server.location.LocationProviderInterface;
74import com.android.server.location.LocationProviderProxy;
75import com.android.server.location.MockProvider;
76import com.android.server.location.PassiveProvider;
77
78import java.io.FileDescriptor;
79import java.io.PrintWriter;
80import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070081import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040082import java.util.HashMap;
83import java.util.HashSet;
84import java.util.List;
85import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -040086import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087
88/**
89 * The service class that manages LocationProviders and issues location
90 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091 */
Victoria Lease5cd731a2012-12-19 15:04:21 -080092public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -080094 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -070095
96 private static final String WAKELOCK_KEY = 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 Lease0aa28602013-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;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700146
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700147 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800148 // Set of providers that are explicitly enabled
149 private final Set<String> mEnabledProviders = new HashSet<String>();
150
151 // Set of providers that are explicitly disabled
152 private final Set<String> mDisabledProviders = new HashSet<String>();
153
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700154 // Mock (test) providers
155 private final HashMap<String, MockProvider> mMockProviders =
156 new HashMap<String, MockProvider>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700158 // all receivers
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400159 private final HashMap<Object, Receiver> mReceivers = new HashMap<Object, Receiver>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700161 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500162 private final ArrayList<LocationProviderInterface> mProviders =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700163 new ArrayList<LocationProviderInterface>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400164
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700165 // real providers, saved here when mocked out
166 private final HashMap<String, LocationProviderInterface> mRealProviders =
167 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700169 // mapping from provider name to provider
170 private final HashMap<String, LocationProviderInterface> mProvidersByName =
171 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700173 // mapping from provider name to all its UpdateRecords
174 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
175 new HashMap<String, ArrayList<UpdateRecord>>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700176
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700177 // mapping from provider name to last known location
178 private final HashMap<String, Location> mLastLocation = new HashMap<String, Location>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
David Christie1b9b7b12013-04-15 15:31:11 -0700180 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
181 // locations stored here are not fudged for coarse permissions.
182 private final HashMap<String, Location> mLastLocationCoarseInterval =
183 new HashMap<String, Location>();
184
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700185 // all providers that operate over proxy, for authorizing incoming location
186 private final ArrayList<LocationProviderProxy> mProxyProviders =
187 new ArrayList<LocationProviderProxy>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Victoria Lease38389b62012-09-30 11:44:22 -0700189 // current active user on the device - other users are denied location data
190 private int mCurrentUserId = UserHandle.USER_OWNER;
191
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700192 public LocationManagerService(Context context) {
193 super();
194 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800195 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800196
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700197 if (D) Log.d(TAG, "Constructed");
198
199 // most startup is deferred until systemReady()
200 }
201
202 public void systemReady() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700203 synchronized (mLock) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800204 if (D) Log.d(TAG, "systemReady()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700205
Victoria Lease5cd731a2012-12-19 15:04:21 -0800206 // fetch package manager
207 mPackageManager = mContext.getPackageManager();
208
Victoria Lease0aa28602013-05-29 15:28:26 -0700209 // fetch power manager
210 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800211
212 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700213 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800214
215 // prepare mLocationHandler's dependents
216 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
217 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
218 mBlacklist.init();
219 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
220
Dianne Hackbornc2293022013-02-06 23:14:49 -0800221 // Monitor for app ops mode changes.
222 AppOpsManager.Callback callback = new AppOpsManager.Callback() {
223 public void opChanged(int op, String packageName) {
224 synchronized (mLock) {
225 applyAllProviderRequirementsLocked();
226 }
227 }
228 };
229 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
230
Victoria Lease5cd731a2012-12-19 15:04:21 -0800231 // prepare providers
232 loadProvidersLocked();
233 updateProvidersLocked();
234 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700235
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700236 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700237 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700238 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700239 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800240 @Override
241 public void onChange(boolean selfChange) {
242 synchronized (mLock) {
243 updateProvidersLocked();
244 }
245 }
246 }, UserHandle.USER_ALL);
247 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700248
Victoria Lease38389b62012-09-30 11:44:22 -0700249 // listen for user change
250 IntentFilter intentFilter = new IntentFilter();
251 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
252
253 mContext.registerReceiverAsUser(new BroadcastReceiver() {
254 @Override
255 public void onReceive(Context context, Intent intent) {
256 String action = intent.getAction();
257 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
258 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
259 }
260 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800261 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700262 }
263
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500264 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
265 PackageManager pm = mContext.getPackageManager();
266 String systemPackageName = mContext.getPackageName();
267 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
268
269 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
270 new Intent(FUSED_LOCATION_SERVICE_ACTION),
271 PackageManager.GET_META_DATA, mCurrentUserId);
272 for (ResolveInfo rInfo : rInfos) {
273 String packageName = rInfo.serviceInfo.packageName;
274
275 // Check that the signature is in the list of supported sigs. If it's not in
276 // this list the standard provider binding logic won't bind to it.
277 try {
278 PackageInfo pInfo;
279 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
280 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
281 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
282 ", but has wrong signature, ignoring");
283 continue;
284 }
285 } catch (NameNotFoundException e) {
286 Log.e(TAG, "missing package: " + packageName);
287 continue;
288 }
289
290 // Get the version info
291 if (rInfo.serviceInfo.metaData == null) {
292 Log.w(TAG, "Found fused provider without metadata: " + packageName);
293 continue;
294 }
295
296 int version = rInfo.serviceInfo.metaData.getInt(
297 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
298 if (version == 0) {
299 // This should be the fallback fused location provider.
300
301 // Make sure it's in the system partition.
302 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
303 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
304 continue;
305 }
306
307 // Check that the fallback is signed the same as the OS
308 // as a proxy for coreApp="true"
309 if (pm.checkSignatures(systemPackageName, packageName)
310 != PackageManager.SIGNATURE_MATCH) {
311 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
312 + packageName);
313 continue;
314 }
315
316 // Found a valid fallback.
317 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
318 return;
319 } else {
320 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
321 }
322 }
323
324 throw new IllegalStateException("Unable to find a fused location provider that is in the "
325 + "system partition with version 0 and signed with the platform certificate. "
326 + "Such a package is needed to provide a default fused location provider in the "
327 + "event that no other fused location provider has been installed or is currently "
328 + "available. For example, coreOnly boot mode when decrypting the data "
329 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
330 }
331
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700332 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700333 // create a passive location provider, which is always enabled
334 PassiveProvider passiveProvider = new PassiveProvider(this);
335 addProviderLocked(passiveProvider);
336 mEnabledProviders.add(passiveProvider.getName());
337 mPassiveProvider = passiveProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700338 // Create a gps location provider
339 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
340 mLocationHandler.getLooper());
Victoria Lease5c24fd02012-10-01 11:00:50 -0700341
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700342 if (GpsLocationProvider.isSupported()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700343 mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
344 mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
345 addProviderLocked(gpsProvider);
346 mRealProviders.put(LocationManager.GPS_PROVIDER, gpsProvider);
347 }
348
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700349 /*
350 Load package name(s) containing location provider support.
351 These packages can contain services implementing location providers:
352 Geocoder Provider, Network Location Provider, and
353 Fused Location Provider. They will each be searched for
354 service components implementing these providers.
355 The location framework also has support for installation
356 of new location providers at run-time. The new package does not
357 have to be explicitly listed here, however it must have a signature
358 that matches the signature of at least one package on this list.
359 */
360 Resources resources = mContext.getResources();
361 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500362 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700363 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500364 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
365 Arrays.toString(pkgs));
366 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
367
368 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700369
370 // bind to network provider
371 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
372 mContext,
373 LocationManager.NETWORK_PROVIDER,
374 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700375 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
376 com.android.internal.R.string.config_networkLocationProviderPackageName,
377 com.android.internal.R.array.config_locationProviderPackageNames,
378 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700379 if (networkProvider != null) {
380 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
381 mProxyProviders.add(networkProvider);
382 addProviderLocked(networkProvider);
383 } else {
384 Slog.w(TAG, "no network location provider found");
385 }
386
387 // bind to fused provider
388 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
389 mContext,
390 LocationManager.FUSED_PROVIDER,
391 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700392 com.android.internal.R.bool.config_enableFusedLocationOverlay,
393 com.android.internal.R.string.config_fusedLocationProviderPackageName,
394 com.android.internal.R.array.config_locationProviderPackageNames,
395 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700396 if (fusedLocationProvider != null) {
397 addProviderLocked(fusedLocationProvider);
398 mProxyProviders.add(fusedLocationProvider);
399 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700400 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700401 } else {
402 Slog.e(TAG, "no fused location provider found",
403 new IllegalStateException("Location service needs a fused location provider"));
404 }
405
406 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700407 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
408 com.android.internal.R.bool.config_enableGeocoderOverlay,
409 com.android.internal.R.string.config_geocoderProviderPackageName,
410 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800411 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700412 if (mGeocodeProvider == null) {
413 Slog.e(TAG, "no geocoder provider found");
414 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700415
416 // bind to geofence provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700417 GeofenceProxy provider = GeofenceProxy.createAndBind(mContext,
418 com.android.internal.R.bool.config_enableGeofenceOverlay,
419 com.android.internal.R.string.config_geofenceProviderPackageName,
420 com.android.internal.R.array.config_locationProviderPackageNames,
421 mLocationHandler,
422 gpsProvider.getGpsGeofenceProxy());
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700423 if (provider == null) {
424 Slog.e(TAG, "no geofence provider found");
425 }
426
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700427 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700430 * Called when the device's active user changes.
431 * @param userId the new active user's UserId
432 */
433 private void switchUser(int userId) {
Victoria Lease83762d22012-10-03 13:51:17 -0700434 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800435 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700436 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700437 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700438 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700439 for (LocationProviderInterface p : mProviders) {
440 updateProviderListenersLocked(p.getName(), false, mCurrentUserId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700441 }
Victoria Lease38389b62012-09-30 11:44:22 -0700442 mCurrentUserId = userId;
Victoria Leaseb711d572012-10-02 13:14:11 -0700443 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700444 }
445 }
446
447 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800448 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
449 * location updates.
450 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700451 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700452 final int mUid; // uid of receiver
453 final int mPid; // pid of receiver
454 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700455 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800457 final ILocationListener mListener;
458 final PendingIntent mPendingIntent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800459 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700460
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400461 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700462
Mike Lockwood48f17512009-04-23 09:12:08 -0700463 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700464 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800465
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700466 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
467 String packageName) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800468 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800469 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700470 if (listener != null) {
471 mKey = listener.asBinder();
472 } else {
473 mKey = intent;
474 }
Victoria Lease37425c32012-10-16 16:08:48 -0700475 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700476 mUid = uid;
477 mPid = pid;
478 mPackageName = packageName;
Victoria Lease0aa28602013-05-29 15:28:26 -0700479
480 // construct/configure wakelock
481 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
482 mWakeLock.setWorkSource(new WorkSource(mUid, mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800483 }
484
485 @Override
486 public boolean equals(Object otherObj) {
487 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700488 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800489 }
490 return false;
491 }
492
493 @Override
494 public int hashCode() {
495 return mKey.hashCode();
496 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800498 @Override
499 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700500 StringBuilder s = new StringBuilder();
501 s.append("Reciever[");
502 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700504 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800505 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700506 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800507 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700508 for (String p : mUpdateRecords.keySet()) {
509 s.append(" ").append(mUpdateRecords.get(p).toString());
510 }
511 s.append("]");
512 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800513 }
514
515 public boolean isListener() {
516 return mListener != null;
517 }
518
519 public boolean isPendingIntent() {
520 return mPendingIntent != null;
521 }
522
523 public ILocationListener getListener() {
524 if (mListener != null) {
525 return mListener;
526 }
527 throw new IllegalStateException("Request for non-existent listener");
528 }
529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
531 if (mListener != null) {
532 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700533 synchronized (this) {
534 // synchronize to ensure incrementPendingBroadcastsLocked()
535 // is called before decrementPendingBroadcasts()
536 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700537 // call this after broadcasting so we do not increment
538 // if we throw an exeption.
539 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800541 } catch (RemoteException e) {
542 return false;
543 }
544 } else {
545 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800546 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800547 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
548 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700549 synchronized (this) {
550 // synchronize to ensure incrementPendingBroadcastsLocked()
551 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700552 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700553 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700554 // call this after broadcasting so we do not increment
555 // if we throw an exeption.
556 incrementPendingBroadcastsLocked();
557 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 } catch (PendingIntent.CanceledException e) {
559 return false;
560 }
561 }
562 return true;
563 }
564
565 public boolean callLocationChangedLocked(Location location) {
566 if (mListener != null) {
567 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700568 synchronized (this) {
569 // synchronize to ensure incrementPendingBroadcastsLocked()
570 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800571 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700572 // call this after broadcasting so we do not increment
573 // if we throw an exeption.
574 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 } catch (RemoteException e) {
577 return false;
578 }
579 } else {
580 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800581 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700583 synchronized (this) {
584 // synchronize to ensure incrementPendingBroadcastsLocked()
585 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700586 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700587 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700588 // call this after broadcasting so we do not increment
589 // if we throw an exeption.
590 incrementPendingBroadcastsLocked();
591 }
592 } catch (PendingIntent.CanceledException e) {
593 return false;
594 }
595 }
596 return true;
597 }
598
599 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
600 if (mListener != null) {
601 try {
602 synchronized (this) {
603 // synchronize to ensure incrementPendingBroadcastsLocked()
604 // is called before decrementPendingBroadcasts()
605 if (enabled) {
606 mListener.onProviderEnabled(provider);
607 } else {
608 mListener.onProviderDisabled(provider);
609 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700610 // call this after broadcasting so we do not increment
611 // if we throw an exeption.
612 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700613 }
614 } catch (RemoteException e) {
615 return false;
616 }
617 } else {
618 Intent providerIntent = new Intent();
619 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
620 try {
621 synchronized (this) {
622 // synchronize to ensure incrementPendingBroadcastsLocked()
623 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700624 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700625 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700626 // call this after broadcasting so we do not increment
627 // if we throw an exeption.
628 incrementPendingBroadcastsLocked();
629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 } catch (PendingIntent.CanceledException e) {
631 return false;
632 }
633 }
634 return true;
635 }
636
Nick Pellyf1be6862012-05-15 10:53:42 -0700637 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700639 if (D) Log.d(TAG, "Location listener died");
640
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400641 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 removeUpdatesLocked(this);
643 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700644 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700645 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700646 }
647 }
648
Nick Pellye0fd6932012-07-11 10:26:13 -0700649 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700650 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
651 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400652 synchronized (this) {
653 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700654 }
655 }
656
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400657 // this must be called while synchronized by caller in a synchronized block
658 // containing the sending of the broadcaset
659 private void incrementPendingBroadcastsLocked() {
660 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700661 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400662 }
663 }
664
665 private void decrementPendingBroadcastsLocked() {
666 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700667 if (mWakeLock.isHeld()) {
668 mWakeLock.release();
669 }
670 }
671 }
672
673 public void clearPendingBroadcastsLocked() {
674 if (mPendingBroadcasts > 0) {
675 mPendingBroadcasts = 0;
676 if (mWakeLock.isHeld()) {
677 mWakeLock.release();
678 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700679 }
680 }
681 }
682
Nick Pellye0fd6932012-07-11 10:26:13 -0700683 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700684 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700685 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -0400686 //the receiver list if it is not found. If it is not found then the
687 //LocationListener was removed when it had a pending broadcast and should
688 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700689 synchronized (mLock) {
690 IBinder binder = listener.asBinder();
691 Receiver receiver = mReceivers.get(binder);
692 if (receiver != null) {
693 synchronized (receiver) {
694 // so wakelock calls will succeed
695 long identity = Binder.clearCallingIdentity();
696 receiver.decrementPendingBroadcastsLocked();
697 Binder.restoreCallingIdentity(identity);
698 }
699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800700 }
701 }
702
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700703 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400704 mProviders.add(provider);
705 mProvidersByName.put(provider.getName(), provider);
706 }
707
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700708 private void removeProviderLocked(LocationProviderInterface provider) {
709 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400710 mProviders.remove(provider);
711 mProvidersByName.remove(provider.getName());
712 }
713
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800714 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800715 * Returns "true" if access to the specified location provider is allowed by the current
716 * user's settings. Access to all location providers is forbidden to non-location-provider
717 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800718 *
719 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800720 * @return
721 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800722 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 if (mEnabledProviders.contains(provider)) {
724 return true;
725 }
726 if (mDisabledProviders.contains(provider)) {
727 return false;
728 }
729 // Use system settings
730 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731
Victoria Leaseb711d572012-10-02 13:14:11 -0700732 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800733 }
734
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700735 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800736 * Returns "true" if access to the specified location provider is allowed by the specified
737 * user's settings. Access to all location providers is forbidden to non-location-provider
738 * processes belonging to background users.
739 *
740 * @param provider the name of the location provider
741 * @param uid the requestor's UID
742 * @return
743 */
744 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
745 if (UserHandle.getUserId(uid) != mCurrentUserId && !isUidALocationProvider(uid)) {
746 return false;
747 }
748 return isAllowedByCurrentUserSettingsLocked(provider);
749 }
750
751 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700752 * Returns the permission string associated with the specified resolution level.
753 *
754 * @param resolutionLevel the resolution level
755 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700756 */
Victoria Lease37425c32012-10-16 16:08:48 -0700757 private String getResolutionPermission(int resolutionLevel) {
758 switch (resolutionLevel) {
759 case RESOLUTION_LEVEL_FINE:
760 return android.Manifest.permission.ACCESS_FINE_LOCATION;
761 case RESOLUTION_LEVEL_COARSE:
762 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
763 default:
764 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700766 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700767
Victoria Leaseda479c52012-10-15 15:24:16 -0700768 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700769 * Returns the resolution level allowed to the given PID/UID pair.
770 *
771 * @param pid the PID
772 * @param uid the UID
773 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -0700774 */
Victoria Lease37425c32012-10-16 16:08:48 -0700775 private int getAllowedResolutionLevel(int pid, int uid) {
776 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
777 pid, uid) == PackageManager.PERMISSION_GRANTED) {
778 return RESOLUTION_LEVEL_FINE;
779 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
780 pid, uid) == PackageManager.PERMISSION_GRANTED) {
781 return RESOLUTION_LEVEL_COARSE;
782 } else {
783 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -0700784 }
Victoria Lease4fab68b2012-09-13 13:20:59 -0700785 }
786
787 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700788 * Returns the resolution level allowed to the caller
789 *
790 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -0700791 */
Victoria Lease37425c32012-10-16 16:08:48 -0700792 private int getCallerAllowedResolutionLevel() {
793 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
794 }
795
796 /**
797 * Throw SecurityException if specified resolution level is insufficient to use geofences.
798 *
799 * @param allowedResolutionLevel resolution level allowed to caller
800 */
801 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
802 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -0700803 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 }
806
Victoria Lease37425c32012-10-16 16:08:48 -0700807 /**
808 * Return the minimum resolution level required to use the specified location provider.
809 *
810 * @param provider the name of the location provider
811 * @return minimum resolution level required for provider
812 */
813 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -0700814 if (LocationManager.GPS_PROVIDER.equals(provider) ||
815 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
816 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -0700817 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -0700818 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
819 LocationManager.FUSED_PROVIDER.equals(provider)) {
820 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -0700821 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -0700822 } else {
823 // mock providers
824 LocationProviderInterface lp = mMockProviders.get(provider);
825 if (lp != null) {
826 ProviderProperties properties = lp.getProperties();
827 if (properties != null) {
828 if (properties.mRequiresSatellite) {
829 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -0700830 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -0700831 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
832 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -0700833 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -0700834 }
835 }
836 }
Victoria Lease8dbb6342012-09-21 16:55:53 -0700837 }
Victoria Lease37425c32012-10-16 16:08:48 -0700838 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -0700839 }
840
Victoria Lease37425c32012-10-16 16:08:48 -0700841 /**
842 * Throw SecurityException if specified resolution level is insufficient to use the named
843 * location provider.
844 *
845 * @param allowedResolutionLevel resolution level allowed to caller
846 * @param providerName the name of the location provider
847 */
848 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
849 String providerName) {
850 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
851 if (allowedResolutionLevel < requiredResolutionLevel) {
852 switch (requiredResolutionLevel) {
853 case RESOLUTION_LEVEL_FINE:
854 throw new SecurityException("\"" + providerName + "\" location provider " +
855 "requires ACCESS_FINE_LOCATION permission.");
856 case RESOLUTION_LEVEL_COARSE:
857 throw new SecurityException("\"" + providerName + "\" location provider " +
858 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
859 default:
860 throw new SecurityException("Insufficient permission for \"" + providerName +
861 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -0700862 }
863 }
Victoria Lease8dbb6342012-09-21 16:55:53 -0700864 }
865
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800866 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800867 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
868 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800869 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800870 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800871 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -0800872 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800873 }
874 return -1;
875 }
876
877 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
878 int op = resolutionLevelToOp(allowedResolutionLevel);
879 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800880 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
881 return false;
882 }
883 }
884 return true;
885 }
886
887 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -0800888 int op = resolutionLevelToOp(allowedResolutionLevel);
889 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -0800890 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
891 return false;
892 }
893 }
894 return true;
895 }
896
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700897 /**
898 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -0700899 * fused, also including ones that are not permitted to
900 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700901 */
Nick Pellye0fd6932012-07-11 10:26:13 -0700902 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700904 ArrayList<String> out;
905 synchronized (mLock) {
906 out = new ArrayList<String>(mProviders.size());
907 for (LocationProviderInterface provider : mProviders) {
908 String name = provider.getName();
909 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -0700910 continue;
911 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800912 out.add(name);
913 }
914 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700915
916 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 return out;
918 }
919
Mike Lockwood03ca2162010-04-01 08:10:09 -0700920 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700921 * Return all providers by name, that match criteria and are optionally
922 * enabled.
923 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -0700924 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700925 @Override
926 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -0700927 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700928 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800929 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -0700930 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -0700931 try {
932 synchronized (mLock) {
933 out = new ArrayList<String>(mProviders.size());
934 for (LocationProviderInterface provider : mProviders) {
935 String name = provider.getName();
936 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -0700937 continue;
938 }
Victoria Lease37425c32012-10-16 16:08:48 -0700939 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800940 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700941 continue;
942 }
943 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
944 name, provider.getProperties(), criteria)) {
945 continue;
946 }
947 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -0700948 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700949 }
Mike Lockwood03ca2162010-04-01 08:10:09 -0700950 }
Victoria Leaseb711d572012-10-02 13:14:11 -0700951 } finally {
952 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -0700953 }
954
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700955 if (D) Log.d(TAG, "getProviders()=" + out);
956 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -0700957 }
958
959 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700960 * Return the name of the best provider given a Criteria object.
961 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -0700962 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700963 * has been deprecated as well. So this method now uses
964 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -0700965 */
Nick Pellye0fd6932012-07-11 10:26:13 -0700966 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -0700967 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700968 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700969
970 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -0700971 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700972 result = pickBest(providers);
973 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
974 return result;
975 }
976 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -0700977 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700978 result = pickBest(providers);
979 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
980 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -0700981 }
982
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700983 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -0700984 return null;
985 }
986
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700987 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -0700988 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700989 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -0700990 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
991 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700992 } else {
993 return providers.get(0);
994 }
995 }
996
Nick Pellye0fd6932012-07-11 10:26:13 -0700997 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -0700998 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
999 LocationProviderInterface p = mProvidersByName.get(provider);
1000 if (p == null) {
1001 throw new IllegalArgumentException("provider=" + provider);
1002 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001003
1004 boolean result = LocationProvider.propertiesMeetCriteria(
1005 p.getName(), p.getProperties(), criteria);
1006 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1007 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001008 }
1009
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001011 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001012 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001013 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 boolean isEnabled = p.isEnabled();
1015 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001016 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 if (isEnabled && !shouldBeEnabled) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001018 updateProviderListenersLocked(name, false, mCurrentUserId);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001019 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 } else if (!isEnabled && shouldBeEnabled) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001021 updateProviderListenersLocked(name, true, mCurrentUserId);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001022 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001024 }
1025 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001026 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1027 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029 }
1030
Victoria Leaseb711d572012-10-02 13:14:11 -07001031 private void updateProviderListenersLocked(String provider, boolean enabled, int userId) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 int listeners = 0;
1033
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001034 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001035 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036
1037 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001038
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001039 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1040 if (records != null) {
1041 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001042 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 UpdateRecord record = records.get(i);
Victoria Lease269518e2012-10-29 08:25:39 -07001044 if (UserHandle.getUserId(record.mReceiver.mUid) == userId) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001045 // Sends a notification message to the receiver
1046 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1047 if (deadReceivers == null) {
1048 deadReceivers = new ArrayList<Receiver>();
1049 }
1050 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001052 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
1055 }
1056
1057 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001058 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 removeUpdatesLocked(deadReceivers.get(i));
1060 }
1061 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001062
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 if (enabled) {
1064 p.enable();
1065 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001066 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001069 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001071 }
1072
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001073 private void applyRequirementsLocked(String provider) {
1074 LocationProviderInterface p = mProvidersByName.get(provider);
1075 if (p == null) return;
1076
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001078 WorkSource worksource = new WorkSource();
1079 ProviderRequest providerRequest = new ProviderRequest();
1080
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001082 for (UpdateRecord record : records) {
Victoria Lease269518e2012-10-29 08:25:39 -07001083 if (UserHandle.getUserId(record.mReceiver.mUid) == mCurrentUserId) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001084 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1085 record.mReceiver.mAllowedResolutionLevel)) {
1086 LocationRequest locationRequest = record.mRequest;
1087 providerRequest.locationRequests.add(locationRequest);
1088 if (locationRequest.getInterval() < providerRequest.interval) {
1089 providerRequest.reportLocation = true;
1090 providerRequest.interval = locationRequest.getInterval();
1091 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001092 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001093 }
1094 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001095
1096 if (providerRequest.reportLocation) {
1097 // calculate who to blame for power
1098 // This is somewhat arbitrary. We pick a threshold interval
1099 // that is slightly higher that the minimum interval, and
1100 // spread the blame across all applications with a request
1101 // under that threshold.
1102 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1103 for (UpdateRecord record : records) {
Victoria Lease269518e2012-10-29 08:25:39 -07001104 if (UserHandle.getUserId(record.mReceiver.mUid) == mCurrentUserId) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001105 LocationRequest locationRequest = record.mRequest;
1106 if (locationRequest.getInterval() <= thresholdInterval) {
Dianne Hackborn002a54e2013-01-10 17:34:55 -08001107 worksource.add(record.mReceiver.mUid, record.mReceiver.mPackageName);
Victoria Leaseb711d572012-10-02 13:14:11 -07001108 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001109 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001110 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 }
1112 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001113
1114 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1115 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 }
1117
1118 private class UpdateRecord {
1119 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001120 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001122 Location mLastFixBroadcast;
1123 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124
1125 /**
1126 * Note: must be constructed with lock held.
1127 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001128 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001130 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001132
1133 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1134 if (records == null) {
1135 records = new ArrayList<UpdateRecord>();
1136 mRecordsByProvider.put(provider, records);
1137 }
1138 if (!records.contains(this)) {
1139 records.add(this);
1140 }
1141 }
1142
1143 /**
1144 * Method to be called when a record will no longer be used. Calling this multiple times
1145 * must have the same effect as calling it once.
1146 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001147 void disposeLocked(boolean removeReceiver) {
1148 // remove from mRecordsByProvider
1149 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1150 if (globalRecords != null) {
1151 globalRecords.remove(this);
1152 }
1153
1154 if (!removeReceiver) return; // the caller will handle the rest
1155
1156 // remove from Receiver#mUpdateRecords
1157 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1158 if (receiverRecords != null) {
1159 receiverRecords.remove(this.mProvider);
1160
1161 // and also remove the Receiver if it has no more update records
1162 if (removeReceiver && receiverRecords.size() == 0) {
1163 removeUpdatesLocked(mReceiver);
1164 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167
1168 @Override
1169 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001170 StringBuilder s = new StringBuilder();
1171 s.append("UpdateRecord[");
1172 s.append(mProvider);
1173 s.append(' ').append(mReceiver.mPackageName).append('(');
1174 s.append(mReceiver.mUid).append(')');
1175 s.append(' ').append(mRequest);
1176 s.append(']');
1177 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 }
1180
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001181 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
1182 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
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001199 private Receiver getReceiverLocked(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
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001263 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001264 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);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001271 return getReceiverLocked(intent, pid, uid, packageName);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001272 } else {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001273 return getReceiverLocked(listener, pid, uid, packageName);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001274 }
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
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001296 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001297 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
1298 packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001299 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301 } finally {
1302 Binder.restoreCallingIdentity(identity);
1303 }
1304 }
1305
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001306 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1307 int pid, int uid, String packageName) {
1308 // Figure out the provider. Either its explicitly request (legacy use cases), or
1309 // use the fused provider
1310 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1311 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001312 if (name == null) {
1313 throw new IllegalArgumentException("provider name must not be null");
1314 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001315
1316 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1317 + " " + name + " " + request + " from " + packageName + "(" + uid + ")");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001318 LocationProviderInterface provider = mProvidersByName.get(name);
1319 if (provider == null) {
1320 throw new IllegalArgumentException("provider doesn't exisit: " + provider);
1321 }
1322
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001323 UpdateRecord record = new UpdateRecord(name, request, receiver);
1324 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1325 if (oldRecord != null) {
1326 oldRecord.disposeLocked(false);
1327 }
1328
Victoria Lease09eeaec2013-02-05 11:34:13 -08001329 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001330 if (isProviderEnabled) {
1331 applyRequirementsLocked(name);
1332 } else {
1333 // Notify the listener that updates are currently disabled
1334 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
1336 }
1337
Nick Pellye0fd6932012-07-11 10:26:13 -07001338 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001339 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1340 String packageName) {
1341 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001342
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001343 final int pid = Binder.getCallingPid();
1344 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001345
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001346 synchronized (mLock) {
1347 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid, packageName);
1348
1349 // providers may use public location API's, need to clear identity
1350 long identity = Binder.clearCallingIdentity();
1351 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001352 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001353 } finally {
1354 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356 }
1357 }
1358
1359 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001360 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001361
1362 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1363 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1364 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001365 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001369 // Record which providers were associated with this listener
1370 HashSet<String> providers = new HashSet<String>();
1371 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1372 if (oldRecords != null) {
1373 // Call dispose() on the obsolete update records.
1374 for (UpdateRecord record : oldRecords.values()) {
1375 record.disposeLocked(false);
1376 }
1377 // Accumulate providers
1378 providers.addAll(oldRecords.keySet());
1379 }
1380
1381 // update provider
1382 for (String provider : providers) {
1383 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001384 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001385 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386 }
1387
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001388 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
1390 }
1391
Dianne Hackbornc2293022013-02-06 23:14:49 -08001392 private void applyAllProviderRequirementsLocked() {
1393 for (LocationProviderInterface p : mProviders) {
1394 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001395 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001396 continue;
1397 }
1398
1399 applyRequirementsLocked(p.getName());
1400 }
1401 }
1402
Nick Pellye0fd6932012-07-11 10:26:13 -07001403 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001404 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001405 if (D) Log.d(TAG, "getLastLocation: " + request);
1406 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001407 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001408 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001409 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1410 request.getProvider());
1411 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001412
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001413 final int uid = Binder.getCallingUid();
1414 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001415 try {
1416 if (mBlacklist.isBlacklisted(packageName)) {
1417 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1418 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001419 return null;
1420 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001421
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001422 if (!reportLocationAccessNoThrow(uid, packageName, allowedResolutionLevel)) {
1423 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1424 packageName);
1425 return null;
1426 }
1427
Victoria Leaseb711d572012-10-02 13:14:11 -07001428 synchronized (mLock) {
1429 // Figure out the provider. Either its explicitly request (deprecated API's),
1430 // or use the fused provider
1431 String name = request.getProvider();
1432 if (name == null) name = LocationManager.FUSED_PROVIDER;
1433 LocationProviderInterface provider = mProvidersByName.get(name);
1434 if (provider == null) return null;
1435
Victoria Lease09eeaec2013-02-05 11:34:13 -08001436 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001437
David Christie1b9b7b12013-04-15 15:31:11 -07001438 Location location;
1439 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1440 // Make sure that an app with coarse permissions can't get frequent location
1441 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1442 location = mLastLocationCoarseInterval.get(name);
1443 } else {
1444 location = mLastLocation.get(name);
1445 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001446 if (location == null) {
1447 return null;
1448 }
Victoria Lease37425c32012-10-16 16:08:48 -07001449 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001450 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1451 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001452 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001453 }
Victoria Lease37425c32012-10-16 16:08:48 -07001454 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001455 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001456 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001457 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001458 return null;
1459 } finally {
1460 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001461 }
1462 }
1463
1464 @Override
1465 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1466 String packageName) {
1467 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001468 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1469 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001470 checkPendingIntent(intent);
1471 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001472 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1473 request.getProvider());
1474 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001475
Victoria Lease37425c32012-10-16 16:08:48 -07001476 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001477
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001478 // geo-fence manager uses the public location API, need to clear identity
1479 int uid = Binder.getCallingUid();
Victoria Lease56e675b2012-11-05 19:25:06 -08001480 if (UserHandle.getUserId(uid) != UserHandle.USER_OWNER) {
1481 // temporary measure until geofences work for secondary users
1482 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1483 return;
1484 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001485 long identity = Binder.clearCallingIdentity();
1486 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001487 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1488 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001489 } finally {
1490 Binder.restoreCallingIdentity(identity);
1491 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001492 }
1493
1494 @Override
1495 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Victoria Lease37425c32012-10-16 16:08:48 -07001496 checkResolutionLevelIsSufficientForGeofenceUse(getCallerAllowedResolutionLevel());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001497 checkPendingIntent(intent);
1498 checkPackageName(packageName);
1499
1500 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1501
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001502 // geo-fence manager uses the public location API, need to clear identity
1503 long identity = Binder.clearCallingIdentity();
1504 try {
1505 mGeofenceManager.removeFence(geofence, intent);
1506 } finally {
1507 Binder.restoreCallingIdentity(identity);
1508 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001509 }
1510
1511
1512 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001513 public boolean addGpsStatusListener(IGpsStatusListener listener, String packageName) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001514 if (mGpsStatusProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 return false;
1516 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001517 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1518 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001519 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001521 final int uid = Binder.getCallingUid();
1522 final long ident = Binder.clearCallingIdentity();
1523 try {
Victoria Lease3d5173d2013-02-05 16:07:32 -08001524 if (!checkLocationAccess(uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001525 return false;
1526 }
1527 } finally {
1528 Binder.restoreCallingIdentity(ident);
1529 }
1530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531 try {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001532 mGpsStatusProvider.addGpsStatusListener(listener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001534 Slog.e(TAG, "mGpsStatusProvider.addGpsStatusListener failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001535 return false;
1536 }
1537 return true;
1538 }
1539
Nick Pellye0fd6932012-07-11 10:26:13 -07001540 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 public void removeGpsStatusListener(IGpsStatusListener listener) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001542 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001543 try {
1544 mGpsStatusProvider.removeGpsStatusListener(listener);
1545 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001546 Slog.e(TAG, "mGpsStatusProvider.removeGpsStatusListener failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001547 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
1549 }
1550
Nick Pellye0fd6932012-07-11 10:26:13 -07001551 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001553 if (provider == null) {
1554 // throw NullPointerException to remain compatible with previous implementation
1555 throw new NullPointerException();
1556 }
Victoria Lease37425c32012-10-16 16:08:48 -07001557 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1558 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001559
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001561 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 != PackageManager.PERMISSION_GRANTED)) {
1563 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1564 }
1565
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001566 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001567 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001568 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001569
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001570 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 }
1572 }
1573
Nick Pellye0fd6932012-07-11 10:26:13 -07001574 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001575 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001576 if (Binder.getCallingUid() != Process.myUid()) {
1577 throw new SecurityException(
1578 "calling sendNiResponse from outside of the system is not allowed");
1579 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001580 try {
1581 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001582 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001583 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001584 return false;
1585 }
1586 }
1587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001589 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001590 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 * accessed by the caller
1592 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001593 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001594 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001595 if (mProvidersByName.get(provider) == null) {
1596 return null;
1597 }
1598
Victoria Lease37425c32012-10-16 16:08:48 -07001599 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1600 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001601
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001602 LocationProviderInterface p;
1603 synchronized (mLock) {
1604 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001607 if (p == null) return null;
1608 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610
Nick Pellye0fd6932012-07-11 10:26:13 -07001611 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 public boolean isProviderEnabled(String provider) {
Victoria Lease37425c32012-10-16 16:08:48 -07001613 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1614 provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001615 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1616
Victoria Lease09eeaec2013-02-05 11:34:13 -08001617 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001618 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001619 try {
1620 synchronized (mLock) {
1621 LocationProviderInterface p = mProvidersByName.get(provider);
1622 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001623
Victoria Lease09eeaec2013-02-05 11:34:13 -08001624 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001625 }
1626 } finally {
1627 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001628 }
1629 }
1630
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001631 /**
1632 * Returns "true" if the UID belongs to a bound location provider.
1633 *
1634 * @param uid the uid
1635 * @return true if uid belongs to a bound location provider
1636 */
1637 private boolean isUidALocationProvider(int uid) {
1638 if (uid == Process.SYSTEM_UID) {
1639 return true;
1640 }
1641 if (mGeocodeProvider != null) {
1642 if (doesPackageHaveUid(uid, mGeocodeProvider.getConnectedPackageName())) return true;
1643 }
1644 for (LocationProviderProxy proxy : mProxyProviders) {
1645 if (doesPackageHaveUid(uid, proxy.getConnectedPackageName())) return true;
1646 }
1647 return false;
1648 }
1649
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001650 private void checkCallerIsProvider() {
1651 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
1652 == PackageManager.PERMISSION_GRANTED) {
1653 return;
1654 }
1655
1656 // Previously we only used the INSTALL_LOCATION_PROVIDER
1657 // check. But that is system or signature
1658 // protection level which is not flexible enough for
1659 // providers installed oustide the system image. So
1660 // also allow providers with a UID matching the
1661 // currently bound package name
1662
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001663 if (isUidALocationProvider(Binder.getCallingUid())) {
1664 return;
1665 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001666
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001667 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
1668 "or UID of a currently bound location provider");
1669 }
1670
1671 private boolean doesPackageHaveUid(int uid, String packageName) {
1672 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 return false;
1674 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001675 try {
1676 ApplicationInfo appInfo = mPackageManager.getApplicationInfo(packageName, 0);
1677 if (appInfo.uid != uid) {
1678 return false;
1679 }
1680 } catch (NameNotFoundException e) {
1681 return false;
1682 }
1683 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685
Nick Pellye0fd6932012-07-11 10:26:13 -07001686 @Override
Mike Lockwooda4903f252010-02-17 06:42:23 -05001687 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001688 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04001689
Nick Pelly2eeeec22012-07-18 13:13:37 -07001690 if (!location.isComplete()) {
1691 Log.w(TAG, "Dropping incomplete location: " + location);
1692 return;
1693 }
1694
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001695 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
1696 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f252010-02-17 06:42:23 -05001697 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07001698 mLocationHandler.sendMessageAtFrontOfQueue(m);
1699 }
1700
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701
Laurent Tu75defb62012-11-01 16:21:52 -07001702 private static boolean shouldBroadcastSafe(
1703 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 // Always broadcast the first update
1705 if (lastLoc == null) {
1706 return true;
1707 }
1708
Nick Pellyf1be6862012-05-15 10:53:42 -07001709 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001710 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07001711 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
1712 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001713 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 return false;
1715 }
1716
1717 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001718 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 if (minDistance > 0.0) {
1720 if (loc.distanceTo(lastLoc) <= minDistance) {
1721 return false;
1722 }
1723 }
1724
Laurent Tu75defb62012-11-01 16:21:52 -07001725 // Check whether sufficient number of udpates is left
1726 if (record.mRequest.getNumUpdates() <= 0) {
1727 return false;
1728 }
1729
1730 // Check whether the expiry date has passed
1731 if (record.mRequest.getExpireAt() < now) {
1732 return false;
1733 }
1734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 return true;
1736 }
1737
Mike Lockwooda4903f252010-02-17 06:42:23 -05001738 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001739 if (D) Log.d(TAG, "incoming location: " + location);
1740
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001741 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f252010-02-17 06:42:23 -05001742 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743
Laurent Tu60ec50a2012-10-04 17:00:10 -07001744 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001745 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001746 if (p == null) return;
1747
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001748 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07001749 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1750 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001751 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07001752 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001753 lastLocation = new Location(provider);
1754 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07001755 } else {
1756 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1757 if (noGPSLocation == null && lastNoGPSLocation != null) {
1758 // New location has no no-GPS location: adopt last no-GPS location. This is set
1759 // directly into location because we do not want to notify COARSE clients.
1760 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
1761 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07001762 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001763 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764
David Christie1b9b7b12013-04-15 15:31:11 -07001765 // Update last known coarse interval location if enough time has passed.
1766 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
1767 if (lastLocationCoarseInterval == null) {
1768 lastLocationCoarseInterval = new Location(location);
1769 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
1770 }
1771 long timeDiffNanos = location.getElapsedRealtimeNanos()
1772 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
1773 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
1774 lastLocationCoarseInterval.set(location);
1775 }
1776 // Don't ever return a coarse location that is more recent than the allowed update
1777 // interval (i.e. don't allow an app to keep registering and unregistering for
1778 // location updates to overcome the minimum interval).
1779 noGPSLocation =
1780 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1781
Laurent Tu60ec50a2012-10-04 17:00:10 -07001782 // Skip if there are no UpdateRecords for this provider.
1783 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1784 if (records == null || records.size() == 0) return;
1785
Victoria Lease09016ab2012-09-16 12:33:15 -07001786 // Fetch coarse location
1787 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07001788 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001789 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
1790 }
1791
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 // Fetch latest status update time
1793 long newStatusUpdateTime = p.getStatusUpdateTime();
1794
Mike Lockwood7ec434e2009-03-27 07:46:48 -07001795 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 Bundle extras = new Bundle();
1797 int status = p.getStatus(extras);
1798
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001799 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001800 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001801
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001802 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001803 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001805 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07001806
Victoria Lease269518e2012-10-29 08:25:39 -07001807 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Victoria Lease2f5b97c2013-05-07 14:22:02 -07001808 if (receiverUserId != mCurrentUserId && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001809 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07001810 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07001811 " (current user: " + mCurrentUserId + ", app: " +
1812 receiver.mPackageName + ")");
1813 }
1814 continue;
1815 }
1816
Nick Pelly4035f5a2012-08-17 14:43:49 -07001817 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
1818 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
1819 receiver.mPackageName);
1820 continue;
1821 }
1822
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001823 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
1824 receiver.mAllowedResolutionLevel)) {
1825 if (D) Log.d(TAG, "skipping loc update for no op app: " +
1826 receiver.mPackageName);
1827 continue;
1828 }
1829
Victoria Lease09016ab2012-09-16 12:33:15 -07001830 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07001831 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1832 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001833 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07001834 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001835 }
Victoria Lease09016ab2012-09-16 12:33:15 -07001836 if (notifyLocation != null) {
1837 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07001838 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001839 if (lastLoc == null) {
1840 lastLoc = new Location(notifyLocation);
1841 r.mLastFixBroadcast = lastLoc;
1842 } else {
1843 lastLoc.set(notifyLocation);
1844 }
1845 if (!receiver.callLocationChangedLocked(notifyLocation)) {
1846 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
1847 receiverDead = true;
1848 }
Laurent Tu75defb62012-11-01 16:21:52 -07001849 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 }
1852
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001853 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07001855 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001857 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001859 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08001860 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001861 }
1862 }
1863
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001864 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07001865 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001866 if (deadUpdateRecords == null) {
1867 deadUpdateRecords = new ArrayList<UpdateRecord>();
1868 }
1869 deadUpdateRecords.add(r);
1870 }
1871 // track dead receivers
1872 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001873 if (deadReceivers == null) {
1874 deadReceivers = new ArrayList<Receiver>();
1875 }
1876 if (!deadReceivers.contains(receiver)) {
1877 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879 }
1880 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001881
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001882 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001884 for (Receiver receiver : deadReceivers) {
1885 removeUpdatesLocked(receiver);
1886 }
1887 }
1888 if (deadUpdateRecords != null) {
1889 for (UpdateRecord r : deadUpdateRecords) {
1890 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
Victoria Lease8b38b292012-12-04 15:04:43 -08001892 applyRequirementsLocked(provider);
1893 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
1896 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08001897 public LocationWorkerHandler(Looper looper) {
1898 super(looper, null, true);
1899 }
1900
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 @Override
1902 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001903 switch (msg.what) {
1904 case MSG_LOCATION_CHANGED:
1905 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
1906 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
1908 }
1909 }
1910
Victoria Lease54ca7aef22013-01-08 09:39:50 -08001911 private boolean isMockProvider(String provider) {
1912 synchronized (mLock) {
1913 return mMockProviders.containsKey(provider);
1914 }
1915 }
1916
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001917 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7aef22013-01-08 09:39:50 -08001918 // create a working copy of the incoming Location so that the service can modify it without
1919 // disturbing the caller's copy
1920 Location myLocation = new Location(location);
1921 String provider = myLocation.getProvider();
1922
1923 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
1924 // bit if location did not come from a mock provider because passive/fused providers can
1925 // forward locations from mock providers, and should not grant them legitimacy in doing so.
1926 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
1927 myLocation.setIsFromMockProvider(true);
1928 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08001929
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001930 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001931 if (isAllowedByCurrentUserSettingsLocked(provider)) {
1932 if (!passive) {
1933 // notify passive provider of the new location
1934 mPassiveProvider.updateLocation(myLocation);
1935 }
Victoria Lease54ca7aef22013-01-08 09:39:50 -08001936 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940
Mike Lockwoode97ae402010-09-29 15:23:46 -04001941 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
1942 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001943 public void onPackageDisappeared(String packageName, int reason) {
1944 // remove all receivers associated with this package name
1945 synchronized (mLock) {
1946 ArrayList<Receiver> deadReceivers = null;
1947
1948 for (Receiver receiver : mReceivers.values()) {
1949 if (receiver.mPackageName.equals(packageName)) {
1950 if (deadReceivers == null) {
1951 deadReceivers = new ArrayList<Receiver>();
1952 }
1953 deadReceivers.add(receiver);
1954 }
1955 }
1956
1957 // perform removal outside of mReceivers loop
1958 if (deadReceivers != null) {
1959 for (Receiver receiver : deadReceivers) {
1960 removeUpdatesLocked(receiver);
1961 }
1962 }
1963 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001964 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04001965 };
1966
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001967 // Geocoder
1968
Nick Pellye0fd6932012-07-11 10:26:13 -07001969 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04001970 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07001971 return mGeocodeProvider != null;
1972 }
1973
Nick Pellye0fd6932012-07-11 10:26:13 -07001974 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05001976 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04001977 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001978 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
1979 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001980 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04001981 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001982 }
1983
Mike Lockwooda55c3212009-04-15 11:10:11 -04001984
Nick Pellye0fd6932012-07-11 10:26:13 -07001985 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04001987 double lowerLeftLatitude, double lowerLeftLongitude,
1988 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05001989 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04001990
1991 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001992 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
1993 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
1994 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001995 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04001996 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 }
1998
1999 // Mock Providers
2000
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 private void checkMockPermissionsSafe() {
2002 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2003 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2004 if (!allowMocks) {
2005 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2006 }
2007
2008 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
2009 PackageManager.PERMISSION_GRANTED) {
2010 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
Nick Pellye0fd6932012-07-11 10:26:13 -07002011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 }
2013
Nick Pellye0fd6932012-07-11 10:26:13 -07002014 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002015 public void addTestProvider(String name, ProviderProperties properties) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002016 checkMockPermissionsSafe();
2017
Mike Lockwooda4903f252010-02-17 06:42:23 -05002018 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2019 throw new IllegalArgumentException("Cannot mock the passive location provider");
2020 }
2021
Mike Lockwood86328a92009-10-23 08:38:25 -04002022 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002023 synchronized (mLock) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002024 MockProvider provider = new MockProvider(name, this, properties);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002025 // remove the real provider if we are replacing GPS or network provider
2026 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002027 || LocationManager.NETWORK_PROVIDER.equals(name)
2028 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002029 LocationProviderInterface p = mProvidersByName.get(name);
2030 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002031 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002032 }
2033 }
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002034 if (mProvidersByName.get(name) != null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002035 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2036 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002037 addProviderLocked(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002038 mMockProviders.put(name, provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002039 mLastLocation.put(name, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002040 mLastLocationCoarseInterval.put(name, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002041 updateProvidersLocked();
2042 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002043 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 }
2045
Nick Pellye0fd6932012-07-11 10:26:13 -07002046 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 public void removeTestProvider(String provider) {
2048 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002049 synchronized (mLock) {
You Kima6d0b6f2012-10-28 03:58:44 +09002050 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002051 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002052 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2053 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002054 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002055 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002056
2057 // reinstate real provider if available
2058 LocationProviderInterface realProvider = mRealProviders.get(provider);
2059 if (realProvider != null) {
2060 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002061 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002062 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002063 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002065 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067 }
2068
Nick Pellye0fd6932012-07-11 10:26:13 -07002069 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 public void setTestProviderLocation(String provider, Location loc) {
2071 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002072 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002073 MockProvider mockProvider = mMockProviders.get(provider);
2074 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2076 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002077 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2078 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002079 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002080 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002081 }
2082 }
2083
Nick Pellye0fd6932012-07-11 10:26:13 -07002084 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 public void clearTestProviderLocation(String provider) {
2086 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002087 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002088 MockProvider mockProvider = mMockProviders.get(provider);
2089 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002090 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2091 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002092 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 }
2094 }
2095
Nick Pellye0fd6932012-07-11 10:26:13 -07002096 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 public void setTestProviderEnabled(String provider, boolean enabled) {
2098 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002099 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002100 MockProvider mockProvider = mMockProviders.get(provider);
2101 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2103 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002104 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002106 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 mEnabledProviders.add(provider);
2108 mDisabledProviders.remove(provider);
2109 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002110 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 mEnabledProviders.remove(provider);
2112 mDisabledProviders.add(provider);
2113 }
2114 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002115 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002116 }
2117 }
2118
Nick Pellye0fd6932012-07-11 10:26:13 -07002119 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002120 public void clearTestProviderEnabled(String provider) {
2121 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002122 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002123 MockProvider mockProvider = mMockProviders.get(provider);
2124 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2126 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002127 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 mEnabledProviders.remove(provider);
2129 mDisabledProviders.remove(provider);
2130 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002131 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
2133 }
2134
Nick Pellye0fd6932012-07-11 10:26:13 -07002135 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002136 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2137 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002138 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002139 MockProvider mockProvider = mMockProviders.get(provider);
2140 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002141 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2142 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002143 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002144 }
2145 }
2146
Nick Pellye0fd6932012-07-11 10:26:13 -07002147 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002148 public void clearTestProviderStatus(String provider) {
2149 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002150 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002151 MockProvider mockProvider = mMockProviders.get(provider);
2152 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2154 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002155 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157 }
2158
2159 private void log(String log) {
2160 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002161 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002162 }
2163 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002164
2165 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2167 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2168 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002169 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002170 + Binder.getCallingPid()
2171 + ", uid=" + Binder.getCallingUid());
2172 return;
2173 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002174
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002175 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002177 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002178 for (Receiver receiver : mReceivers.values()) {
2179 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002181 pw.println(" Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002182 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2183 pw.println(" " + entry.getKey() + ":");
2184 for (UpdateRecord record : entry.getValue()) {
2185 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 }
2187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002189 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2190 String provider = entry.getKey();
2191 Location location = entry.getValue();
2192 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002194
David Christie1b9b7b12013-04-15 15:31:11 -07002195 pw.println(" Last Known Locations Coarse Intervals:");
2196 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2197 String provider = entry.getKey();
2198 Location location = entry.getValue();
2199 pw.println(" " + provider + ": " + location);
2200 }
2201
Nick Pellye0fd6932012-07-11 10:26:13 -07002202 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002203
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 if (mEnabledProviders.size() > 0) {
2205 pw.println(" Enabled Providers:");
2206 for (String i : mEnabledProviders) {
2207 pw.println(" " + i);
2208 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210 }
2211 if (mDisabledProviders.size() > 0) {
2212 pw.println(" Disabled Providers:");
2213 for (String i : mDisabledProviders) {
2214 pw.println(" " + i);
2215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002216 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002217 pw.append(" ");
2218 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 if (mMockProviders.size() > 0) {
2220 pw.println(" Mock Providers:");
2221 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002222 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 }
2224 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002225
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002226 pw.append(" fudger: ");
2227 mLocationFudger.dump(fd, pw, args);
2228
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002229 if (args.length > 0 && "short".equals(args[0])) {
2230 return;
2231 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002232 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002233 pw.print(provider.getName() + " Internal State");
2234 if (provider instanceof LocationProviderProxy) {
2235 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2236 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002237 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002238 pw.println(":");
2239 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
2242 }
2243}