blob: 67e58a6724084bbe7024204dd753c2ca7ffc0098 [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
destradaaea8a8a62014-06-23 18:19:03 -070019import com.android.internal.content.PackageMonitor;
20import com.android.internal.location.ProviderProperties;
21import com.android.internal.location.ProviderRequest;
22import com.android.internal.os.BackgroundThread;
23import com.android.server.location.FlpHardwareProvider;
24import com.android.server.location.FusedProxy;
25import com.android.server.location.GeocoderProxy;
26import com.android.server.location.GeofenceManager;
27import com.android.server.location.GeofenceProxy;
28import com.android.server.location.GpsLocationProvider;
29import com.android.server.location.GpsMeasurementsProvider;
30import com.android.server.location.LocationBlacklist;
31import com.android.server.location.LocationFudger;
32import com.android.server.location.LocationProviderInterface;
33import com.android.server.location.LocationProviderProxy;
34import com.android.server.location.LocationRequestStatistics;
35import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
36import com.android.server.location.LocationRequestStatistics.PackageStatistics;
37import com.android.server.location.MockProvider;
38import com.android.server.location.PassiveProvider;
39
Dianne Hackborna06de0f2012-12-11 16:34:47 -080040import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070042import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.ContentResolver;
44import android.content.Context;
45import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070046import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070047import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050048import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.content.pm.PackageManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070050import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050051import android.content.pm.ResolveInfo;
52import android.content.pm.Signature;
Amith Yamasanib27528d2014-06-05 15:02:10 -070053import android.content.pm.UserInfo;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050054import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070055import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070057import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050058import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070059import android.location.Geofence;
destradaaea8a8a62014-06-23 18:19:03 -070060import android.location.IGpsMeasurementsListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.location.IGpsStatusListener;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -040062import android.location.IGpsStatusProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.location.ILocationListener;
64import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040065import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.location.Location;
67import android.location.LocationManager;
68import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070069import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Binder;
71import android.os.Bundle;
72import android.os.Handler;
73import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070074import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Message;
76import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070077import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070079import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070080import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070081import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070082import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080085import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070086
Mike Lockwood43e33f22010-03-26 10:41:48 -040087import java.io.FileDescriptor;
88import java.io.PrintWriter;
89import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070090import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040091import java.util.HashMap;
92import java.util.HashSet;
93import java.util.List;
94import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -040095import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
97/**
98 * The service class that manages LocationProviders and issues location
99 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800101public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800103 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700104
105 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106
Victoria Lease37425c32012-10-16 16:08:48 -0700107 // Location resolution level: no location data whatsoever
108 private static final int RESOLUTION_LEVEL_NONE = 0;
109 // Location resolution level: coarse location data only
110 private static final int RESOLUTION_LEVEL_COARSE = 1;
111 // Location resolution level: fine location data
112 private static final int RESOLUTION_LEVEL_FINE = 2;
113
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700115 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700117 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400118 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700119 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
120
121 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700122 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700123 private static final String FUSED_LOCATION_SERVICE_ACTION =
124 "com.android.location.service.FusedLocationProvider";
125
126 private static final int MSG_LOCATION_CHANGED = 1;
127
David Christie1b9b7b12013-04-15 15:31:11 -0700128 private static final long NANOS_PER_MILLI = 1000000L;
129
David Christie0b837452013-07-29 16:02:13 -0700130 // The maximum interval a location request can have and still be considered "high power".
131 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
132
Nick Pellyf1be6862012-05-15 10:53:42 -0700133 // Location Providers may sometimes deliver location updates
134 // slightly faster that requested - provide grace period so
135 // we don't unnecessarily filter events that are otherwise on
136 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700137 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700138
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700139 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
140
141 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800142 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700143
144 // used internally for synchronization
145 private final Object mLock = new Object();
146
Victoria Lease5cd731a2012-12-19 15:04:21 -0800147 // --- fields below are final after systemReady() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700148 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700149 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700150 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700151 private PowerManager mPowerManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700152 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700153 private GeocoderProxy mGeocodeProvider;
154 private IGpsStatusProvider mGpsStatusProvider;
155 private INetInitiatedListener mNetInitiatedListener;
156 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700157 private PassiveProvider mPassiveProvider; // track passive provider for special cases
158 private LocationBlacklist mBlacklist;
destradaaea8a8a62014-06-23 18:19:03 -0700159 private GpsMeasurementsProvider mGpsMeasurementsProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700160
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700161 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162 // Set of providers that are explicitly enabled
163 private final Set<String> mEnabledProviders = new HashSet<String>();
164
165 // Set of providers that are explicitly disabled
166 private final Set<String> mDisabledProviders = new HashSet<String>();
167
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700168 // Mock (test) providers
169 private final HashMap<String, MockProvider> mMockProviders =
170 new HashMap<String, MockProvider>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 // all receivers
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400173 private final HashMap<Object, Receiver> mReceivers = new HashMap<Object, Receiver>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700175 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500176 private final ArrayList<LocationProviderInterface> mProviders =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700177 new ArrayList<LocationProviderInterface>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400178
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700179 // real providers, saved here when mocked out
180 private final HashMap<String, LocationProviderInterface> mRealProviders =
181 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700183 // mapping from provider name to provider
184 private final HashMap<String, LocationProviderInterface> mProvidersByName =
185 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700187 // mapping from provider name to all its UpdateRecords
188 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
189 new HashMap<String, ArrayList<UpdateRecord>>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700190
David Christie2ff96af2014-01-30 16:09:37 -0800191 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
192
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700193 // mapping from provider name to last known location
194 private final HashMap<String, Location> mLastLocation = new HashMap<String, Location>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195
David Christie1b9b7b12013-04-15 15:31:11 -0700196 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
197 // locations stored here are not fudged for coarse permissions.
198 private final HashMap<String, Location> mLastLocationCoarseInterval =
199 new HashMap<String, Location>();
200
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700201 // all providers that operate over proxy, for authorizing incoming location
202 private final ArrayList<LocationProviderProxy> mProxyProviders =
203 new ArrayList<LocationProviderProxy>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Victoria Lease38389b62012-09-30 11:44:22 -0700205 // current active user on the device - other users are denied location data
206 private int mCurrentUserId = UserHandle.USER_OWNER;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700207 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_OWNER };
Victoria Lease38389b62012-09-30 11:44:22 -0700208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 public LocationManagerService(Context context) {
210 super();
211 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800212 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800213
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700214 if (D) Log.d(TAG, "Constructed");
215
216 // most startup is deferred until systemReady()
217 }
218
Svetoslav Ganova0027152013-06-25 14:59:53 -0700219 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700220 synchronized (mLock) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800221 if (D) Log.d(TAG, "systemReady()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700222
Victoria Lease5cd731a2012-12-19 15:04:21 -0800223 // fetch package manager
224 mPackageManager = mContext.getPackageManager();
225
Victoria Lease0aa28602013-05-29 15:28:26 -0700226 // fetch power manager
227 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800228
229 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700230 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800231
232 // prepare mLocationHandler's dependents
233 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
234 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
235 mBlacklist.init();
236 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
237
Dianne Hackbornc2293022013-02-06 23:14:49 -0800238 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700239 AppOpsManager.OnOpChangedListener callback
240 = new AppOpsManager.OnOpChangedInternalListener() {
241 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800242 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700243 for (Receiver receiver : mReceivers.values()) {
244 receiver.updateMonitoring(true);
245 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800246 applyAllProviderRequirementsLocked();
247 }
248 }
249 };
250 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
251
Amith Yamasanib27528d2014-06-05 15:02:10 -0700252 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
253 updateUserProfiles(mCurrentUserId);
254
Victoria Lease5cd731a2012-12-19 15:04:21 -0800255 // prepare providers
256 loadProvidersLocked();
257 updateProvidersLocked();
258 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700259
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700260 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700261 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700262 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700263 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800264 @Override
265 public void onChange(boolean selfChange) {
266 synchronized (mLock) {
267 updateProvidersLocked();
268 }
269 }
270 }, UserHandle.USER_ALL);
271 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700272
Victoria Lease38389b62012-09-30 11:44:22 -0700273 // listen for user change
274 IntentFilter intentFilter = new IntentFilter();
275 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700276 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
277 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Victoria Lease38389b62012-09-30 11:44:22 -0700278
279 mContext.registerReceiverAsUser(new BroadcastReceiver() {
280 @Override
281 public void onReceive(Context context, Intent intent) {
282 String action = intent.getAction();
283 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
284 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700285 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
286 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
287 updateUserProfiles(mCurrentUserId);
Victoria Lease38389b62012-09-30 11:44:22 -0700288 }
289 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800290 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700291 }
292
Amith Yamasanib27528d2014-06-05 15:02:10 -0700293 /**
294 * Makes a list of userids that are related to the current user. This is
295 * relevant when using managed profiles. Otherwise the list only contains
296 * the current user.
297 *
298 * @param currentUserId the current user, who might have an alter-ego.
299 */
300 void updateUserProfiles(int currentUserId) {
301 List<UserInfo> profiles = mUserManager.getProfiles(currentUserId);
302 synchronized (mLock) {
303 mCurrentUserProfiles = new int[profiles.size()];
304 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
305 mCurrentUserProfiles[i] = profiles.get(i).id;
306 }
307 }
308 }
309
310 /**
311 * Checks if the specified userId matches any of the current foreground
312 * users stored in mCurrentUserProfiles.
313 */
314 private boolean isCurrentProfile(int userId) {
315 synchronized (mLock) {
316 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
317 if (mCurrentUserProfiles[i] == userId) {
318 return true;
319 }
320 }
321 return false;
322 }
323 }
324
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500325 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
326 PackageManager pm = mContext.getPackageManager();
327 String systemPackageName = mContext.getPackageName();
328 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
329
330 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
331 new Intent(FUSED_LOCATION_SERVICE_ACTION),
332 PackageManager.GET_META_DATA, mCurrentUserId);
333 for (ResolveInfo rInfo : rInfos) {
334 String packageName = rInfo.serviceInfo.packageName;
335
336 // Check that the signature is in the list of supported sigs. If it's not in
337 // this list the standard provider binding logic won't bind to it.
338 try {
339 PackageInfo pInfo;
340 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
341 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
342 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
343 ", but has wrong signature, ignoring");
344 continue;
345 }
346 } catch (NameNotFoundException e) {
347 Log.e(TAG, "missing package: " + packageName);
348 continue;
349 }
350
351 // Get the version info
352 if (rInfo.serviceInfo.metaData == null) {
353 Log.w(TAG, "Found fused provider without metadata: " + packageName);
354 continue;
355 }
356
357 int version = rInfo.serviceInfo.metaData.getInt(
358 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
359 if (version == 0) {
360 // This should be the fallback fused location provider.
361
362 // Make sure it's in the system partition.
363 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
364 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
365 continue;
366 }
367
368 // Check that the fallback is signed the same as the OS
369 // as a proxy for coreApp="true"
370 if (pm.checkSignatures(systemPackageName, packageName)
371 != PackageManager.SIGNATURE_MATCH) {
372 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
373 + packageName);
374 continue;
375 }
376
377 // Found a valid fallback.
378 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
379 return;
380 } else {
381 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
382 }
383 }
384
385 throw new IllegalStateException("Unable to find a fused location provider that is in the "
386 + "system partition with version 0 and signed with the platform certificate. "
387 + "Such a package is needed to provide a default fused location provider in the "
388 + "event that no other fused location provider has been installed or is currently "
389 + "available. For example, coreOnly boot mode when decrypting the data "
390 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
391 }
392
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700393 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700394 // create a passive location provider, which is always enabled
395 PassiveProvider passiveProvider = new PassiveProvider(this);
396 addProviderLocked(passiveProvider);
397 mEnabledProviders.add(passiveProvider.getName());
398 mPassiveProvider = passiveProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700399 // Create a gps location provider
400 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
401 mLocationHandler.getLooper());
Victoria Lease5c24fd02012-10-01 11:00:50 -0700402
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700403 if (GpsLocationProvider.isSupported()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700404 mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
405 mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
406 addProviderLocked(gpsProvider);
407 mRealProviders.put(LocationManager.GPS_PROVIDER, gpsProvider);
408 }
destradaaea8a8a62014-06-23 18:19:03 -0700409 mGpsMeasurementsProvider = gpsProvider.getGpsMeasurementsProvider();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700410
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700411 /*
412 Load package name(s) containing location provider support.
413 These packages can contain services implementing location providers:
414 Geocoder Provider, Network Location Provider, and
415 Fused Location Provider. They will each be searched for
416 service components implementing these providers.
417 The location framework also has support for installation
418 of new location providers at run-time. The new package does not
419 have to be explicitly listed here, however it must have a signature
420 that matches the signature of at least one package on this list.
421 */
422 Resources resources = mContext.getResources();
423 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500424 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700425 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500426 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
427 Arrays.toString(pkgs));
428 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
429
430 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700431
432 // bind to network provider
433 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
434 mContext,
435 LocationManager.NETWORK_PROVIDER,
436 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700437 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
438 com.android.internal.R.string.config_networkLocationProviderPackageName,
439 com.android.internal.R.array.config_locationProviderPackageNames,
440 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700441 if (networkProvider != null) {
442 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
443 mProxyProviders.add(networkProvider);
444 addProviderLocked(networkProvider);
445 } else {
446 Slog.w(TAG, "no network location provider found");
447 }
448
449 // bind to fused provider
450 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
451 mContext,
452 LocationManager.FUSED_PROVIDER,
453 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700454 com.android.internal.R.bool.config_enableFusedLocationOverlay,
455 com.android.internal.R.string.config_fusedLocationProviderPackageName,
456 com.android.internal.R.array.config_locationProviderPackageNames,
457 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700458 if (fusedLocationProvider != null) {
459 addProviderLocked(fusedLocationProvider);
460 mProxyProviders.add(fusedLocationProvider);
461 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700462 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700463 } else {
464 Slog.e(TAG, "no fused location provider found",
465 new IllegalStateException("Location service needs a fused location provider"));
466 }
467
468 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700469 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
470 com.android.internal.R.bool.config_enableGeocoderOverlay,
471 com.android.internal.R.string.config_geocoderProviderPackageName,
472 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800473 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700474 if (mGeocodeProvider == null) {
475 Slog.e(TAG, "no geocoder provider found");
476 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700477
destradaacfbdcd22014-04-30 11:29:11 -0700478 // bind to fused provider if supported
destradaa5ce66d82014-05-28 18:24:08 -0700479 if (FlpHardwareProvider.isSupported()) {
480 FlpHardwareProvider flpHardwareProvider =
481 FlpHardwareProvider.getInstance(mContext);
destradaacfbdcd22014-04-30 11:29:11 -0700482 FusedProxy fusedProxy = FusedProxy.createAndBind(
483 mContext,
484 mLocationHandler,
485 flpHardwareProvider.getLocationHardware(),
destradaad5323172014-06-12 11:47:05 -0700486 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
487 com.android.internal.R.string.config_hardwareFlpPackageName,
destradaacfbdcd22014-04-30 11:29:11 -0700488 com.android.internal.R.array.config_locationProviderPackageNames);
489 if(fusedProxy == null) {
490 Slog.e(TAG, "Unable to bind FusedProxy.");
491 }
destradaa0682809a2013-08-12 18:50:30 -0700492
destradaacfbdcd22014-04-30 11:29:11 -0700493 // bind to geofence provider
494 GeofenceProxy provider = GeofenceProxy.createAndBind(mContext,
495 com.android.internal.R.bool.config_enableGeofenceOverlay,
496 com.android.internal.R.string.config_geofenceProviderPackageName,
497 com.android.internal.R.array.config_locationProviderPackageNames,
498 mLocationHandler,
499 gpsProvider.getGpsGeofenceProxy(),
500 flpHardwareProvider.getGeofenceHardware());
501 if (provider == null) {
502 Slog.e(TAG, "Unable to bind FLP Geofence proxy.");
503 }
504 } else {
505 Slog.e(TAG, "FLP HAL not supported.");
destradaa0682809a2013-08-12 18:50:30 -0700506 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900507
508 String[] testProviderStrings = resources.getStringArray(
509 com.android.internal.R.array.config_testLocationProviders);
510 for (String testProviderString : testProviderStrings) {
511 String fragments[] = testProviderString.split(",");
512 String name = fragments[0].trim();
513 if (mProvidersByName.get(name) != null) {
514 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
515 }
516 ProviderProperties properties = new ProviderProperties(
517 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
518 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
519 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
520 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
521 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
522 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
523 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
524 Integer.parseInt(fragments[8]) /* powerRequirement */,
525 Integer.parseInt(fragments[9]) /* accuracy */);
526 addTestProviderLocked(name, properties);
527 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700528 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700531 * Called when the device's active user changes.
532 * @param userId the new active user's UserId
533 */
534 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800535 if (mCurrentUserId == userId) {
536 return;
537 }
Victoria Lease83762d22012-10-03 13:51:17 -0700538 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800539 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700540 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700541 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700542 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700543 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700544 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700545 }
Victoria Lease38389b62012-09-30 11:44:22 -0700546 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700547 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700548 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700549 }
550 }
551
552 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800553 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
554 * location updates.
555 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700556 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700557 final int mUid; // uid of receiver
558 final int mPid; // pid of receiver
559 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700560 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 final ILocationListener mListener;
563 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700564 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700565 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800566 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700567
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400568 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700569
David Christie0b837452013-07-29 16:02:13 -0700570 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700571 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700572 // True if app ops has started monitoring this receiver for high power (gps) locations.
573 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700574 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700575 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700577 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700578 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800580 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700581 if (listener != null) {
582 mKey = listener.asBinder();
583 } else {
584 mKey = intent;
585 }
Victoria Lease37425c32012-10-16 16:08:48 -0700586 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700587 mUid = uid;
588 mPid = pid;
589 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700590 if (workSource != null && workSource.size() <= 0) {
591 workSource = null;
592 }
593 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700594 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700595
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700596 updateMonitoring(true);
597
Victoria Lease0aa28602013-05-29 15:28:26 -0700598 // construct/configure wakelock
599 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700600 if (workSource == null) {
601 workSource = new WorkSource(mUid, mPackageName);
602 }
603 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604 }
605
606 @Override
607 public boolean equals(Object otherObj) {
608 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700609 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800610 }
611 return false;
612 }
613
614 @Override
615 public int hashCode() {
616 return mKey.hashCode();
617 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400618
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800619 @Override
620 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700621 StringBuilder s = new StringBuilder();
622 s.append("Reciever[");
623 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700625 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700627 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800628 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700629 for (String p : mUpdateRecords.keySet()) {
630 s.append(" ").append(mUpdateRecords.get(p).toString());
631 }
632 s.append("]");
633 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800634 }
635
David Christie15b31912013-08-13 15:54:32 -0700636 /**
637 * Update AppOp monitoring for this receiver.
638 *
639 * @param allow If true receiver is currently active, if false it's been removed.
640 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700641 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700642 if (mHideFromAppOps) {
643 return;
644 }
645
David Christie15b31912013-08-13 15:54:32 -0700646 boolean requestingLocation = false;
647 boolean requestingHighPowerLocation = false;
648 if (allow) {
649 // See if receiver has any enabled update records. Also note if any update records
650 // are high power (has a high power provider with an interval under a threshold).
651 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
652 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
653 requestingLocation = true;
654 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800655 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700656 ProviderProperties properties = locationProvider != null
657 ? locationProvider.getProperties() : null;
658 if (properties != null
659 && properties.mPowerRequirement == Criteria.POWER_HIGH
660 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
661 requestingHighPowerLocation = true;
662 break;
663 }
664 }
665 }
666 }
667
David Christie0b837452013-07-29 16:02:13 -0700668 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700669 mOpMonitoring = updateMonitoring(
670 requestingLocation,
671 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700672 AppOpsManager.OP_MONITOR_LOCATION);
673
674 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700675 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700676 mOpHighPowerMonitoring = updateMonitoring(
677 requestingHighPowerLocation,
678 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700679 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700680 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700681 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700682 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
683 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
684 }
David Christie0b837452013-07-29 16:02:13 -0700685 }
686
687 /**
688 * Update AppOps monitoring for a single location request and op type.
689 *
690 * @param allowMonitoring True if monitoring is allowed for this request/op.
691 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
692 * @param op AppOps code for the op to update.
693 * @return True if monitoring is on for this request/op after updating.
694 */
695 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
696 int op) {
697 if (!currentlyMonitoring) {
698 if (allowMonitoring) {
699 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
700 == AppOpsManager.MODE_ALLOWED;
701 }
702 } else {
703 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
704 != AppOpsManager.MODE_ALLOWED) {
705 mAppOps.finishOp(op, mUid, mPackageName);
706 return false;
707 }
708 }
709
710 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700711 }
712
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800713 public boolean isListener() {
714 return mListener != null;
715 }
716
717 public boolean isPendingIntent() {
718 return mPendingIntent != null;
719 }
720
721 public ILocationListener getListener() {
722 if (mListener != null) {
723 return mListener;
724 }
725 throw new IllegalStateException("Request for non-existent listener");
726 }
727
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800728 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
729 if (mListener != null) {
730 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700731 synchronized (this) {
732 // synchronize to ensure incrementPendingBroadcastsLocked()
733 // is called before decrementPendingBroadcasts()
734 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700735 // call this after broadcasting so we do not increment
736 // if we throw an exeption.
737 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 } catch (RemoteException e) {
740 return false;
741 }
742 } else {
743 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800744 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
746 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700747 synchronized (this) {
748 // synchronize to ensure incrementPendingBroadcastsLocked()
749 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700750 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700751 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700752 // call this after broadcasting so we do not increment
753 // if we throw an exeption.
754 incrementPendingBroadcastsLocked();
755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 } catch (PendingIntent.CanceledException e) {
757 return false;
758 }
759 }
760 return true;
761 }
762
763 public boolean callLocationChangedLocked(Location location) {
764 if (mListener != null) {
765 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700766 synchronized (this) {
767 // synchronize to ensure incrementPendingBroadcastsLocked()
768 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800769 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700770 // call this after broadcasting so we do not increment
771 // if we throw an exeption.
772 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700773 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 } catch (RemoteException e) {
775 return false;
776 }
777 } else {
778 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800779 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800780 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700781 synchronized (this) {
782 // synchronize to ensure incrementPendingBroadcastsLocked()
783 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700784 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700785 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700786 // call this after broadcasting so we do not increment
787 // if we throw an exeption.
788 incrementPendingBroadcastsLocked();
789 }
790 } catch (PendingIntent.CanceledException e) {
791 return false;
792 }
793 }
794 return true;
795 }
796
797 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700798 // First update AppOp monitoring.
799 // An app may get/lose location access as providers are enabled/disabled.
800 updateMonitoring(true);
801
Mike Lockwood48f17512009-04-23 09:12:08 -0700802 if (mListener != null) {
803 try {
804 synchronized (this) {
805 // synchronize to ensure incrementPendingBroadcastsLocked()
806 // is called before decrementPendingBroadcasts()
807 if (enabled) {
808 mListener.onProviderEnabled(provider);
809 } else {
810 mListener.onProviderDisabled(provider);
811 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700812 // call this after broadcasting so we do not increment
813 // if we throw an exeption.
814 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700815 }
816 } catch (RemoteException e) {
817 return false;
818 }
819 } else {
820 Intent providerIntent = new Intent();
821 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
822 try {
823 synchronized (this) {
824 // synchronize to ensure incrementPendingBroadcastsLocked()
825 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700826 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700827 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700828 // call this after broadcasting so we do not increment
829 // if we throw an exeption.
830 incrementPendingBroadcastsLocked();
831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800832 } catch (PendingIntent.CanceledException e) {
833 return false;
834 }
835 }
836 return true;
837 }
838
Nick Pellyf1be6862012-05-15 10:53:42 -0700839 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700841 if (D) Log.d(TAG, "Location listener died");
842
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400843 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 removeUpdatesLocked(this);
845 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700846 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700847 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700848 }
849 }
850
Nick Pellye0fd6932012-07-11 10:26:13 -0700851 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700852 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
853 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400854 synchronized (this) {
855 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700856 }
857 }
858
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400859 // this must be called while synchronized by caller in a synchronized block
860 // containing the sending of the broadcaset
861 private void incrementPendingBroadcastsLocked() {
862 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700863 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400864 }
865 }
866
867 private void decrementPendingBroadcastsLocked() {
868 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700869 if (mWakeLock.isHeld()) {
870 mWakeLock.release();
871 }
872 }
873 }
874
875 public void clearPendingBroadcastsLocked() {
876 if (mPendingBroadcasts > 0) {
877 mPendingBroadcasts = 0;
878 if (mWakeLock.isHeld()) {
879 mWakeLock.release();
880 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700881 }
882 }
883 }
884
Nick Pellye0fd6932012-07-11 10:26:13 -0700885 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700886 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700887 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -0400888 //the receiver list if it is not found. If it is not found then the
889 //LocationListener was removed when it had a pending broadcast and should
890 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700891 synchronized (mLock) {
892 IBinder binder = listener.asBinder();
893 Receiver receiver = mReceivers.get(binder);
894 if (receiver != null) {
895 synchronized (receiver) {
896 // so wakelock calls will succeed
897 long identity = Binder.clearCallingIdentity();
898 receiver.decrementPendingBroadcastsLocked();
899 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -0800900 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800902 }
903 }
904
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700905 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400906 mProviders.add(provider);
907 mProvidersByName.put(provider.getName(), provider);
908 }
909
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700910 private void removeProviderLocked(LocationProviderInterface provider) {
911 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400912 mProviders.remove(provider);
913 mProvidersByName.remove(provider.getName());
914 }
915
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800916 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800917 * Returns "true" if access to the specified location provider is allowed by the current
918 * user's settings. Access to all location providers is forbidden to non-location-provider
919 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800920 *
921 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800922 * @return
923 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800924 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 if (mEnabledProviders.contains(provider)) {
926 return true;
927 }
928 if (mDisabledProviders.contains(provider)) {
929 return false;
930 }
931 // Use system settings
932 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800933
Victoria Leaseb711d572012-10-02 13:14:11 -0700934 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800935 }
936
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700937 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800938 * Returns "true" if access to the specified location provider is allowed by the specified
939 * user's settings. Access to all location providers is forbidden to non-location-provider
940 * processes belonging to background users.
941 *
942 * @param provider the name of the location provider
943 * @param uid the requestor's UID
944 * @return
945 */
946 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700947 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800948 return false;
949 }
950 return isAllowedByCurrentUserSettingsLocked(provider);
951 }
952
953 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700954 * Returns the permission string associated with the specified resolution level.
955 *
956 * @param resolutionLevel the resolution level
957 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700958 */
Victoria Lease37425c32012-10-16 16:08:48 -0700959 private String getResolutionPermission(int resolutionLevel) {
960 switch (resolutionLevel) {
961 case RESOLUTION_LEVEL_FINE:
962 return android.Manifest.permission.ACCESS_FINE_LOCATION;
963 case RESOLUTION_LEVEL_COARSE:
964 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
965 default:
966 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700968 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700969
Victoria Leaseda479c52012-10-15 15:24:16 -0700970 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700971 * Returns the resolution level allowed to the given PID/UID pair.
972 *
973 * @param pid the PID
974 * @param uid the UID
975 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -0700976 */
Victoria Lease37425c32012-10-16 16:08:48 -0700977 private int getAllowedResolutionLevel(int pid, int uid) {
978 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
979 pid, uid) == PackageManager.PERMISSION_GRANTED) {
980 return RESOLUTION_LEVEL_FINE;
981 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
982 pid, uid) == PackageManager.PERMISSION_GRANTED) {
983 return RESOLUTION_LEVEL_COARSE;
984 } else {
985 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -0700986 }
Victoria Lease4fab68b2012-09-13 13:20:59 -0700987 }
988
989 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700990 * Returns the resolution level allowed to the caller
991 *
992 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -0700993 */
Victoria Lease37425c32012-10-16 16:08:48 -0700994 private int getCallerAllowedResolutionLevel() {
995 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
996 }
997
998 /**
999 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1000 *
1001 * @param allowedResolutionLevel resolution level allowed to caller
1002 */
1003 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1004 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001005 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008
Victoria Lease37425c32012-10-16 16:08:48 -07001009 /**
1010 * Return the minimum resolution level required to use the specified location provider.
1011 *
1012 * @param provider the name of the location provider
1013 * @return minimum resolution level required for provider
1014 */
1015 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001016 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1017 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1018 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001019 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001020 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1021 LocationManager.FUSED_PROVIDER.equals(provider)) {
1022 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001023 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001024 } else {
1025 // mock providers
1026 LocationProviderInterface lp = mMockProviders.get(provider);
1027 if (lp != null) {
1028 ProviderProperties properties = lp.getProperties();
1029 if (properties != null) {
1030 if (properties.mRequiresSatellite) {
1031 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001032 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001033 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1034 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001035 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001036 }
1037 }
1038 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001039 }
Victoria Lease37425c32012-10-16 16:08:48 -07001040 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001041 }
1042
Victoria Lease37425c32012-10-16 16:08:48 -07001043 /**
1044 * Throw SecurityException if specified resolution level is insufficient to use the named
1045 * location provider.
1046 *
1047 * @param allowedResolutionLevel resolution level allowed to caller
1048 * @param providerName the name of the location provider
1049 */
1050 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1051 String providerName) {
1052 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1053 if (allowedResolutionLevel < requiredResolutionLevel) {
1054 switch (requiredResolutionLevel) {
1055 case RESOLUTION_LEVEL_FINE:
1056 throw new SecurityException("\"" + providerName + "\" location provider " +
1057 "requires ACCESS_FINE_LOCATION permission.");
1058 case RESOLUTION_LEVEL_COARSE:
1059 throw new SecurityException("\"" + providerName + "\" location provider " +
1060 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1061 default:
1062 throw new SecurityException("Insufficient permission for \"" + providerName +
1063 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001064 }
1065 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001066 }
1067
David Christie82edc9b2013-07-19 11:31:42 -07001068 /**
1069 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1070 * for battery).
1071 */
David Christie40e57822013-07-30 11:36:48 -07001072 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001073 mContext.enforceCallingOrSelfPermission(
1074 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1075 }
1076
David Christie40e57822013-07-30 11:36:48 -07001077 private void checkUpdateAppOpsAllowed() {
1078 mContext.enforceCallingOrSelfPermission(
1079 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1080 }
1081
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001082 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001083 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1084 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001085 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001086 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001087 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001088 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001089 }
1090 return -1;
1091 }
1092
1093 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
1094 int op = resolutionLevelToOp(allowedResolutionLevel);
1095 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001096 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1097 return false;
1098 }
1099 }
1100 return true;
1101 }
1102
1103 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001104 int op = resolutionLevelToOp(allowedResolutionLevel);
1105 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001106 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1107 return false;
1108 }
1109 }
1110 return true;
1111 }
1112
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001113 /**
1114 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001115 * fused, also including ones that are not permitted to
1116 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001117 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001118 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001120 ArrayList<String> out;
1121 synchronized (mLock) {
1122 out = new ArrayList<String>(mProviders.size());
1123 for (LocationProviderInterface provider : mProviders) {
1124 String name = provider.getName();
1125 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001126 continue;
1127 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 out.add(name);
1129 }
1130 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001131
1132 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001133 return out;
1134 }
1135
Mike Lockwood03ca2162010-04-01 08:10:09 -07001136 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001137 * Return all providers by name, that match criteria and are optionally
1138 * enabled.
1139 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001140 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001141 @Override
1142 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001143 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001144 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001145 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -07001146 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001147 try {
1148 synchronized (mLock) {
1149 out = new ArrayList<String>(mProviders.size());
1150 for (LocationProviderInterface provider : mProviders) {
1151 String name = provider.getName();
1152 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001153 continue;
1154 }
Victoria Lease37425c32012-10-16 16:08:48 -07001155 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001156 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001157 continue;
1158 }
1159 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1160 name, provider.getProperties(), criteria)) {
1161 continue;
1162 }
1163 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001164 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001165 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001166 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001167 } finally {
1168 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001169 }
1170
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001171 if (D) Log.d(TAG, "getProviders()=" + out);
1172 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001173 }
1174
1175 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001176 * Return the name of the best provider given a Criteria object.
1177 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001178 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001179 * has been deprecated as well. So this method now uses
1180 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001181 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001182 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001183 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001184 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001185
1186 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001187 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001188 result = pickBest(providers);
1189 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1190 return result;
1191 }
1192 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001193 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001194 result = pickBest(providers);
1195 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1196 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001197 }
1198
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001199 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001200 return null;
1201 }
1202
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001203 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001204 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001205 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001206 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1207 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001208 } else {
1209 return providers.get(0);
1210 }
1211 }
1212
Nick Pellye0fd6932012-07-11 10:26:13 -07001213 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001214 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1215 LocationProviderInterface p = mProvidersByName.get(provider);
1216 if (p == null) {
1217 throw new IllegalArgumentException("provider=" + provider);
1218 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001219
1220 boolean result = LocationProvider.propertiesMeetCriteria(
1221 p.getName(), p.getProperties(), criteria);
1222 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1223 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001224 }
1225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001227 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001228 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001229 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 boolean isEnabled = p.isEnabled();
1231 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001232 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001234 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001235 // If any provider has been disabled, clear all last locations for all providers.
1236 // This is to be on the safe side in case a provider has location derived from
1237 // this disabled provider.
1238 mLastLocation.clear();
1239 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001240 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001242 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001243 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001245 }
1246 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001247 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1248 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001249 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1250 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 }
1252 }
1253
Amith Yamasanib27528d2014-06-05 15:02:10 -07001254 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 int listeners = 0;
1256
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001257 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001258 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259
1260 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001261
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1263 if (records != null) {
1264 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001265 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 UpdateRecord record = records.get(i);
Amith Yamasanib27528d2014-06-05 15:02:10 -07001267 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001268 // Sends a notification message to the receiver
1269 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1270 if (deadReceivers == null) {
1271 deadReceivers = new ArrayList<Receiver>();
1272 }
1273 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001275 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 }
1278 }
1279
1280 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001281 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 removeUpdatesLocked(deadReceivers.get(i));
1283 }
1284 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001285
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 if (enabled) {
1287 p.enable();
1288 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001289 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 }
1295
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001296 private void applyRequirementsLocked(String provider) {
1297 LocationProviderInterface p = mProvidersByName.get(provider);
1298 if (p == null) return;
1299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001301 WorkSource worksource = new WorkSource();
1302 ProviderRequest providerRequest = new ProviderRequest();
1303
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001305 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001306 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001307 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1308 record.mReceiver.mAllowedResolutionLevel)) {
1309 LocationRequest locationRequest = record.mRequest;
1310 providerRequest.locationRequests.add(locationRequest);
1311 if (locationRequest.getInterval() < providerRequest.interval) {
1312 providerRequest.reportLocation = true;
1313 providerRequest.interval = locationRequest.getInterval();
1314 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001315 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001316 }
1317 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001318
1319 if (providerRequest.reportLocation) {
1320 // calculate who to blame for power
1321 // This is somewhat arbitrary. We pick a threshold interval
1322 // that is slightly higher that the minimum interval, and
1323 // spread the blame across all applications with a request
1324 // under that threshold.
1325 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1326 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001327 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001328 LocationRequest locationRequest = record.mRequest;
1329 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001330 if (record.mReceiver.mWorkSource != null
1331 && record.mReceiver.mWorkSource.size() > 0
1332 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001333 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001334 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001335 worksource.add(record.mReceiver.mWorkSource);
1336 } else {
1337 // Assign blame to caller.
1338 worksource.add(
1339 record.mReceiver.mUid,
1340 record.mReceiver.mPackageName);
1341 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001342 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001343 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001344 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 }
1346 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001347
1348 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1349 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351
1352 private class UpdateRecord {
1353 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001354 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001356 Location mLastFixBroadcast;
1357 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358
1359 /**
1360 * Note: must be constructed with lock held.
1361 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001362 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001364 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001365 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366
1367 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1368 if (records == null) {
1369 records = new ArrayList<UpdateRecord>();
1370 mRecordsByProvider.put(provider, records);
1371 }
1372 if (!records.contains(this)) {
1373 records.add(this);
1374 }
David Christie2ff96af2014-01-30 16:09:37 -08001375
1376 // Update statistics for historical location requests by package/provider
1377 mRequestStatistics.startRequesting(
1378 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
1380
1381 /**
David Christie2ff96af2014-01-30 16:09:37 -08001382 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001384 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001385 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1386
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001387 // remove from mRecordsByProvider
1388 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1389 if (globalRecords != null) {
1390 globalRecords.remove(this);
1391 }
1392
1393 if (!removeReceiver) return; // the caller will handle the rest
1394
1395 // remove from Receiver#mUpdateRecords
1396 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1397 if (receiverRecords != null) {
1398 receiverRecords.remove(this.mProvider);
1399
1400 // and also remove the Receiver if it has no more update records
1401 if (removeReceiver && receiverRecords.size() == 0) {
1402 removeUpdatesLocked(mReceiver);
1403 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406
1407 @Override
1408 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001409 StringBuilder s = new StringBuilder();
1410 s.append("UpdateRecord[");
1411 s.append(mProvider);
1412 s.append(' ').append(mReceiver.mPackageName).append('(');
1413 s.append(mReceiver.mUid).append(')');
1414 s.append(' ').append(mRequest);
1415 s.append(']');
1416 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001420 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001421 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001422 IBinder binder = listener.asBinder();
1423 Receiver receiver = mReceivers.get(binder);
1424 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001425 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1426 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001427 mReceivers.put(binder, receiver);
1428
1429 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001430 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001431 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001432 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001433 return null;
1434 }
1435 }
1436 return receiver;
1437 }
1438
David Christie82edc9b2013-07-19 11:31:42 -07001439 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001440 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001441 Receiver receiver = mReceivers.get(intent);
1442 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001443 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1444 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001445 mReceivers.put(intent, receiver);
1446 }
1447 return receiver;
1448 }
1449
Victoria Lease37425c32012-10-16 16:08:48 -07001450 /**
1451 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1452 * and consistency requirements.
1453 *
1454 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001455 * @return a version of request that meets the given resolution and consistency requirements
1456 * @hide
1457 */
1458 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1459 LocationRequest sanitizedRequest = new LocationRequest(request);
1460 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1461 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001462 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001463 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001464 break;
1465 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001466 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001467 break;
1468 }
1469 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001470 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1471 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001472 }
Victoria Lease37425c32012-10-16 16:08:48 -07001473 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1474 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001475 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001476 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001477 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001478 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001479 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001480 }
Victoria Lease37425c32012-10-16 16:08:48 -07001481 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001482 }
1483
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001484 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001485 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001486 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001487 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001488 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001489 String[] packages = mPackageManager.getPackagesForUid(uid);
1490 if (packages == null) {
1491 throw new SecurityException("invalid UID " + uid);
1492 }
1493 for (String pkg : packages) {
1494 if (packageName.equals(pkg)) return;
1495 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001496 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001497 }
1498
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001499 private void checkPendingIntent(PendingIntent intent) {
1500 if (intent == null) {
1501 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001502 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001503 }
1504
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001505 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001506 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001507 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001508 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001509 } else if (intent != null && listener != null) {
1510 throw new IllegalArgumentException("cannot register both listener and intent");
1511 } else if (intent != null) {
1512 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001513 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001514 } else {
David Christie40e57822013-07-30 11:36:48 -07001515 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001516 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001517 }
1518
Nick Pellye0fd6932012-07-11 10:26:13 -07001519 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001520 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1521 PendingIntent intent, String packageName) {
1522 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1523 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001524 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1525 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1526 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07001527 WorkSource workSource = request.getWorkSource();
1528 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07001529 checkDeviceStatsAllowed();
1530 }
1531 boolean hideFromAppOps = request.getHideFromAppOps();
1532 if (hideFromAppOps) {
1533 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07001534 }
Victoria Lease37425c32012-10-16 16:08:48 -07001535 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001537 final int pid = Binder.getCallingPid();
1538 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001539 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 long identity = Binder.clearCallingIdentity();
1541 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001542 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1543 // a location.
Dianne Hackborn35654b62013-01-14 17:38:02 -08001544 checkLocationAccess(uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001545
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001546 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001547 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07001548 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07001549 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 } finally {
1552 Binder.restoreCallingIdentity(identity);
1553 }
1554 }
1555
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001556 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1557 int pid, int uid, String packageName) {
1558 // Figure out the provider. Either its explicitly request (legacy use cases), or
1559 // use the fused provider
1560 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1561 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001562 if (name == null) {
1563 throw new IllegalArgumentException("provider name must not be null");
1564 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001565
1566 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1567 + " " + name + " " + request + " from " + packageName + "(" + uid + ")");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001568 LocationProviderInterface provider = mProvidersByName.get(name);
1569 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07001570 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001571 }
1572
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001573 UpdateRecord record = new UpdateRecord(name, request, receiver);
1574 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1575 if (oldRecord != null) {
1576 oldRecord.disposeLocked(false);
1577 }
1578
Victoria Lease09eeaec2013-02-05 11:34:13 -08001579 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001580 if (isProviderEnabled) {
1581 applyRequirementsLocked(name);
1582 } else {
1583 // Notify the listener that updates are currently disabled
1584 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
David Christie0b837452013-07-29 16:02:13 -07001586 // Update the monitoring here just in case multiple location requests were added to the
1587 // same receiver (this request may be high power and the initial might not have been).
1588 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 }
1590
Nick Pellye0fd6932012-07-11 10:26:13 -07001591 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001592 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1593 String packageName) {
1594 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001595
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001596 final int pid = Binder.getCallingPid();
1597 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001598
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001599 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07001600 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07001601 boolean hideFromAppOps = false;
1602 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
1603 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001604
1605 // providers may use public location API's, need to clear identity
1606 long identity = Binder.clearCallingIdentity();
1607 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001608 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001609 } finally {
1610 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
1613 }
1614
1615 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001616 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001617
1618 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1619 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1620 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001621 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001622 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07001625 receiver.updateMonitoring(false);
1626
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001627 // Record which providers were associated with this listener
1628 HashSet<String> providers = new HashSet<String>();
1629 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1630 if (oldRecords != null) {
1631 // Call dispose() on the obsolete update records.
1632 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08001633 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001634 record.disposeLocked(false);
1635 }
1636 // Accumulate providers
1637 providers.addAll(oldRecords.keySet());
1638 }
1639
1640 // update provider
1641 for (String provider : providers) {
1642 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001643 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001644 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001647 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001648 }
1649 }
1650
Dianne Hackbornc2293022013-02-06 23:14:49 -08001651 private void applyAllProviderRequirementsLocked() {
1652 for (LocationProviderInterface p : mProviders) {
1653 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001654 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001655 continue;
1656 }
1657
1658 applyRequirementsLocked(p.getName());
1659 }
1660 }
1661
Nick Pellye0fd6932012-07-11 10:26:13 -07001662 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001663 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001664 if (D) Log.d(TAG, "getLastLocation: " + request);
1665 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001666 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001667 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001668 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1669 request.getProvider());
1670 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001671
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001672 final int uid = Binder.getCallingUid();
1673 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001674 try {
1675 if (mBlacklist.isBlacklisted(packageName)) {
1676 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1677 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001678 return null;
1679 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001680
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001681 if (!reportLocationAccessNoThrow(uid, packageName, allowedResolutionLevel)) {
1682 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1683 packageName);
1684 return null;
1685 }
1686
Victoria Leaseb711d572012-10-02 13:14:11 -07001687 synchronized (mLock) {
1688 // Figure out the provider. Either its explicitly request (deprecated API's),
1689 // or use the fused provider
1690 String name = request.getProvider();
1691 if (name == null) name = LocationManager.FUSED_PROVIDER;
1692 LocationProviderInterface provider = mProvidersByName.get(name);
1693 if (provider == null) return null;
1694
Victoria Lease09eeaec2013-02-05 11:34:13 -08001695 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001696
David Christie1b9b7b12013-04-15 15:31:11 -07001697 Location location;
1698 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1699 // Make sure that an app with coarse permissions can't get frequent location
1700 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1701 location = mLastLocationCoarseInterval.get(name);
1702 } else {
1703 location = mLastLocation.get(name);
1704 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001705 if (location == null) {
1706 return null;
1707 }
Victoria Lease37425c32012-10-16 16:08:48 -07001708 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001709 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1710 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001711 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001712 }
Victoria Lease37425c32012-10-16 16:08:48 -07001713 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001714 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001715 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001716 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001717 return null;
1718 } finally {
1719 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001720 }
1721 }
1722
1723 @Override
1724 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1725 String packageName) {
1726 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001727 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1728 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001729 checkPendingIntent(intent);
1730 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001731 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1732 request.getProvider());
1733 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001734
Victoria Lease37425c32012-10-16 16:08:48 -07001735 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001736
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001737 // geo-fence manager uses the public location API, need to clear identity
1738 int uid = Binder.getCallingUid();
Victoria Lease56e675b2012-11-05 19:25:06 -08001739 if (UserHandle.getUserId(uid) != UserHandle.USER_OWNER) {
1740 // temporary measure until geofences work for secondary users
1741 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1742 return;
1743 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001744 long identity = Binder.clearCallingIdentity();
1745 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001746 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1747 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001748 } finally {
1749 Binder.restoreCallingIdentity(identity);
1750 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001751 }
1752
1753 @Override
1754 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Victoria Lease37425c32012-10-16 16:08:48 -07001755 checkResolutionLevelIsSufficientForGeofenceUse(getCallerAllowedResolutionLevel());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001756 checkPendingIntent(intent);
1757 checkPackageName(packageName);
1758
1759 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1760
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001761 // geo-fence manager uses the public location API, need to clear identity
1762 long identity = Binder.clearCallingIdentity();
1763 try {
1764 mGeofenceManager.removeFence(geofence, intent);
1765 } finally {
1766 Binder.restoreCallingIdentity(identity);
1767 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001768 }
1769
1770
1771 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001772 public boolean addGpsStatusListener(IGpsStatusListener listener, String packageName) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001773 if (mGpsStatusProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 return false;
1775 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001776 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1777 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001778 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001780 final int uid = Binder.getCallingUid();
1781 final long ident = Binder.clearCallingIdentity();
1782 try {
Victoria Lease3d5173d2013-02-05 16:07:32 -08001783 if (!checkLocationAccess(uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001784 return false;
1785 }
1786 } finally {
1787 Binder.restoreCallingIdentity(ident);
1788 }
1789
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 try {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001791 mGpsStatusProvider.addGpsStatusListener(listener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001793 Slog.e(TAG, "mGpsStatusProvider.addGpsStatusListener failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001794 return false;
1795 }
1796 return true;
1797 }
1798
Nick Pellye0fd6932012-07-11 10:26:13 -07001799 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 public void removeGpsStatusListener(IGpsStatusListener listener) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001801 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001802 try {
1803 mGpsStatusProvider.removeGpsStatusListener(listener);
1804 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001805 Slog.e(TAG, "mGpsStatusProvider.removeGpsStatusListener failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
1808 }
1809
Nick Pellye0fd6932012-07-11 10:26:13 -07001810 @Override
destradaaea8a8a62014-06-23 18:19:03 -07001811 public boolean addGpsMeasurementsListener(
1812 IGpsMeasurementsListener listener,
1813 String packageName) {
1814 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1815 checkResolutionLevelIsSufficientForProviderUse(
1816 allowedResolutionLevel,
1817 LocationManager.GPS_PROVIDER);
1818
1819 int uid = Binder.getCallingUid();
1820 long identity = Binder.clearCallingIdentity();
1821 boolean hasLocationAccess;
1822 try {
1823 hasLocationAccess = checkLocationAccess(uid, packageName, allowedResolutionLevel);
1824 } finally {
1825 Binder.restoreCallingIdentity(identity);
1826 }
1827
1828 if (!hasLocationAccess) {
1829 return false;
1830 }
1831
1832 return mGpsMeasurementsProvider.addListener(listener);
1833 }
1834
1835 @Override
1836 public boolean removeGpsMeasurementsListener(IGpsMeasurementsListener listener) {
1837 return mGpsMeasurementsProvider.removeListener(listener);
1838 }
1839
1840 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001842 if (provider == null) {
1843 // throw NullPointerException to remain compatible with previous implementation
1844 throw new NullPointerException();
1845 }
Victoria Lease37425c32012-10-16 16:08:48 -07001846 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1847 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001848
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001849 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001850 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 != PackageManager.PERMISSION_GRANTED)) {
1852 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1853 }
1854
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001855 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001856 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001857 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001858
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001859 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861 }
1862
Nick Pellye0fd6932012-07-11 10:26:13 -07001863 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001864 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001865 if (Binder.getCallingUid() != Process.myUid()) {
1866 throw new SecurityException(
1867 "calling sendNiResponse from outside of the system is not allowed");
1868 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001869 try {
1870 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001871 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001872 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001873 return false;
1874 }
1875 }
1876
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001878 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001879 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 * accessed by the caller
1881 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001882 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001883 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001884 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08001885 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07001886 }
1887
Victoria Lease37425c32012-10-16 16:08:48 -07001888 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1889 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001890
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001891 LocationProviderInterface p;
1892 synchronized (mLock) {
1893 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001894 }
1895
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001896 if (p == null) return null;
1897 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
1899
Nick Pellye0fd6932012-07-11 10:26:13 -07001900 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07001902 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
1903 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001904 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1905
Victoria Lease09eeaec2013-02-05 11:34:13 -08001906 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001907 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001908 try {
1909 synchronized (mLock) {
1910 LocationProviderInterface p = mProvidersByName.get(provider);
1911 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001912
Victoria Lease09eeaec2013-02-05 11:34:13 -08001913 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001914 }
1915 } finally {
1916 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001917 }
1918 }
1919
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001920 /**
1921 * Returns "true" if the UID belongs to a bound location provider.
1922 *
1923 * @param uid the uid
1924 * @return true if uid belongs to a bound location provider
1925 */
1926 private boolean isUidALocationProvider(int uid) {
1927 if (uid == Process.SYSTEM_UID) {
1928 return true;
1929 }
1930 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07001931 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001932 }
1933 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07001934 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001935 }
1936 return false;
1937 }
1938
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001939 private void checkCallerIsProvider() {
1940 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
1941 == PackageManager.PERMISSION_GRANTED) {
1942 return;
1943 }
1944
1945 // Previously we only used the INSTALL_LOCATION_PROVIDER
1946 // check. But that is system or signature
1947 // protection level which is not flexible enough for
1948 // providers installed oustide the system image. So
1949 // also allow providers with a UID matching the
1950 // currently bound package name
1951
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001952 if (isUidALocationProvider(Binder.getCallingUid())) {
1953 return;
1954 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001955
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001956 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
1957 "or UID of a currently bound location provider");
1958 }
1959
David Christie1f141c12014-05-14 15:11:15 -07001960 /**
1961 * Returns true if the given package belongs to the given uid.
1962 */
1963 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001964 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 return false;
1966 }
David Christie1f141c12014-05-14 15:11:15 -07001967 String[] packageNames = mPackageManager.getPackagesForUid(uid);
1968 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001969 return false;
1970 }
David Christie1f141c12014-05-14 15:11:15 -07001971 for (String name : packageNames) {
1972 if (packageName.equals(name)) {
1973 return true;
1974 }
1975 }
1976 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
1978
Nick Pellye0fd6932012-07-11 10:26:13 -07001979 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05001980 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001981 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04001982
Nick Pelly2eeeec22012-07-18 13:13:37 -07001983 if (!location.isComplete()) {
1984 Log.w(TAG, "Dropping incomplete location: " + location);
1985 return;
1986 }
1987
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001988 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
1989 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05001990 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07001991 mLocationHandler.sendMessageAtFrontOfQueue(m);
1992 }
1993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994
Laurent Tu75defb62012-11-01 16:21:52 -07001995 private static boolean shouldBroadcastSafe(
1996 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001997 // Always broadcast the first update
1998 if (lastLoc == null) {
1999 return true;
2000 }
2001
Nick Pellyf1be6862012-05-15 10:53:42 -07002002 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002003 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002004 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2005 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002006 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 return false;
2008 }
2009
2010 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002011 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 if (minDistance > 0.0) {
2013 if (loc.distanceTo(lastLoc) <= minDistance) {
2014 return false;
2015 }
2016 }
2017
Laurent Tu75defb62012-11-01 16:21:52 -07002018 // Check whether sufficient number of udpates is left
2019 if (record.mRequest.getNumUpdates() <= 0) {
2020 return false;
2021 }
2022
2023 // Check whether the expiry date has passed
2024 if (record.mRequest.getExpireAt() < now) {
2025 return false;
2026 }
2027
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002028 return true;
2029 }
2030
Mike Lockwooda4903f22010-02-17 06:42:23 -05002031 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002032 if (D) Log.d(TAG, "incoming location: " + location);
2033
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002034 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002035 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002036
Laurent Tu60ec50a2012-10-04 17:00:10 -07002037 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002038 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002039 if (p == null) return;
2040
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002041 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002042 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2043 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002044 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002045 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002046 lastLocation = new Location(provider);
2047 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002048 } else {
2049 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2050 if (noGPSLocation == null && lastNoGPSLocation != null) {
2051 // New location has no no-GPS location: adopt last no-GPS location. This is set
2052 // directly into location because we do not want to notify COARSE clients.
2053 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2054 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002055 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002056 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057
David Christie1b9b7b12013-04-15 15:31:11 -07002058 // Update last known coarse interval location if enough time has passed.
2059 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2060 if (lastLocationCoarseInterval == null) {
2061 lastLocationCoarseInterval = new Location(location);
2062 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2063 }
2064 long timeDiffNanos = location.getElapsedRealtimeNanos()
2065 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2066 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2067 lastLocationCoarseInterval.set(location);
2068 }
2069 // Don't ever return a coarse location that is more recent than the allowed update
2070 // interval (i.e. don't allow an app to keep registering and unregistering for
2071 // location updates to overcome the minimum interval).
2072 noGPSLocation =
2073 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2074
Laurent Tu60ec50a2012-10-04 17:00:10 -07002075 // Skip if there are no UpdateRecords for this provider.
2076 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2077 if (records == null || records.size() == 0) return;
2078
Victoria Lease09016ab2012-09-16 12:33:15 -07002079 // Fetch coarse location
2080 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002081 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002082 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2083 }
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 // Fetch latest status update time
2086 long newStatusUpdateTime = p.getStatusUpdateTime();
2087
David Christie2ff96af2014-01-30 16:09:37 -08002088 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 Bundle extras = new Bundle();
2090 int status = p.getStatus(extras);
2091
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002093 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002094
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002096 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002098 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002099
Victoria Lease269518e2012-10-29 08:25:39 -07002100 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002101 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002102 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002103 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002104 " (current user: " + mCurrentUserId + ", app: " +
2105 receiver.mPackageName + ")");
2106 }
2107 continue;
2108 }
2109
Nick Pelly4035f5a2012-08-17 14:43:49 -07002110 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2111 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2112 receiver.mPackageName);
2113 continue;
2114 }
2115
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002116 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
2117 receiver.mAllowedResolutionLevel)) {
2118 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2119 receiver.mPackageName);
2120 continue;
2121 }
2122
Victoria Lease09016ab2012-09-16 12:33:15 -07002123 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07002124 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2125 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002126 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002127 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002128 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002129 if (notifyLocation != null) {
2130 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002131 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002132 if (lastLoc == null) {
2133 lastLoc = new Location(notifyLocation);
2134 r.mLastFixBroadcast = lastLoc;
2135 } else {
2136 lastLoc.set(notifyLocation);
2137 }
2138 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2139 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2140 receiverDead = true;
2141 }
Laurent Tu75defb62012-11-01 16:21:52 -07002142 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 }
2144 }
2145
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002146 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002148 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002150 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002152 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002153 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002154 }
2155 }
2156
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002157 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002158 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002159 if (deadUpdateRecords == null) {
2160 deadUpdateRecords = new ArrayList<UpdateRecord>();
2161 }
2162 deadUpdateRecords.add(r);
2163 }
2164 // track dead receivers
2165 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002166 if (deadReceivers == null) {
2167 deadReceivers = new ArrayList<Receiver>();
2168 }
2169 if (!deadReceivers.contains(receiver)) {
2170 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002171 }
2172 }
2173 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002174
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002175 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002177 for (Receiver receiver : deadReceivers) {
2178 removeUpdatesLocked(receiver);
2179 }
2180 }
2181 if (deadUpdateRecords != null) {
2182 for (UpdateRecord r : deadUpdateRecords) {
2183 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002184 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002185 applyRequirementsLocked(provider);
2186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 }
2188
2189 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002190 public LocationWorkerHandler(Looper looper) {
2191 super(looper, null, true);
2192 }
2193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002194 @Override
2195 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002196 switch (msg.what) {
2197 case MSG_LOCATION_CHANGED:
2198 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2199 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201 }
2202 }
2203
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002204 private boolean isMockProvider(String provider) {
2205 synchronized (mLock) {
2206 return mMockProviders.containsKey(provider);
2207 }
2208 }
2209
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002210 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002211 // create a working copy of the incoming Location so that the service can modify it without
2212 // disturbing the caller's copy
2213 Location myLocation = new Location(location);
2214 String provider = myLocation.getProvider();
2215
2216 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2217 // bit if location did not come from a mock provider because passive/fused providers can
2218 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2219 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2220 myLocation.setIsFromMockProvider(true);
2221 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002222
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002223 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002224 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2225 if (!passive) {
2226 // notify passive provider of the new location
2227 mPassiveProvider.updateLocation(myLocation);
2228 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002229 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002231 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233
Mike Lockwoode97ae402010-09-29 15:23:46 -04002234 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2235 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002236 public void onPackageDisappeared(String packageName, int reason) {
2237 // remove all receivers associated with this package name
2238 synchronized (mLock) {
2239 ArrayList<Receiver> deadReceivers = null;
2240
2241 for (Receiver receiver : mReceivers.values()) {
2242 if (receiver.mPackageName.equals(packageName)) {
2243 if (deadReceivers == null) {
2244 deadReceivers = new ArrayList<Receiver>();
2245 }
2246 deadReceivers.add(receiver);
2247 }
2248 }
2249
2250 // perform removal outside of mReceivers loop
2251 if (deadReceivers != null) {
2252 for (Receiver receiver : deadReceivers) {
2253 removeUpdatesLocked(receiver);
2254 }
2255 }
2256 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002257 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002258 };
2259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 // Geocoder
2261
Nick Pellye0fd6932012-07-11 10:26:13 -07002262 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002263 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002264 return mGeocodeProvider != null;
2265 }
2266
Nick Pellye0fd6932012-07-11 10:26:13 -07002267 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002268 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002269 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002270 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002271 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2272 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002273 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002274 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 }
2276
Mike Lockwooda55c3212009-04-15 11:10:11 -04002277
Nick Pellye0fd6932012-07-11 10:26:13 -07002278 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002280 double lowerLeftLatitude, double lowerLeftLongitude,
2281 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002282 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002283
2284 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002285 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2286 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2287 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002289 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290 }
2291
2292 // Mock Providers
2293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294 private void checkMockPermissionsSafe() {
2295 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2296 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2297 if (!allowMocks) {
2298 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2299 }
2300
2301 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
David Christie2ff96af2014-01-30 16:09:37 -08002302 PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
Nick Pellye0fd6932012-07-11 10:26:13 -07002304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 }
2306
Nick Pellye0fd6932012-07-11 10:26:13 -07002307 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002308 public void addTestProvider(String name, ProviderProperties properties) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002309 checkMockPermissionsSafe();
2310
Mike Lockwooda4903f22010-02-17 06:42:23 -05002311 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2312 throw new IllegalArgumentException("Cannot mock the passive location provider");
2313 }
2314
Mike Lockwood86328a92009-10-23 08:38:25 -04002315 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002316 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002317 // remove the real provider if we are replacing GPS or network provider
2318 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002319 || LocationManager.NETWORK_PROVIDER.equals(name)
2320 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002321 LocationProviderInterface p = mProvidersByName.get(name);
2322 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002323 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002324 }
2325 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002326 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002327 updateProvidersLocked();
2328 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002329 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
2331
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002332 private void addTestProviderLocked(String name, ProviderProperties properties) {
2333 if (mProvidersByName.get(name) != null) {
2334 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2335 }
2336 MockProvider provider = new MockProvider(name, this, properties);
2337 addProviderLocked(provider);
2338 mMockProviders.put(name, provider);
2339 mLastLocation.put(name, null);
2340 mLastLocationCoarseInterval.put(name, null);
2341 }
2342
Nick Pellye0fd6932012-07-11 10:26:13 -07002343 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 public void removeTestProvider(String provider) {
2345 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002346 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002347
2348 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002349 // we don't leave anything dangling.
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002350 clearTestProviderEnabled(provider);
2351 clearTestProviderLocation(provider);
2352 clearTestProviderStatus(provider);
2353
You Kima6d0b6f2012-10-28 03:58:44 +09002354 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002355 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002356 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2357 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002358 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002359 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002360
2361 // reinstate real provider if available
2362 LocationProviderInterface realProvider = mRealProviders.get(provider);
2363 if (realProvider != null) {
2364 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002365 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002366 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002367 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002369 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 }
2371 }
2372
Nick Pellye0fd6932012-07-11 10:26:13 -07002373 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 public void setTestProviderLocation(String provider, Location loc) {
2375 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002376 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002377 MockProvider mockProvider = mMockProviders.get(provider);
2378 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002379 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2380 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002381 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2382 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002383 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002384 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 }
2386 }
2387
Nick Pellye0fd6932012-07-11 10:26:13 -07002388 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002389 public void clearTestProviderLocation(String provider) {
2390 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002391 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002392 MockProvider mockProvider = mMockProviders.get(provider);
2393 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2395 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002396 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 }
2398 }
2399
Nick Pellye0fd6932012-07-11 10:26:13 -07002400 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 public void setTestProviderEnabled(String provider, boolean enabled) {
2402 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002403 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002404 MockProvider mockProvider = mMockProviders.get(provider);
2405 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2407 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002408 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002409 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002410 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 mEnabledProviders.add(provider);
2412 mDisabledProviders.remove(provider);
2413 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002414 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 mEnabledProviders.remove(provider);
2416 mDisabledProviders.add(provider);
2417 }
2418 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002419 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 }
2421 }
2422
Nick Pellye0fd6932012-07-11 10:26:13 -07002423 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 public void clearTestProviderEnabled(String provider) {
2425 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002426 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002427 MockProvider mockProvider = mMockProviders.get(provider);
2428 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2430 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002431 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 mEnabledProviders.remove(provider);
2433 mDisabledProviders.remove(provider);
2434 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002435 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 }
2437 }
2438
Nick Pellye0fd6932012-07-11 10:26:13 -07002439 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2441 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002442 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002443 MockProvider mockProvider = mMockProviders.get(provider);
2444 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002445 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2446 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002447 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002448 }
2449 }
2450
Nick Pellye0fd6932012-07-11 10:26:13 -07002451 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 public void clearTestProviderStatus(String provider) {
2453 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002454 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002455 MockProvider mockProvider = mMockProviders.get(provider);
2456 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2458 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002459 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002460 }
2461 }
2462
2463 private void log(String log) {
2464 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002465 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 }
2467 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002468
2469 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2471 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2472 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002473 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 + Binder.getCallingPid()
2475 + ", uid=" + Binder.getCallingUid());
2476 return;
2477 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002478
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002479 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002482 for (Receiver receiver : mReceivers.values()) {
2483 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002484 }
David Christie2ff96af2014-01-30 16:09:37 -08002485 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002486 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2487 pw.println(" " + entry.getKey() + ":");
2488 for (UpdateRecord record : entry.getValue()) {
2489 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 }
2491 }
David Christie2ff96af2014-01-30 16:09:37 -08002492 pw.println(" Historical Records by Provider:");
2493 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2494 : mRequestStatistics.statistics.entrySet()) {
2495 PackageProviderKey key = entry.getKey();
2496 PackageStatistics stats = entry.getValue();
2497 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2498 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002500 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2501 String provider = entry.getKey();
2502 Location location = entry.getValue();
2503 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002505
David Christie1b9b7b12013-04-15 15:31:11 -07002506 pw.println(" Last Known Locations Coarse Intervals:");
2507 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2508 String provider = entry.getKey();
2509 Location location = entry.getValue();
2510 pw.println(" " + provider + ": " + location);
2511 }
2512
Nick Pellye0fd6932012-07-11 10:26:13 -07002513 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 if (mEnabledProviders.size() > 0) {
2516 pw.println(" Enabled Providers:");
2517 for (String i : mEnabledProviders) {
2518 pw.println(" " + i);
2519 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002520
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 }
2522 if (mDisabledProviders.size() > 0) {
2523 pw.println(" Disabled Providers:");
2524 for (String i : mDisabledProviders) {
2525 pw.println(" " + i);
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002528 pw.append(" ");
2529 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 if (mMockProviders.size() > 0) {
2531 pw.println(" Mock Providers:");
2532 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002533 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
2535 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002536
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002537 pw.append(" fudger: ");
2538 mLocationFudger.dump(fd, pw, args);
2539
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002540 if (args.length > 0 && "short".equals(args[0])) {
2541 return;
2542 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002543 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002544 pw.print(provider.getName() + " Internal State");
2545 if (provider instanceof LocationProviderProxy) {
2546 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2547 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002548 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002549 pw.println(":");
2550 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002551 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002552 }
2553 }
2554}