blob: 5eee3962fc47e87e76096047e4ef960035ca08b6 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Dianne Hackborna06de0f2012-12-11 16:34:47 -080019import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070021import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080022import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070025import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070026import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050027import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.pm.PackageManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070029import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050030import android.content.pm.ResolveInfo;
31import android.content.pm.Signature;
Amith Yamasanib27528d2014-06-05 15:02:10 -070032import android.content.pm.UserInfo;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050033import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070034import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070036import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050037import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070038import android.location.Geofence;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.location.IGpsStatusListener;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -040040import android.location.IGpsStatusProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.location.ILocationListener;
42import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040043import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.location.Location;
45import android.location.LocationManager;
46import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070047import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Binder;
49import android.os.Bundle;
50import android.os.Handler;
51import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070052import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Message;
54import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070055import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070057import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070058import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070059import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070060import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080063import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070064
Mike Lockwoode97ae402010-09-29 15:23:46 -040065import com.android.internal.content.PackageMonitor;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070066import com.android.internal.location.ProviderProperties;
67import com.android.internal.location.ProviderRequest;
Dianne Hackborn8d044e82013-04-30 17:24:15 -070068import com.android.internal.os.BackgroundThread;
destradaa1af4b022013-07-12 15:43:36 -070069import com.android.server.location.FlpHardwareProvider;
70import com.android.server.location.FusedProxy;
Mike Lockwood43e33f22010-03-26 10:41:48 -040071import com.android.server.location.GeocoderProxy;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -070072import com.android.server.location.GeofenceProxy;
Nick Pellye0fd6932012-07-11 10:26:13 -070073import com.android.server.location.GeofenceManager;
Mike Lockwood43e33f22010-03-26 10:41:48 -040074import com.android.server.location.GpsLocationProvider;
Nick Pelly4035f5a2012-08-17 14:43:49 -070075import com.android.server.location.LocationBlacklist;
Nick Pelly74fa7ea2012-08-13 19:36:38 -070076import com.android.server.location.LocationFudger;
Mike Lockwood43e33f22010-03-26 10:41:48 -040077import com.android.server.location.LocationProviderInterface;
78import com.android.server.location.LocationProviderProxy;
David Christie2ff96af2014-01-30 16:09:37 -080079import com.android.server.location.LocationRequestStatistics;
80import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
81import com.android.server.location.LocationRequestStatistics.PackageStatistics;
Mike Lockwood43e33f22010-03-26 10:41:48 -040082import com.android.server.location.MockProvider;
83import com.android.server.location.PassiveProvider;
84
85import java.io.FileDescriptor;
86import java.io.PrintWriter;
87import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070088import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040089import java.util.HashMap;
90import java.util.HashSet;
91import java.util.List;
92import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -040093import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
95/**
96 * The service class that manages LocationProviders and issues location
97 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098 */
Victoria Lease5cd731a2012-12-19 15:04:21 -080099public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800101 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700102
103 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104
Victoria Lease37425c32012-10-16 16:08:48 -0700105 // Location resolution level: no location data whatsoever
106 private static final int RESOLUTION_LEVEL_NONE = 0;
107 // Location resolution level: coarse location data only
108 private static final int RESOLUTION_LEVEL_COARSE = 1;
109 // Location resolution level: fine location data
110 private static final int RESOLUTION_LEVEL_FINE = 2;
111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700113 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700115 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400116 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700117 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
118
119 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700120 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700121 private static final String FUSED_LOCATION_SERVICE_ACTION =
122 "com.android.location.service.FusedLocationProvider";
123
124 private static final int MSG_LOCATION_CHANGED = 1;
125
David Christie1b9b7b12013-04-15 15:31:11 -0700126 private static final long NANOS_PER_MILLI = 1000000L;
127
David Christie0b837452013-07-29 16:02:13 -0700128 // The maximum interval a location request can have and still be considered "high power".
129 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
130
Nick Pellyf1be6862012-05-15 10:53:42 -0700131 // Location Providers may sometimes deliver location updates
132 // slightly faster that requested - provide grace period so
133 // we don't unnecessarily filter events that are otherwise on
134 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700135 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700136
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700137 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
138
139 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800140 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700141
142 // used internally for synchronization
143 private final Object mLock = new Object();
144
Victoria Lease5cd731a2012-12-19 15:04:21 -0800145 // --- fields below are final after systemReady() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700146 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700147 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700148 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700149 private PowerManager mPowerManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700150 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700151 private GeocoderProxy mGeocodeProvider;
152 private IGpsStatusProvider mGpsStatusProvider;
153 private INetInitiatedListener mNetInitiatedListener;
154 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700155 private PassiveProvider mPassiveProvider; // track passive provider for special cases
156 private LocationBlacklist mBlacklist;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700157
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700158 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 // Set of providers that are explicitly enabled
160 private final Set<String> mEnabledProviders = new HashSet<String>();
161
162 // Set of providers that are explicitly disabled
163 private final Set<String> mDisabledProviders = new HashSet<String>();
164
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700165 // Mock (test) providers
166 private final HashMap<String, MockProvider> mMockProviders =
167 new HashMap<String, MockProvider>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700169 // all receivers
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400170 private final HashMap<Object, Receiver> mReceivers = new HashMap<Object, Receiver>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500173 private final ArrayList<LocationProviderInterface> mProviders =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700174 new ArrayList<LocationProviderInterface>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400175
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700176 // real providers, saved here when mocked out
177 private final HashMap<String, LocationProviderInterface> mRealProviders =
178 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700180 // mapping from provider name to provider
181 private final HashMap<String, LocationProviderInterface> mProvidersByName =
182 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700184 // mapping from provider name to all its UpdateRecords
185 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
186 new HashMap<String, ArrayList<UpdateRecord>>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700187
David Christie2ff96af2014-01-30 16:09:37 -0800188 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
189
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700190 // mapping from provider name to last known location
191 private final HashMap<String, Location> mLastLocation = new HashMap<String, Location>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
David Christie1b9b7b12013-04-15 15:31:11 -0700193 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
194 // locations stored here are not fudged for coarse permissions.
195 private final HashMap<String, Location> mLastLocationCoarseInterval =
196 new HashMap<String, Location>();
197
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700198 // all providers that operate over proxy, for authorizing incoming location
199 private final ArrayList<LocationProviderProxy> mProxyProviders =
200 new ArrayList<LocationProviderProxy>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Victoria Lease38389b62012-09-30 11:44:22 -0700202 // current active user on the device - other users are denied location data
203 private int mCurrentUserId = UserHandle.USER_OWNER;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700204 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_OWNER };
Victoria Lease38389b62012-09-30 11:44:22 -0700205
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700206 public LocationManagerService(Context context) {
207 super();
208 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800209 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800210
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700211 if (D) Log.d(TAG, "Constructed");
212
213 // most startup is deferred until systemReady()
214 }
215
Svetoslav Ganova0027152013-06-25 14:59:53 -0700216 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700217 synchronized (mLock) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800218 if (D) Log.d(TAG, "systemReady()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700219
Victoria Lease5cd731a2012-12-19 15:04:21 -0800220 // fetch package manager
221 mPackageManager = mContext.getPackageManager();
222
Victoria Lease0aa28602013-05-29 15:28:26 -0700223 // fetch power manager
224 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800225
226 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700227 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800228
229 // prepare mLocationHandler's dependents
230 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
231 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
232 mBlacklist.init();
233 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
234
Dianne Hackbornc2293022013-02-06 23:14:49 -0800235 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700236 AppOpsManager.OnOpChangedListener callback
237 = new AppOpsManager.OnOpChangedInternalListener() {
238 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800239 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700240 for (Receiver receiver : mReceivers.values()) {
241 receiver.updateMonitoring(true);
242 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800243 applyAllProviderRequirementsLocked();
244 }
245 }
246 };
247 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
248
Amith Yamasanib27528d2014-06-05 15:02:10 -0700249 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
250 updateUserProfiles(mCurrentUserId);
251
Victoria Lease5cd731a2012-12-19 15:04:21 -0800252 // prepare providers
253 loadProvidersLocked();
254 updateProvidersLocked();
255 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700256
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700257 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700258 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700259 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700260 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800261 @Override
262 public void onChange(boolean selfChange) {
263 synchronized (mLock) {
264 updateProvidersLocked();
265 }
266 }
267 }, UserHandle.USER_ALL);
268 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700269
Victoria Lease38389b62012-09-30 11:44:22 -0700270 // listen for user change
271 IntentFilter intentFilter = new IntentFilter();
272 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700273 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
274 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Victoria Lease38389b62012-09-30 11:44:22 -0700275
276 mContext.registerReceiverAsUser(new BroadcastReceiver() {
277 @Override
278 public void onReceive(Context context, Intent intent) {
279 String action = intent.getAction();
280 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
281 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700282 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
283 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
284 updateUserProfiles(mCurrentUserId);
Victoria Lease38389b62012-09-30 11:44:22 -0700285 }
286 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800287 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700288 }
289
Amith Yamasanib27528d2014-06-05 15:02:10 -0700290 /**
291 * Makes a list of userids that are related to the current user. This is
292 * relevant when using managed profiles. Otherwise the list only contains
293 * the current user.
294 *
295 * @param currentUserId the current user, who might have an alter-ego.
296 */
297 void updateUserProfiles(int currentUserId) {
298 List<UserInfo> profiles = mUserManager.getProfiles(currentUserId);
299 synchronized (mLock) {
300 mCurrentUserProfiles = new int[profiles.size()];
301 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
302 mCurrentUserProfiles[i] = profiles.get(i).id;
303 }
304 }
305 }
306
307 /**
308 * Checks if the specified userId matches any of the current foreground
309 * users stored in mCurrentUserProfiles.
310 */
311 private boolean isCurrentProfile(int userId) {
312 synchronized (mLock) {
313 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
314 if (mCurrentUserProfiles[i] == userId) {
315 return true;
316 }
317 }
318 return false;
319 }
320 }
321
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500322 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
323 PackageManager pm = mContext.getPackageManager();
324 String systemPackageName = mContext.getPackageName();
325 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
326
327 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
328 new Intent(FUSED_LOCATION_SERVICE_ACTION),
329 PackageManager.GET_META_DATA, mCurrentUserId);
330 for (ResolveInfo rInfo : rInfos) {
331 String packageName = rInfo.serviceInfo.packageName;
332
333 // Check that the signature is in the list of supported sigs. If it's not in
334 // this list the standard provider binding logic won't bind to it.
335 try {
336 PackageInfo pInfo;
337 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
338 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
339 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
340 ", but has wrong signature, ignoring");
341 continue;
342 }
343 } catch (NameNotFoundException e) {
344 Log.e(TAG, "missing package: " + packageName);
345 continue;
346 }
347
348 // Get the version info
349 if (rInfo.serviceInfo.metaData == null) {
350 Log.w(TAG, "Found fused provider without metadata: " + packageName);
351 continue;
352 }
353
354 int version = rInfo.serviceInfo.metaData.getInt(
355 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
356 if (version == 0) {
357 // This should be the fallback fused location provider.
358
359 // Make sure it's in the system partition.
360 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
361 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
362 continue;
363 }
364
365 // Check that the fallback is signed the same as the OS
366 // as a proxy for coreApp="true"
367 if (pm.checkSignatures(systemPackageName, packageName)
368 != PackageManager.SIGNATURE_MATCH) {
369 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
370 + packageName);
371 continue;
372 }
373
374 // Found a valid fallback.
375 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
376 return;
377 } else {
378 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
379 }
380 }
381
382 throw new IllegalStateException("Unable to find a fused location provider that is in the "
383 + "system partition with version 0 and signed with the platform certificate. "
384 + "Such a package is needed to provide a default fused location provider in the "
385 + "event that no other fused location provider has been installed or is currently "
386 + "available. For example, coreOnly boot mode when decrypting the data "
387 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
388 }
389
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700390 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700391 // create a passive location provider, which is always enabled
392 PassiveProvider passiveProvider = new PassiveProvider(this);
393 addProviderLocked(passiveProvider);
394 mEnabledProviders.add(passiveProvider.getName());
395 mPassiveProvider = passiveProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700396 // Create a gps location provider
397 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
398 mLocationHandler.getLooper());
Victoria Lease5c24fd02012-10-01 11:00:50 -0700399
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700400 if (GpsLocationProvider.isSupported()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700401 mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
402 mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
403 addProviderLocked(gpsProvider);
404 mRealProviders.put(LocationManager.GPS_PROVIDER, gpsProvider);
405 }
406
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700407 /*
408 Load package name(s) containing location provider support.
409 These packages can contain services implementing location providers:
410 Geocoder Provider, Network Location Provider, and
411 Fused Location Provider. They will each be searched for
412 service components implementing these providers.
413 The location framework also has support for installation
414 of new location providers at run-time. The new package does not
415 have to be explicitly listed here, however it must have a signature
416 that matches the signature of at least one package on this list.
417 */
418 Resources resources = mContext.getResources();
419 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500420 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700421 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500422 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
423 Arrays.toString(pkgs));
424 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
425
426 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700427
428 // bind to network provider
429 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
430 mContext,
431 LocationManager.NETWORK_PROVIDER,
432 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700433 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
434 com.android.internal.R.string.config_networkLocationProviderPackageName,
435 com.android.internal.R.array.config_locationProviderPackageNames,
436 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700437 if (networkProvider != null) {
438 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
439 mProxyProviders.add(networkProvider);
440 addProviderLocked(networkProvider);
441 } else {
442 Slog.w(TAG, "no network location provider found");
443 }
444
445 // bind to fused provider
446 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
447 mContext,
448 LocationManager.FUSED_PROVIDER,
449 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700450 com.android.internal.R.bool.config_enableFusedLocationOverlay,
451 com.android.internal.R.string.config_fusedLocationProviderPackageName,
452 com.android.internal.R.array.config_locationProviderPackageNames,
453 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700454 if (fusedLocationProvider != null) {
455 addProviderLocked(fusedLocationProvider);
456 mProxyProviders.add(fusedLocationProvider);
457 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700458 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700459 } else {
460 Slog.e(TAG, "no fused location provider found",
461 new IllegalStateException("Location service needs a fused location provider"));
462 }
463
464 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700465 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
466 com.android.internal.R.bool.config_enableGeocoderOverlay,
467 com.android.internal.R.string.config_geocoderProviderPackageName,
468 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800469 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700470 if (mGeocodeProvider == null) {
471 Slog.e(TAG, "no geocoder provider found");
472 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700473
destradaacfbdcd22014-04-30 11:29:11 -0700474 // bind to fused provider if supported
destradaa5ce66d82014-05-28 18:24:08 -0700475 if (FlpHardwareProvider.isSupported()) {
476 FlpHardwareProvider flpHardwareProvider =
477 FlpHardwareProvider.getInstance(mContext);
destradaacfbdcd22014-04-30 11:29:11 -0700478 FusedProxy fusedProxy = FusedProxy.createAndBind(
479 mContext,
480 mLocationHandler,
481 flpHardwareProvider.getLocationHardware(),
482 com.android.internal.R.bool.config_enableFusedLocationOverlay,
483 com.android.internal.R.string.config_fusedLocationProviderPackageName,
484 com.android.internal.R.array.config_locationProviderPackageNames);
485 if(fusedProxy == null) {
486 Slog.e(TAG, "Unable to bind FusedProxy.");
487 }
destradaa0682809a2013-08-12 18:50:30 -0700488
destradaacfbdcd22014-04-30 11:29:11 -0700489 // bind to geofence provider
490 GeofenceProxy provider = GeofenceProxy.createAndBind(mContext,
491 com.android.internal.R.bool.config_enableGeofenceOverlay,
492 com.android.internal.R.string.config_geofenceProviderPackageName,
493 com.android.internal.R.array.config_locationProviderPackageNames,
494 mLocationHandler,
495 gpsProvider.getGpsGeofenceProxy(),
496 flpHardwareProvider.getGeofenceHardware());
497 if (provider == null) {
498 Slog.e(TAG, "Unable to bind FLP Geofence proxy.");
499 }
500 } else {
501 Slog.e(TAG, "FLP HAL not supported.");
destradaa0682809a2013-08-12 18:50:30 -0700502 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900503
504 String[] testProviderStrings = resources.getStringArray(
505 com.android.internal.R.array.config_testLocationProviders);
506 for (String testProviderString : testProviderStrings) {
507 String fragments[] = testProviderString.split(",");
508 String name = fragments[0].trim();
509 if (mProvidersByName.get(name) != null) {
510 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
511 }
512 ProviderProperties properties = new ProviderProperties(
513 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
514 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
515 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
516 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
517 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
518 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
519 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
520 Integer.parseInt(fragments[8]) /* powerRequirement */,
521 Integer.parseInt(fragments[9]) /* accuracy */);
522 addTestProviderLocked(name, properties);
523 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700524 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800526 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700527 * Called when the device's active user changes.
528 * @param userId the new active user's UserId
529 */
530 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800531 if (mCurrentUserId == userId) {
532 return;
533 }
Victoria Lease83762d22012-10-03 13:51:17 -0700534 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800535 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700536 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700537 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700538 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700539 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700540 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700541 }
Victoria Lease38389b62012-09-30 11:44:22 -0700542 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700543 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700544 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700545 }
546 }
547
548 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800549 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
550 * location updates.
551 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700552 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700553 final int mUid; // uid of receiver
554 final int mPid; // pid of receiver
555 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700556 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 final ILocationListener mListener;
559 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700560 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700561 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800562 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700563
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400564 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700565
David Christie0b837452013-07-29 16:02:13 -0700566 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700567 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700568 // True if app ops has started monitoring this receiver for high power (gps) locations.
569 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700570 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700571 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800572
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700573 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700574 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800576 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700577 if (listener != null) {
578 mKey = listener.asBinder();
579 } else {
580 mKey = intent;
581 }
Victoria Lease37425c32012-10-16 16:08:48 -0700582 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700583 mUid = uid;
584 mPid = pid;
585 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700586 if (workSource != null && workSource.size() <= 0) {
587 workSource = null;
588 }
589 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700590 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700591
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700592 updateMonitoring(true);
593
Victoria Lease0aa28602013-05-29 15:28:26 -0700594 // construct/configure wakelock
595 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700596 if (workSource == null) {
597 workSource = new WorkSource(mUid, mPackageName);
598 }
599 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800600 }
601
602 @Override
603 public boolean equals(Object otherObj) {
604 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700605 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800606 }
607 return false;
608 }
609
610 @Override
611 public int hashCode() {
612 return mKey.hashCode();
613 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800615 @Override
616 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700617 StringBuilder s = new StringBuilder();
618 s.append("Reciever[");
619 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700621 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800622 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700623 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800624 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700625 for (String p : mUpdateRecords.keySet()) {
626 s.append(" ").append(mUpdateRecords.get(p).toString());
627 }
628 s.append("]");
629 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800630 }
631
David Christie15b31912013-08-13 15:54:32 -0700632 /**
633 * Update AppOp monitoring for this receiver.
634 *
635 * @param allow If true receiver is currently active, if false it's been removed.
636 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700637 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700638 if (mHideFromAppOps) {
639 return;
640 }
641
David Christie15b31912013-08-13 15:54:32 -0700642 boolean requestingLocation = false;
643 boolean requestingHighPowerLocation = false;
644 if (allow) {
645 // See if receiver has any enabled update records. Also note if any update records
646 // are high power (has a high power provider with an interval under a threshold).
647 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
648 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
649 requestingLocation = true;
650 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800651 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700652 ProviderProperties properties = locationProvider != null
653 ? locationProvider.getProperties() : null;
654 if (properties != null
655 && properties.mPowerRequirement == Criteria.POWER_HIGH
656 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
657 requestingHighPowerLocation = true;
658 break;
659 }
660 }
661 }
662 }
663
David Christie0b837452013-07-29 16:02:13 -0700664 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700665 mOpMonitoring = updateMonitoring(
666 requestingLocation,
667 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700668 AppOpsManager.OP_MONITOR_LOCATION);
669
670 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700671 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700672 mOpHighPowerMonitoring = updateMonitoring(
673 requestingHighPowerLocation,
674 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700675 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700676 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700677 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700678 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
679 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
680 }
David Christie0b837452013-07-29 16:02:13 -0700681 }
682
683 /**
684 * Update AppOps monitoring for a single location request and op type.
685 *
686 * @param allowMonitoring True if monitoring is allowed for this request/op.
687 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
688 * @param op AppOps code for the op to update.
689 * @return True if monitoring is on for this request/op after updating.
690 */
691 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
692 int op) {
693 if (!currentlyMonitoring) {
694 if (allowMonitoring) {
695 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
696 == AppOpsManager.MODE_ALLOWED;
697 }
698 } else {
699 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
700 != AppOpsManager.MODE_ALLOWED) {
701 mAppOps.finishOp(op, mUid, mPackageName);
702 return false;
703 }
704 }
705
706 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700707 }
708
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800709 public boolean isListener() {
710 return mListener != null;
711 }
712
713 public boolean isPendingIntent() {
714 return mPendingIntent != null;
715 }
716
717 public ILocationListener getListener() {
718 if (mListener != null) {
719 return mListener;
720 }
721 throw new IllegalStateException("Request for non-existent listener");
722 }
723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
725 if (mListener != null) {
726 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700727 synchronized (this) {
728 // synchronize to ensure incrementPendingBroadcastsLocked()
729 // is called before decrementPendingBroadcasts()
730 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700731 // call this after broadcasting so we do not increment
732 // if we throw an exeption.
733 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700734 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 } catch (RemoteException e) {
736 return false;
737 }
738 } else {
739 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800740 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
742 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700743 synchronized (this) {
744 // synchronize to ensure incrementPendingBroadcastsLocked()
745 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700746 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700747 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700748 // call this after broadcasting so we do not increment
749 // if we throw an exeption.
750 incrementPendingBroadcastsLocked();
751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 } catch (PendingIntent.CanceledException e) {
753 return false;
754 }
755 }
756 return true;
757 }
758
759 public boolean callLocationChangedLocked(Location location) {
760 if (mListener != null) {
761 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700762 synchronized (this) {
763 // synchronize to ensure incrementPendingBroadcastsLocked()
764 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800765 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700766 // call this after broadcasting so we do not increment
767 // if we throw an exeption.
768 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770 } catch (RemoteException e) {
771 return false;
772 }
773 } else {
774 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800775 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800776 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700777 synchronized (this) {
778 // synchronize to ensure incrementPendingBroadcastsLocked()
779 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700780 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700781 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700782 // call this after broadcasting so we do not increment
783 // if we throw an exeption.
784 incrementPendingBroadcastsLocked();
785 }
786 } catch (PendingIntent.CanceledException e) {
787 return false;
788 }
789 }
790 return true;
791 }
792
793 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700794 // First update AppOp monitoring.
795 // An app may get/lose location access as providers are enabled/disabled.
796 updateMonitoring(true);
797
Mike Lockwood48f17512009-04-23 09:12:08 -0700798 if (mListener != null) {
799 try {
800 synchronized (this) {
801 // synchronize to ensure incrementPendingBroadcastsLocked()
802 // is called before decrementPendingBroadcasts()
803 if (enabled) {
804 mListener.onProviderEnabled(provider);
805 } else {
806 mListener.onProviderDisabled(provider);
807 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700808 // call this after broadcasting so we do not increment
809 // if we throw an exeption.
810 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700811 }
812 } catch (RemoteException e) {
813 return false;
814 }
815 } else {
816 Intent providerIntent = new Intent();
817 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
818 try {
819 synchronized (this) {
820 // synchronize to ensure incrementPendingBroadcastsLocked()
821 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700822 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700823 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700824 // call this after broadcasting so we do not increment
825 // if we throw an exeption.
826 incrementPendingBroadcastsLocked();
827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828 } catch (PendingIntent.CanceledException e) {
829 return false;
830 }
831 }
832 return true;
833 }
834
Nick Pellyf1be6862012-05-15 10:53:42 -0700835 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800836 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700837 if (D) Log.d(TAG, "Location listener died");
838
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400839 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840 removeUpdatesLocked(this);
841 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700842 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700843 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700844 }
845 }
846
Nick Pellye0fd6932012-07-11 10:26:13 -0700847 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700848 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
849 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400850 synchronized (this) {
851 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700852 }
853 }
854
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400855 // this must be called while synchronized by caller in a synchronized block
856 // containing the sending of the broadcaset
857 private void incrementPendingBroadcastsLocked() {
858 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700859 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400860 }
861 }
862
863 private void decrementPendingBroadcastsLocked() {
864 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700865 if (mWakeLock.isHeld()) {
866 mWakeLock.release();
867 }
868 }
869 }
870
871 public void clearPendingBroadcastsLocked() {
872 if (mPendingBroadcasts > 0) {
873 mPendingBroadcasts = 0;
874 if (mWakeLock.isHeld()) {
875 mWakeLock.release();
876 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700877 }
878 }
879 }
880
Nick Pellye0fd6932012-07-11 10:26:13 -0700881 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700882 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700883 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -0400884 //the receiver list if it is not found. If it is not found then the
885 //LocationListener was removed when it had a pending broadcast and should
886 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700887 synchronized (mLock) {
888 IBinder binder = listener.asBinder();
889 Receiver receiver = mReceivers.get(binder);
890 if (receiver != null) {
891 synchronized (receiver) {
892 // so wakelock calls will succeed
893 long identity = Binder.clearCallingIdentity();
894 receiver.decrementPendingBroadcastsLocked();
895 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -0800896 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700897 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800898 }
899 }
900
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700901 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400902 mProviders.add(provider);
903 mProvidersByName.put(provider.getName(), provider);
904 }
905
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700906 private void removeProviderLocked(LocationProviderInterface provider) {
907 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400908 mProviders.remove(provider);
909 mProvidersByName.remove(provider.getName());
910 }
911
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800912 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800913 * Returns "true" if access to the specified location provider is allowed by the current
914 * user's settings. Access to all location providers is forbidden to non-location-provider
915 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800916 *
917 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800918 * @return
919 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800920 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 if (mEnabledProviders.contains(provider)) {
922 return true;
923 }
924 if (mDisabledProviders.contains(provider)) {
925 return false;
926 }
927 // Use system settings
928 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929
Victoria Leaseb711d572012-10-02 13:14:11 -0700930 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700933 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800934 * Returns "true" if access to the specified location provider is allowed by the specified
935 * user's settings. Access to all location providers is forbidden to non-location-provider
936 * processes belonging to background users.
937 *
938 * @param provider the name of the location provider
939 * @param uid the requestor's UID
940 * @return
941 */
942 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700943 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800944 return false;
945 }
946 return isAllowedByCurrentUserSettingsLocked(provider);
947 }
948
949 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700950 * Returns the permission string associated with the specified resolution level.
951 *
952 * @param resolutionLevel the resolution level
953 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700954 */
Victoria Lease37425c32012-10-16 16:08:48 -0700955 private String getResolutionPermission(int resolutionLevel) {
956 switch (resolutionLevel) {
957 case RESOLUTION_LEVEL_FINE:
958 return android.Manifest.permission.ACCESS_FINE_LOCATION;
959 case RESOLUTION_LEVEL_COARSE:
960 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
961 default:
962 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700964 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700965
Victoria Leaseda479c52012-10-15 15:24:16 -0700966 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700967 * Returns the resolution level allowed to the given PID/UID pair.
968 *
969 * @param pid the PID
970 * @param uid the UID
971 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -0700972 */
Victoria Lease37425c32012-10-16 16:08:48 -0700973 private int getAllowedResolutionLevel(int pid, int uid) {
974 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
975 pid, uid) == PackageManager.PERMISSION_GRANTED) {
976 return RESOLUTION_LEVEL_FINE;
977 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
978 pid, uid) == PackageManager.PERMISSION_GRANTED) {
979 return RESOLUTION_LEVEL_COARSE;
980 } else {
981 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -0700982 }
Victoria Lease4fab68b2012-09-13 13:20:59 -0700983 }
984
985 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700986 * Returns the resolution level allowed to the caller
987 *
988 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -0700989 */
Victoria Lease37425c32012-10-16 16:08:48 -0700990 private int getCallerAllowedResolutionLevel() {
991 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
992 }
993
994 /**
995 * Throw SecurityException if specified resolution level is insufficient to use geofences.
996 *
997 * @param allowedResolutionLevel resolution level allowed to caller
998 */
999 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1000 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001001 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001003 }
1004
Victoria Lease37425c32012-10-16 16:08:48 -07001005 /**
1006 * Return the minimum resolution level required to use the specified location provider.
1007 *
1008 * @param provider the name of the location provider
1009 * @return minimum resolution level required for provider
1010 */
1011 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001012 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1013 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1014 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001015 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001016 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1017 LocationManager.FUSED_PROVIDER.equals(provider)) {
1018 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001019 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001020 } else {
1021 // mock providers
1022 LocationProviderInterface lp = mMockProviders.get(provider);
1023 if (lp != null) {
1024 ProviderProperties properties = lp.getProperties();
1025 if (properties != null) {
1026 if (properties.mRequiresSatellite) {
1027 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001028 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001029 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1030 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001031 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001032 }
1033 }
1034 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001035 }
Victoria Lease37425c32012-10-16 16:08:48 -07001036 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001037 }
1038
Victoria Lease37425c32012-10-16 16:08:48 -07001039 /**
1040 * Throw SecurityException if specified resolution level is insufficient to use the named
1041 * location provider.
1042 *
1043 * @param allowedResolutionLevel resolution level allowed to caller
1044 * @param providerName the name of the location provider
1045 */
1046 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1047 String providerName) {
1048 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1049 if (allowedResolutionLevel < requiredResolutionLevel) {
1050 switch (requiredResolutionLevel) {
1051 case RESOLUTION_LEVEL_FINE:
1052 throw new SecurityException("\"" + providerName + "\" location provider " +
1053 "requires ACCESS_FINE_LOCATION permission.");
1054 case RESOLUTION_LEVEL_COARSE:
1055 throw new SecurityException("\"" + providerName + "\" location provider " +
1056 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1057 default:
1058 throw new SecurityException("Insufficient permission for \"" + providerName +
1059 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001060 }
1061 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001062 }
1063
David Christie82edc9b2013-07-19 11:31:42 -07001064 /**
1065 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1066 * for battery).
1067 */
David Christie40e57822013-07-30 11:36:48 -07001068 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001069 mContext.enforceCallingOrSelfPermission(
1070 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1071 }
1072
David Christie40e57822013-07-30 11:36:48 -07001073 private void checkUpdateAppOpsAllowed() {
1074 mContext.enforceCallingOrSelfPermission(
1075 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1076 }
1077
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001078 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001079 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1080 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001081 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001082 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001083 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001084 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001085 }
1086 return -1;
1087 }
1088
1089 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
1090 int op = resolutionLevelToOp(allowedResolutionLevel);
1091 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001092 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1093 return false;
1094 }
1095 }
1096 return true;
1097 }
1098
1099 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001100 int op = resolutionLevelToOp(allowedResolutionLevel);
1101 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001102 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1103 return false;
1104 }
1105 }
1106 return true;
1107 }
1108
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001109 /**
1110 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001111 * fused, also including ones that are not permitted to
1112 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001113 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001114 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001115 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001116 ArrayList<String> out;
1117 synchronized (mLock) {
1118 out = new ArrayList<String>(mProviders.size());
1119 for (LocationProviderInterface provider : mProviders) {
1120 String name = provider.getName();
1121 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001122 continue;
1123 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 out.add(name);
1125 }
1126 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001127
1128 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 return out;
1130 }
1131
Mike Lockwood03ca2162010-04-01 08:10:09 -07001132 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001133 * Return all providers by name, that match criteria and are optionally
1134 * enabled.
1135 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001136 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001137 @Override
1138 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001139 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001140 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001141 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -07001142 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001143 try {
1144 synchronized (mLock) {
1145 out = new ArrayList<String>(mProviders.size());
1146 for (LocationProviderInterface provider : mProviders) {
1147 String name = provider.getName();
1148 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001149 continue;
1150 }
Victoria Lease37425c32012-10-16 16:08:48 -07001151 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001152 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001153 continue;
1154 }
1155 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1156 name, provider.getProperties(), criteria)) {
1157 continue;
1158 }
1159 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001160 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001161 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001162 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001163 } finally {
1164 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001165 }
1166
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001167 if (D) Log.d(TAG, "getProviders()=" + out);
1168 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001169 }
1170
1171 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001172 * Return the name of the best provider given a Criteria object.
1173 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001174 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001175 * has been deprecated as well. So this method now uses
1176 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001177 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001178 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001179 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001180 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001181
1182 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001183 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001184 result = pickBest(providers);
1185 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1186 return result;
1187 }
1188 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001189 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001190 result = pickBest(providers);
1191 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1192 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001193 }
1194
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001195 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001196 return null;
1197 }
1198
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001199 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001200 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001201 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001202 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1203 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001204 } else {
1205 return providers.get(0);
1206 }
1207 }
1208
Nick Pellye0fd6932012-07-11 10:26:13 -07001209 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001210 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1211 LocationProviderInterface p = mProvidersByName.get(provider);
1212 if (p == null) {
1213 throw new IllegalArgumentException("provider=" + provider);
1214 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001215
1216 boolean result = LocationProvider.propertiesMeetCriteria(
1217 p.getName(), p.getProperties(), criteria);
1218 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1219 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001220 }
1221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001223 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001224 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001225 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 boolean isEnabled = p.isEnabled();
1227 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001228 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001230 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001231 // If any provider has been disabled, clear all last locations for all providers.
1232 // This is to be on the safe side in case a provider has location derived from
1233 // this disabled provider.
1234 mLastLocation.clear();
1235 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001236 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001237 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001238 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001239 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001241 }
1242 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001243 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1244 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001245 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1246 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 }
1248 }
1249
Amith Yamasanib27528d2014-06-05 15:02:10 -07001250 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 int listeners = 0;
1252
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001253 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001254 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255
1256 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1259 if (records != null) {
1260 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001261 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 UpdateRecord record = records.get(i);
Amith Yamasanib27528d2014-06-05 15:02:10 -07001263 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001264 // Sends a notification message to the receiver
1265 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1266 if (deadReceivers == null) {
1267 deadReceivers = new ArrayList<Receiver>();
1268 }
1269 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001271 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
1274 }
1275
1276 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001277 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 removeUpdatesLocked(deadReceivers.get(i));
1279 }
1280 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001281
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 if (enabled) {
1283 p.enable();
1284 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001285 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 }
1287 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 }
1291
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001292 private void applyRequirementsLocked(String provider) {
1293 LocationProviderInterface p = mProvidersByName.get(provider);
1294 if (p == null) return;
1295
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001297 WorkSource worksource = new WorkSource();
1298 ProviderRequest providerRequest = new ProviderRequest();
1299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001301 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001302 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001303 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1304 record.mReceiver.mAllowedResolutionLevel)) {
1305 LocationRequest locationRequest = record.mRequest;
1306 providerRequest.locationRequests.add(locationRequest);
1307 if (locationRequest.getInterval() < providerRequest.interval) {
1308 providerRequest.reportLocation = true;
1309 providerRequest.interval = locationRequest.getInterval();
1310 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001311 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001312 }
1313 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001314
1315 if (providerRequest.reportLocation) {
1316 // calculate who to blame for power
1317 // This is somewhat arbitrary. We pick a threshold interval
1318 // that is slightly higher that the minimum interval, and
1319 // spread the blame across all applications with a request
1320 // under that threshold.
1321 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1322 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001323 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001324 LocationRequest locationRequest = record.mRequest;
1325 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001326 if (record.mReceiver.mWorkSource != null
1327 && record.mReceiver.mWorkSource.size() > 0
1328 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001329 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001330 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001331 worksource.add(record.mReceiver.mWorkSource);
1332 } else {
1333 // Assign blame to caller.
1334 worksource.add(
1335 record.mReceiver.mUid,
1336 record.mReceiver.mPackageName);
1337 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001338 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001339 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001340 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 }
1342 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001343
1344 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1345 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
1347
1348 private class UpdateRecord {
1349 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001350 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001352 Location mLastFixBroadcast;
1353 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354
1355 /**
1356 * Note: must be constructed with lock held.
1357 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001358 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001360 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362
1363 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1364 if (records == null) {
1365 records = new ArrayList<UpdateRecord>();
1366 mRecordsByProvider.put(provider, records);
1367 }
1368 if (!records.contains(this)) {
1369 records.add(this);
1370 }
David Christie2ff96af2014-01-30 16:09:37 -08001371
1372 // Update statistics for historical location requests by package/provider
1373 mRequestStatistics.startRequesting(
1374 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376
1377 /**
David Christie2ff96af2014-01-30 16:09:37 -08001378 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001380 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001381 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1382
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001383 // remove from mRecordsByProvider
1384 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1385 if (globalRecords != null) {
1386 globalRecords.remove(this);
1387 }
1388
1389 if (!removeReceiver) return; // the caller will handle the rest
1390
1391 // remove from Receiver#mUpdateRecords
1392 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1393 if (receiverRecords != null) {
1394 receiverRecords.remove(this.mProvider);
1395
1396 // and also remove the Receiver if it has no more update records
1397 if (removeReceiver && receiverRecords.size() == 0) {
1398 removeUpdatesLocked(mReceiver);
1399 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402
1403 @Override
1404 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001405 StringBuilder s = new StringBuilder();
1406 s.append("UpdateRecord[");
1407 s.append(mProvider);
1408 s.append(' ').append(mReceiver.mPackageName).append('(');
1409 s.append(mReceiver.mUid).append(')');
1410 s.append(' ').append(mRequest);
1411 s.append(']');
1412 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
1415
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001416 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001417 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001418 IBinder binder = listener.asBinder();
1419 Receiver receiver = mReceivers.get(binder);
1420 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001421 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1422 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001423 mReceivers.put(binder, receiver);
1424
1425 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001426 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001427 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001428 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001429 return null;
1430 }
1431 }
1432 return receiver;
1433 }
1434
David Christie82edc9b2013-07-19 11:31:42 -07001435 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001436 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001437 Receiver receiver = mReceivers.get(intent);
1438 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001439 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1440 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001441 mReceivers.put(intent, receiver);
1442 }
1443 return receiver;
1444 }
1445
Victoria Lease37425c32012-10-16 16:08:48 -07001446 /**
1447 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1448 * and consistency requirements.
1449 *
1450 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001451 * @return a version of request that meets the given resolution and consistency requirements
1452 * @hide
1453 */
1454 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1455 LocationRequest sanitizedRequest = new LocationRequest(request);
1456 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1457 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001458 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001459 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001460 break;
1461 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001462 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001463 break;
1464 }
1465 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001466 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1467 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001468 }
Victoria Lease37425c32012-10-16 16:08:48 -07001469 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1470 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001471 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001472 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001473 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001474 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001475 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001476 }
Victoria Lease37425c32012-10-16 16:08:48 -07001477 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001478 }
1479
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001480 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001481 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001482 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001483 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001484 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001485 String[] packages = mPackageManager.getPackagesForUid(uid);
1486 if (packages == null) {
1487 throw new SecurityException("invalid UID " + uid);
1488 }
1489 for (String pkg : packages) {
1490 if (packageName.equals(pkg)) return;
1491 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001492 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001493 }
1494
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001495 private void checkPendingIntent(PendingIntent intent) {
1496 if (intent == null) {
1497 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001498 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001499 }
1500
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001501 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001502 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001503 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001504 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001505 } else if (intent != null && listener != null) {
1506 throw new IllegalArgumentException("cannot register both listener and intent");
1507 } else if (intent != null) {
1508 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001509 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001510 } else {
David Christie40e57822013-07-30 11:36:48 -07001511 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001512 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001513 }
1514
Nick Pellye0fd6932012-07-11 10:26:13 -07001515 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001516 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1517 PendingIntent intent, String packageName) {
1518 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1519 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001520 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1521 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1522 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07001523 WorkSource workSource = request.getWorkSource();
1524 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07001525 checkDeviceStatsAllowed();
1526 }
1527 boolean hideFromAppOps = request.getHideFromAppOps();
1528 if (hideFromAppOps) {
1529 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07001530 }
Victoria Lease37425c32012-10-16 16:08:48 -07001531 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001533 final int pid = Binder.getCallingPid();
1534 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001535 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 long identity = Binder.clearCallingIdentity();
1537 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001538 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1539 // a location.
Dianne Hackborn35654b62013-01-14 17:38:02 -08001540 checkLocationAccess(uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001541
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001542 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001543 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07001544 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07001545 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001546 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 } finally {
1548 Binder.restoreCallingIdentity(identity);
1549 }
1550 }
1551
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001552 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1553 int pid, int uid, String packageName) {
1554 // Figure out the provider. Either its explicitly request (legacy use cases), or
1555 // use the fused provider
1556 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1557 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001558 if (name == null) {
1559 throw new IllegalArgumentException("provider name must not be null");
1560 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001561
1562 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1563 + " " + name + " " + request + " from " + packageName + "(" + uid + ")");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001564 LocationProviderInterface provider = mProvidersByName.get(name);
1565 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07001566 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001567 }
1568
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001569 UpdateRecord record = new UpdateRecord(name, request, receiver);
1570 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1571 if (oldRecord != null) {
1572 oldRecord.disposeLocked(false);
1573 }
1574
Victoria Lease09eeaec2013-02-05 11:34:13 -08001575 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001576 if (isProviderEnabled) {
1577 applyRequirementsLocked(name);
1578 } else {
1579 // Notify the listener that updates are currently disabled
1580 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 }
David Christie0b837452013-07-29 16:02:13 -07001582 // Update the monitoring here just in case multiple location requests were added to the
1583 // same receiver (this request may be high power and the initial might not have been).
1584 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001585 }
1586
Nick Pellye0fd6932012-07-11 10:26:13 -07001587 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001588 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1589 String packageName) {
1590 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001591
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001592 final int pid = Binder.getCallingPid();
1593 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001594
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001595 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07001596 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07001597 boolean hideFromAppOps = false;
1598 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
1599 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001600
1601 // providers may use public location API's, need to clear identity
1602 long identity = Binder.clearCallingIdentity();
1603 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001604 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001605 } finally {
1606 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
1609 }
1610
1611 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001612 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613
1614 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1615 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1616 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001617 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001618 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 }
1620
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07001621 receiver.updateMonitoring(false);
1622
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001623 // Record which providers were associated with this listener
1624 HashSet<String> providers = new HashSet<String>();
1625 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1626 if (oldRecords != null) {
1627 // Call dispose() on the obsolete update records.
1628 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08001629 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001630 record.disposeLocked(false);
1631 }
1632 // Accumulate providers
1633 providers.addAll(oldRecords.keySet());
1634 }
1635
1636 // update provider
1637 for (String provider : providers) {
1638 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001639 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001640 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641 }
1642
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001643 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
1645 }
1646
Dianne Hackbornc2293022013-02-06 23:14:49 -08001647 private void applyAllProviderRequirementsLocked() {
1648 for (LocationProviderInterface p : mProviders) {
1649 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001650 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001651 continue;
1652 }
1653
1654 applyRequirementsLocked(p.getName());
1655 }
1656 }
1657
Nick Pellye0fd6932012-07-11 10:26:13 -07001658 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001659 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001660 if (D) Log.d(TAG, "getLastLocation: " + request);
1661 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001662 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001663 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001664 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1665 request.getProvider());
1666 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001667
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001668 final int uid = Binder.getCallingUid();
1669 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001670 try {
1671 if (mBlacklist.isBlacklisted(packageName)) {
1672 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1673 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001674 return null;
1675 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001676
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001677 if (!reportLocationAccessNoThrow(uid, packageName, allowedResolutionLevel)) {
1678 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1679 packageName);
1680 return null;
1681 }
1682
Victoria Leaseb711d572012-10-02 13:14:11 -07001683 synchronized (mLock) {
1684 // Figure out the provider. Either its explicitly request (deprecated API's),
1685 // or use the fused provider
1686 String name = request.getProvider();
1687 if (name == null) name = LocationManager.FUSED_PROVIDER;
1688 LocationProviderInterface provider = mProvidersByName.get(name);
1689 if (provider == null) return null;
1690
Victoria Lease09eeaec2013-02-05 11:34:13 -08001691 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001692
David Christie1b9b7b12013-04-15 15:31:11 -07001693 Location location;
1694 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1695 // Make sure that an app with coarse permissions can't get frequent location
1696 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1697 location = mLastLocationCoarseInterval.get(name);
1698 } else {
1699 location = mLastLocation.get(name);
1700 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001701 if (location == null) {
1702 return null;
1703 }
Victoria Lease37425c32012-10-16 16:08:48 -07001704 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001705 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1706 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001707 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001708 }
Victoria Lease37425c32012-10-16 16:08:48 -07001709 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001710 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001711 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001712 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001713 return null;
1714 } finally {
1715 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001716 }
1717 }
1718
1719 @Override
1720 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1721 String packageName) {
1722 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001723 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1724 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001725 checkPendingIntent(intent);
1726 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001727 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1728 request.getProvider());
1729 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001730
Victoria Lease37425c32012-10-16 16:08:48 -07001731 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001732
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001733 // geo-fence manager uses the public location API, need to clear identity
1734 int uid = Binder.getCallingUid();
Victoria Lease56e675b2012-11-05 19:25:06 -08001735 if (UserHandle.getUserId(uid) != UserHandle.USER_OWNER) {
1736 // temporary measure until geofences work for secondary users
1737 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1738 return;
1739 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001740 long identity = Binder.clearCallingIdentity();
1741 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001742 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1743 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001744 } finally {
1745 Binder.restoreCallingIdentity(identity);
1746 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001747 }
1748
1749 @Override
1750 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Victoria Lease37425c32012-10-16 16:08:48 -07001751 checkResolutionLevelIsSufficientForGeofenceUse(getCallerAllowedResolutionLevel());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001752 checkPendingIntent(intent);
1753 checkPackageName(packageName);
1754
1755 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1756
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001757 // geo-fence manager uses the public location API, need to clear identity
1758 long identity = Binder.clearCallingIdentity();
1759 try {
1760 mGeofenceManager.removeFence(geofence, intent);
1761 } finally {
1762 Binder.restoreCallingIdentity(identity);
1763 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001764 }
1765
1766
1767 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001768 public boolean addGpsStatusListener(IGpsStatusListener listener, String packageName) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001769 if (mGpsStatusProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 return false;
1771 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001772 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1773 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001774 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001776 final int uid = Binder.getCallingUid();
1777 final long ident = Binder.clearCallingIdentity();
1778 try {
Victoria Lease3d5173d2013-02-05 16:07:32 -08001779 if (!checkLocationAccess(uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001780 return false;
1781 }
1782 } finally {
1783 Binder.restoreCallingIdentity(ident);
1784 }
1785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 try {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001787 mGpsStatusProvider.addGpsStatusListener(listener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001789 Slog.e(TAG, "mGpsStatusProvider.addGpsStatusListener failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 return false;
1791 }
1792 return true;
1793 }
1794
Nick Pellye0fd6932012-07-11 10:26:13 -07001795 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 public void removeGpsStatusListener(IGpsStatusListener listener) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001797 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001798 try {
1799 mGpsStatusProvider.removeGpsStatusListener(listener);
1800 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001801 Slog.e(TAG, "mGpsStatusProvider.removeGpsStatusListener failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
1804 }
1805
Nick Pellye0fd6932012-07-11 10:26:13 -07001806 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001808 if (provider == null) {
1809 // throw NullPointerException to remain compatible with previous implementation
1810 throw new NullPointerException();
1811 }
Victoria Lease37425c32012-10-16 16:08:48 -07001812 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1813 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001816 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 != PackageManager.PERMISSION_GRANTED)) {
1818 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1819 }
1820
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001821 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001822 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001823 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001824
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001825 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
1827 }
1828
Nick Pellye0fd6932012-07-11 10:26:13 -07001829 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001830 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001831 if (Binder.getCallingUid() != Process.myUid()) {
1832 throw new SecurityException(
1833 "calling sendNiResponse from outside of the system is not allowed");
1834 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001835 try {
1836 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001837 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001838 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001839 return false;
1840 }
1841 }
1842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001844 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001845 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 * accessed by the caller
1847 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001848 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001849 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001850 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08001851 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07001852 }
1853
Victoria Lease37425c32012-10-16 16:08:48 -07001854 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1855 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001857 LocationProviderInterface p;
1858 synchronized (mLock) {
1859 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001860 }
1861
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001862 if (p == null) return null;
1863 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001864 }
1865
Nick Pellye0fd6932012-07-11 10:26:13 -07001866 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07001868 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
1869 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001870 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1871
Victoria Lease09eeaec2013-02-05 11:34:13 -08001872 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001873 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001874 try {
1875 synchronized (mLock) {
1876 LocationProviderInterface p = mProvidersByName.get(provider);
1877 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001878
Victoria Lease09eeaec2013-02-05 11:34:13 -08001879 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001880 }
1881 } finally {
1882 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001883 }
1884 }
1885
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001886 /**
1887 * Returns "true" if the UID belongs to a bound location provider.
1888 *
1889 * @param uid the uid
1890 * @return true if uid belongs to a bound location provider
1891 */
1892 private boolean isUidALocationProvider(int uid) {
1893 if (uid == Process.SYSTEM_UID) {
1894 return true;
1895 }
1896 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07001897 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001898 }
1899 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07001900 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001901 }
1902 return false;
1903 }
1904
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001905 private void checkCallerIsProvider() {
1906 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
1907 == PackageManager.PERMISSION_GRANTED) {
1908 return;
1909 }
1910
1911 // Previously we only used the INSTALL_LOCATION_PROVIDER
1912 // check. But that is system or signature
1913 // protection level which is not flexible enough for
1914 // providers installed oustide the system image. So
1915 // also allow providers with a UID matching the
1916 // currently bound package name
1917
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001918 if (isUidALocationProvider(Binder.getCallingUid())) {
1919 return;
1920 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001921
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001922 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
1923 "or UID of a currently bound location provider");
1924 }
1925
David Christie1f141c12014-05-14 15:11:15 -07001926 /**
1927 * Returns true if the given package belongs to the given uid.
1928 */
1929 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001930 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 return false;
1932 }
David Christie1f141c12014-05-14 15:11:15 -07001933 String[] packageNames = mPackageManager.getPackagesForUid(uid);
1934 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001935 return false;
1936 }
David Christie1f141c12014-05-14 15:11:15 -07001937 for (String name : packageNames) {
1938 if (packageName.equals(name)) {
1939 return true;
1940 }
1941 }
1942 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944
Nick Pellye0fd6932012-07-11 10:26:13 -07001945 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05001946 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001947 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04001948
Nick Pelly2eeeec22012-07-18 13:13:37 -07001949 if (!location.isComplete()) {
1950 Log.w(TAG, "Dropping incomplete location: " + location);
1951 return;
1952 }
1953
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001954 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
1955 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05001956 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07001957 mLocationHandler.sendMessageAtFrontOfQueue(m);
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960
Laurent Tu75defb62012-11-01 16:21:52 -07001961 private static boolean shouldBroadcastSafe(
1962 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 // Always broadcast the first update
1964 if (lastLoc == null) {
1965 return true;
1966 }
1967
Nick Pellyf1be6862012-05-15 10:53:42 -07001968 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001969 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07001970 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
1971 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001972 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001973 return false;
1974 }
1975
1976 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001977 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 if (minDistance > 0.0) {
1979 if (loc.distanceTo(lastLoc) <= minDistance) {
1980 return false;
1981 }
1982 }
1983
Laurent Tu75defb62012-11-01 16:21:52 -07001984 // Check whether sufficient number of udpates is left
1985 if (record.mRequest.getNumUpdates() <= 0) {
1986 return false;
1987 }
1988
1989 // Check whether the expiry date has passed
1990 if (record.mRequest.getExpireAt() < now) {
1991 return false;
1992 }
1993
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 return true;
1995 }
1996
Mike Lockwooda4903f22010-02-17 06:42:23 -05001997 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001998 if (D) Log.d(TAG, "incoming location: " + location);
1999
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002000 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002001 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002002
Laurent Tu60ec50a2012-10-04 17:00:10 -07002003 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002004 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002005 if (p == null) return;
2006
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002007 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002008 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2009 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002010 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002011 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002012 lastLocation = new Location(provider);
2013 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002014 } else {
2015 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2016 if (noGPSLocation == null && lastNoGPSLocation != null) {
2017 // New location has no no-GPS location: adopt last no-GPS location. This is set
2018 // directly into location because we do not want to notify COARSE clients.
2019 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2020 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002021 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002022 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002023
David Christie1b9b7b12013-04-15 15:31:11 -07002024 // Update last known coarse interval location if enough time has passed.
2025 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2026 if (lastLocationCoarseInterval == null) {
2027 lastLocationCoarseInterval = new Location(location);
2028 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2029 }
2030 long timeDiffNanos = location.getElapsedRealtimeNanos()
2031 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2032 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2033 lastLocationCoarseInterval.set(location);
2034 }
2035 // Don't ever return a coarse location that is more recent than the allowed update
2036 // interval (i.e. don't allow an app to keep registering and unregistering for
2037 // location updates to overcome the minimum interval).
2038 noGPSLocation =
2039 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2040
Laurent Tu60ec50a2012-10-04 17:00:10 -07002041 // Skip if there are no UpdateRecords for this provider.
2042 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2043 if (records == null || records.size() == 0) return;
2044
Victoria Lease09016ab2012-09-16 12:33:15 -07002045 // Fetch coarse location
2046 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002047 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002048 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2049 }
2050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 // Fetch latest status update time
2052 long newStatusUpdateTime = p.getStatusUpdateTime();
2053
David Christie2ff96af2014-01-30 16:09:37 -08002054 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055 Bundle extras = new Bundle();
2056 int status = p.getStatus(extras);
2057
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002059 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002060
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002061 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002062 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002063 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002064 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002065
Victoria Lease269518e2012-10-29 08:25:39 -07002066 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002067 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002068 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002069 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002070 " (current user: " + mCurrentUserId + ", app: " +
2071 receiver.mPackageName + ")");
2072 }
2073 continue;
2074 }
2075
Nick Pelly4035f5a2012-08-17 14:43:49 -07002076 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2077 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2078 receiver.mPackageName);
2079 continue;
2080 }
2081
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002082 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
2083 receiver.mAllowedResolutionLevel)) {
2084 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2085 receiver.mPackageName);
2086 continue;
2087 }
2088
Victoria Lease09016ab2012-09-16 12:33:15 -07002089 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07002090 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2091 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002092 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002093 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002094 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002095 if (notifyLocation != null) {
2096 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002097 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002098 if (lastLoc == null) {
2099 lastLoc = new Location(notifyLocation);
2100 r.mLastFixBroadcast = lastLoc;
2101 } else {
2102 lastLoc.set(notifyLocation);
2103 }
2104 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2105 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2106 receiverDead = true;
2107 }
Laurent Tu75defb62012-11-01 16:21:52 -07002108 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002109 }
2110 }
2111
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002112 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002114 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002116 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002118 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002119 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002120 }
2121 }
2122
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002123 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002124 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002125 if (deadUpdateRecords == null) {
2126 deadUpdateRecords = new ArrayList<UpdateRecord>();
2127 }
2128 deadUpdateRecords.add(r);
2129 }
2130 // track dead receivers
2131 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002132 if (deadReceivers == null) {
2133 deadReceivers = new ArrayList<Receiver>();
2134 }
2135 if (!deadReceivers.contains(receiver)) {
2136 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002137 }
2138 }
2139 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002140
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002141 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002143 for (Receiver receiver : deadReceivers) {
2144 removeUpdatesLocked(receiver);
2145 }
2146 }
2147 if (deadUpdateRecords != null) {
2148 for (UpdateRecord r : deadUpdateRecords) {
2149 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002151 applyRequirementsLocked(provider);
2152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 }
2154
2155 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002156 public LocationWorkerHandler(Looper looper) {
2157 super(looper, null, true);
2158 }
2159
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 @Override
2161 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002162 switch (msg.what) {
2163 case MSG_LOCATION_CHANGED:
2164 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2165 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002166 }
2167 }
2168 }
2169
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002170 private boolean isMockProvider(String provider) {
2171 synchronized (mLock) {
2172 return mMockProviders.containsKey(provider);
2173 }
2174 }
2175
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002176 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002177 // create a working copy of the incoming Location so that the service can modify it without
2178 // disturbing the caller's copy
2179 Location myLocation = new Location(location);
2180 String provider = myLocation.getProvider();
2181
2182 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2183 // bit if location did not come from a mock provider because passive/fused providers can
2184 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2185 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2186 myLocation.setIsFromMockProvider(true);
2187 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002188
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002189 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002190 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2191 if (!passive) {
2192 // notify passive provider of the new location
2193 mPassiveProvider.updateLocation(myLocation);
2194 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002195 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199
Mike Lockwoode97ae402010-09-29 15:23:46 -04002200 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2201 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002202 public void onPackageDisappeared(String packageName, int reason) {
2203 // remove all receivers associated with this package name
2204 synchronized (mLock) {
2205 ArrayList<Receiver> deadReceivers = null;
2206
2207 for (Receiver receiver : mReceivers.values()) {
2208 if (receiver.mPackageName.equals(packageName)) {
2209 if (deadReceivers == null) {
2210 deadReceivers = new ArrayList<Receiver>();
2211 }
2212 deadReceivers.add(receiver);
2213 }
2214 }
2215
2216 // perform removal outside of mReceivers loop
2217 if (deadReceivers != null) {
2218 for (Receiver receiver : deadReceivers) {
2219 removeUpdatesLocked(receiver);
2220 }
2221 }
2222 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002223 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002224 };
2225
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 // Geocoder
2227
Nick Pellye0fd6932012-07-11 10:26:13 -07002228 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002229 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002230 return mGeocodeProvider != null;
2231 }
2232
Nick Pellye0fd6932012-07-11 10:26:13 -07002233 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002235 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002236 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002237 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2238 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002239 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002240 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
2242
Mike Lockwooda55c3212009-04-15 11:10:11 -04002243
Nick Pellye0fd6932012-07-11 10:26:13 -07002244 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002246 double lowerLeftLatitude, double lowerLeftLongitude,
2247 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002248 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002249
2250 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002251 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2252 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2253 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002255 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002256 }
2257
2258 // Mock Providers
2259
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 private void checkMockPermissionsSafe() {
2261 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2262 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2263 if (!allowMocks) {
2264 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2265 }
2266
2267 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
David Christie2ff96af2014-01-30 16:09:37 -08002268 PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002269 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
Nick Pellye0fd6932012-07-11 10:26:13 -07002270 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002271 }
2272
Nick Pellye0fd6932012-07-11 10:26:13 -07002273 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002274 public void addTestProvider(String name, ProviderProperties properties) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002275 checkMockPermissionsSafe();
2276
Mike Lockwooda4903f22010-02-17 06:42:23 -05002277 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2278 throw new IllegalArgumentException("Cannot mock the passive location provider");
2279 }
2280
Mike Lockwood86328a92009-10-23 08:38:25 -04002281 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002282 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002283 // remove the real provider if we are replacing GPS or network provider
2284 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002285 || LocationManager.NETWORK_PROVIDER.equals(name)
2286 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002287 LocationProviderInterface p = mProvidersByName.get(name);
2288 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002289 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002290 }
2291 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002292 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002293 updateProvidersLocked();
2294 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002295 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002296 }
2297
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002298 private void addTestProviderLocked(String name, ProviderProperties properties) {
2299 if (mProvidersByName.get(name) != null) {
2300 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2301 }
2302 MockProvider provider = new MockProvider(name, this, properties);
2303 addProviderLocked(provider);
2304 mMockProviders.put(name, provider);
2305 mLastLocation.put(name, null);
2306 mLastLocationCoarseInterval.put(name, null);
2307 }
2308
Nick Pellye0fd6932012-07-11 10:26:13 -07002309 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 public void removeTestProvider(String provider) {
2311 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002312 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002313
2314 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002315 // we don't leave anything dangling.
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002316 clearTestProviderEnabled(provider);
2317 clearTestProviderLocation(provider);
2318 clearTestProviderStatus(provider);
2319
You Kima6d0b6f2012-10-28 03:58:44 +09002320 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002321 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002322 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2323 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002324 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002325 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002326
2327 // reinstate real provider if available
2328 LocationProviderInterface realProvider = mRealProviders.get(provider);
2329 if (realProvider != null) {
2330 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002331 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002332 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002333 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002335 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
2337 }
2338
Nick Pellye0fd6932012-07-11 10:26:13 -07002339 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 public void setTestProviderLocation(String provider, Location loc) {
2341 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002342 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002343 MockProvider mockProvider = mMockProviders.get(provider);
2344 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2346 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002347 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2348 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002349 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002350 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 }
2352 }
2353
Nick Pellye0fd6932012-07-11 10:26:13 -07002354 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 public void clearTestProviderLocation(String provider) {
2356 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002357 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002358 MockProvider mockProvider = mMockProviders.get(provider);
2359 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2361 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002362 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002363 }
2364 }
2365
Nick Pellye0fd6932012-07-11 10:26:13 -07002366 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002367 public void setTestProviderEnabled(String provider, boolean enabled) {
2368 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002369 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002370 MockProvider mockProvider = mMockProviders.get(provider);
2371 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002372 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2373 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002374 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002375 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002376 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 mEnabledProviders.add(provider);
2378 mDisabledProviders.remove(provider);
2379 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002380 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002381 mEnabledProviders.remove(provider);
2382 mDisabledProviders.add(provider);
2383 }
2384 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002385 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002386 }
2387 }
2388
Nick Pellye0fd6932012-07-11 10:26:13 -07002389 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 public void clearTestProviderEnabled(String provider) {
2391 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002392 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002393 MockProvider mockProvider = mMockProviders.get(provider);
2394 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002395 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2396 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002397 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398 mEnabledProviders.remove(provider);
2399 mDisabledProviders.remove(provider);
2400 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002401 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002402 }
2403 }
2404
Nick Pellye0fd6932012-07-11 10:26:13 -07002405 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2407 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002408 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002409 MockProvider mockProvider = mMockProviders.get(provider);
2410 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2412 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002413 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 }
2415 }
2416
Nick Pellye0fd6932012-07-11 10:26:13 -07002417 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 public void clearTestProviderStatus(String provider) {
2419 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002420 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002421 MockProvider mockProvider = mMockProviders.get(provider);
2422 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002423 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2424 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002425 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 }
2427 }
2428
2429 private void log(String log) {
2430 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002431 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 }
2433 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002434
2435 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2437 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2438 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002439 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 + Binder.getCallingPid()
2441 + ", uid=" + Binder.getCallingUid());
2442 return;
2443 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002444
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002445 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002448 for (Receiver receiver : mReceivers.values()) {
2449 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 }
David Christie2ff96af2014-01-30 16:09:37 -08002451 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002452 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2453 pw.println(" " + entry.getKey() + ":");
2454 for (UpdateRecord record : entry.getValue()) {
2455 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 }
2457 }
David Christie2ff96af2014-01-30 16:09:37 -08002458 pw.println(" Historical Records by Provider:");
2459 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2460 : mRequestStatistics.statistics.entrySet()) {
2461 PackageProviderKey key = entry.getKey();
2462 PackageStatistics stats = entry.getValue();
2463 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002466 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2467 String provider = entry.getKey();
2468 Location location = entry.getValue();
2469 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002471
David Christie1b9b7b12013-04-15 15:31:11 -07002472 pw.println(" Last Known Locations Coarse Intervals:");
2473 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2474 String provider = entry.getKey();
2475 Location location = entry.getValue();
2476 pw.println(" " + provider + ": " + location);
2477 }
2478
Nick Pellye0fd6932012-07-11 10:26:13 -07002479 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002480
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 if (mEnabledProviders.size() > 0) {
2482 pw.println(" Enabled Providers:");
2483 for (String i : mEnabledProviders) {
2484 pw.println(" " + i);
2485 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 }
2488 if (mDisabledProviders.size() > 0) {
2489 pw.println(" Disabled Providers:");
2490 for (String i : mDisabledProviders) {
2491 pw.println(" " + i);
2492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002494 pw.append(" ");
2495 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002496 if (mMockProviders.size() > 0) {
2497 pw.println(" Mock Providers:");
2498 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002499 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002500 }
2501 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002502
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002503 pw.append(" fudger: ");
2504 mLocationFudger.dump(fd, pw, args);
2505
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002506 if (args.length > 0 && "short".equals(args[0])) {
2507 return;
2508 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002509 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002510 pw.print(provider.getName() + " Internal State");
2511 if (provider instanceof LocationProviderProxy) {
2512 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2513 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002514 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002515 pw.println(":");
2516 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002517 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 }
2519 }
2520}