blob: 5646084f5c63e28058ff1d598bc9cb206f8c0721 [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
Soonil Nagarkar7decfb62017-01-18 12:18:49 -080019import android.app.ActivityManager;
Svet Ganovadc1cf42015-06-15 16:36:24 -070020import android.content.pm.PackageManagerInternal;
destradaaea8a8a62014-06-23 18:19:03 -070021import com.android.internal.content.PackageMonitor;
22import com.android.internal.location.ProviderProperties;
23import com.android.internal.location.ProviderRequest;
24import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070025import com.android.internal.util.ArrayUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070026import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070027import com.android.server.location.FlpHardwareProvider;
28import com.android.server.location.FusedProxy;
29import com.android.server.location.GeocoderProxy;
30import com.android.server.location.GeofenceManager;
31import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080032import com.android.server.location.GnssLocationProvider;
33import com.android.server.location.GnssMeasurementsProvider;
34import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070035import com.android.server.location.LocationBlacklist;
36import com.android.server.location.LocationFudger;
37import com.android.server.location.LocationProviderInterface;
38import com.android.server.location.LocationProviderProxy;
39import com.android.server.location.LocationRequestStatistics;
40import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
41import com.android.server.location.LocationRequestStatistics.PackageStatistics;
42import com.android.server.location.MockProvider;
43import com.android.server.location.PassiveProvider;
44
Dianne Hackborna06de0f2012-12-11 16:34:47 -080045import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070047import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.ContentResolver;
49import android.content.Context;
50import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070051import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070052import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050053import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070055import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050056import android.content.pm.ResolveInfo;
57import android.content.pm.Signature;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050058import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070059import android.database.ContentObserver;
destradaaa4fa3b52014-07-09 10:46:39 -070060import android.hardware.location.ActivityRecognitionHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070062import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050063import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070064import android.location.Geofence;
Lifu Tang818aa2c2016-02-01 01:52:00 -080065import android.location.IGnssMeasurementsListener;
Lifu Tang30f95a72016-01-07 23:20:38 -080066import android.location.IGnssStatusListener;
67import android.location.IGnssStatusProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -070068import android.location.IGpsGeofenceHardware;
Lifu Tang818aa2c2016-02-01 01:52:00 -080069import android.location.IGnssNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.location.ILocationListener;
71import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040072import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.location.Location;
74import android.location.LocationManager;
75import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070076import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Binder;
78import android.os.Bundle;
79import android.os.Handler;
80import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070081import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Message;
83import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070084import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070086import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070087import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070088import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070089import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Tom O'Neilla206a0f2016-12-15 10:26:28 -080091import android.text.TextUtils;
92import android.util.EventLog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080094import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070095
Mike Lockwood43e33f22010-03-26 10:41:48 -040096import java.io.FileDescriptor;
97import java.io.PrintWriter;
98import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070099import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400100import java.util.HashMap;
101import java.util.HashSet;
102import java.util.List;
103import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400104import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
106/**
107 * The service class that manages LocationProviders and issues location
108 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800110public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800112 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700113
114 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Victoria Lease37425c32012-10-16 16:08:48 -0700116 // Location resolution level: no location data whatsoever
117 private static final int RESOLUTION_LEVEL_NONE = 0;
118 // Location resolution level: coarse location data only
119 private static final int RESOLUTION_LEVEL_COARSE = 1;
120 // Location resolution level: fine location data
121 private static final int RESOLUTION_LEVEL_FINE = 2;
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700124 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700126 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400127 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700128 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
129
130 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700131 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700132 private static final String FUSED_LOCATION_SERVICE_ACTION =
133 "com.android.location.service.FusedLocationProvider";
134
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800135 private static final String GMSCORE_PACKAGE = "com.android.google.gms";
136
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700137 private static final int MSG_LOCATION_CHANGED = 1;
138
David Christie1b9b7b12013-04-15 15:31:11 -0700139 private static final long NANOS_PER_MILLI = 1000000L;
140
David Christie0b837452013-07-29 16:02:13 -0700141 // The maximum interval a location request can have and still be considered "high power".
142 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
143
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800144 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800145 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800146
Nick Pellyf1be6862012-05-15 10:53:42 -0700147 // Location Providers may sometimes deliver location updates
148 // slightly faster that requested - provide grace period so
149 // we don't unnecessarily filter events that are otherwise on
150 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700151 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700152
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700153 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
154
155 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800156 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700157
158 // used internally for synchronization
159 private final Object mLock = new Object();
160
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700161 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700162 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700163 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700164 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700165 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800166 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700167 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700168 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800169 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700170 private INetInitiatedListener mNetInitiatedListener;
171 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700172 private PassiveProvider mPassiveProvider; // track passive provider for special cases
173 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800174 private GnssMeasurementsProvider mGnssMeasurementsProvider;
175 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700176 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700177
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700178 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700180 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800181 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
183 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800184 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 // Mock (test) providers
187 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800188 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700190 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800191 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700193 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500194 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800195 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400196
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700197 // real providers, saved here when mocked out
198 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800199 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700201 // mapping from provider name to provider
202 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800203 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700205 // mapping from provider name to all its UpdateRecords
206 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800207 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700208
David Christie2ff96af2014-01-30 16:09:37 -0800209 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
210
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700211 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800212 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
David Christie1b9b7b12013-04-15 15:31:11 -0700214 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
215 // locations stored here are not fudged for coarse permissions.
216 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800217 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700218
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800219 // all providers that operate over proxy, for authorizing incoming location and whitelisting
220 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700221 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800222 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800224 private String[] mBackgroundThrottlePackageWhitelist = new String[]{};
225
Victoria Lease38389b62012-09-30 11:44:22 -0700226 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700227 private int mCurrentUserId = UserHandle.USER_SYSTEM;
228 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_SYSTEM };
Victoria Lease38389b62012-09-30 11:44:22 -0700229
Lifu Tang9363b942016-02-16 18:07:00 -0800230 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800231
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700232 public LocationManagerService(Context context) {
233 super();
234 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800235 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800236
Svet Ganovadc1cf42015-06-15 16:36:24 -0700237 // Let the package manager query which are the default location
238 // providers as they get certain permissions granted by default.
239 PackageManagerInternal packageManagerInternal = LocalServices.getService(
240 PackageManagerInternal.class);
241 packageManagerInternal.setLocationPackagesProvider(
242 new PackageManagerInternal.PackagesProvider() {
243 @Override
244 public String[] getPackages(int userId) {
245 return mContext.getResources().getStringArray(
246 com.android.internal.R.array.config_locationProviderPackageNames);
247 }
248 });
249
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700250 if (D) Log.d(TAG, "Constructed");
251
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700252 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700253 }
254
Svetoslav Ganova0027152013-06-25 14:59:53 -0700255 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700256 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700257 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700258
Victoria Lease5cd731a2012-12-19 15:04:21 -0800259 // fetch package manager
260 mPackageManager = mContext.getPackageManager();
261
Victoria Lease0aa28602013-05-29 15:28:26 -0700262 // fetch power manager
263 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800264
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800265 // fetch activity manager
266 mActivityManager
267 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
268
Victoria Lease5cd731a2012-12-19 15:04:21 -0800269 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700270 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800271
272 // prepare mLocationHandler's dependents
273 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
274 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
275 mBlacklist.init();
276 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
277
Dianne Hackbornc2293022013-02-06 23:14:49 -0800278 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700279 AppOpsManager.OnOpChangedListener callback
280 = new AppOpsManager.OnOpChangedInternalListener() {
281 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800282 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700283 for (Receiver receiver : mReceivers.values()) {
284 receiver.updateMonitoring(true);
285 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800286 applyAllProviderRequirementsLocked();
287 }
288 }
289 };
290 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
291
David Christieb870dbf2015-06-22 12:42:53 -0700292 PackageManager.OnPermissionsChangedListener permissionListener
293 = new PackageManager.OnPermissionsChangedListener() {
294 @Override
295 public void onPermissionsChanged(final int uid) {
296 synchronized (mLock) {
297 applyAllProviderRequirementsLocked();
298 }
299 }
300 };
301 mPackageManager.addOnPermissionsChangeListener(permissionListener);
302
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800303 // listen for background/foreground changes
304 ActivityManager.OnUidImportanceListener uidImportanceListener
305 = new ActivityManager.OnUidImportanceListener() {
306 @Override
307 public void onUidImportance(int uid, int importance) {
308 boolean foreground = isImportanceForeground(importance);
309 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
310 synchronized (mLock) {
311 for (Map.Entry<String, ArrayList<UpdateRecord>> entry
312 : mRecordsByProvider.entrySet()) {
313 String provider = entry.getKey();
314 for (UpdateRecord record : entry.getValue()) {
315 if (record.mReceiver.mUid == uid
316 && record.mIsForegroundUid != foreground) {
317 if (D) Log.d(TAG, "request from uid " + uid + " is now "
318 + (foreground ? "foreground" : "background)"));
319 record.mIsForegroundUid = foreground;
320
321 if (!isThrottlingExemptLocked(record.mReceiver)) {
322 affectedProviders.add(provider);
323 }
324 }
325 }
326 }
327 for (String provider : affectedProviders) {
328 applyRequirementsLocked(provider);
329 }
330 }
331
332 }
333 };
334 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
335 ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE);
336
Amith Yamasanib27528d2014-06-05 15:02:10 -0700337 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
338 updateUserProfiles(mCurrentUserId);
339
Victoria Lease5cd731a2012-12-19 15:04:21 -0800340 // prepare providers
341 loadProvidersLocked();
342 updateProvidersLocked();
343 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700344
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700345 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700346 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700347 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700348 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800349 @Override
350 public void onChange(boolean selfChange) {
351 synchronized (mLock) {
352 updateProvidersLocked();
353 }
354 }
355 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800356 mContext.getContentResolver().registerContentObserver(
357 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
358 true,
359 new ContentObserver(mLocationHandler) {
360 @Override
361 public void onChange(boolean selfChange) {
362 synchronized (mLock) {
363 updateProvidersLocked();
364 }
365 }
366 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800367 mContext.getContentResolver().registerContentObserver(
368 Settings.Global.getUriFor(
369 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
370 true,
371 new ContentObserver(mLocationHandler) {
372 @Override
373 public void onChange(boolean selfChange) {
374 synchronized (mLock) {
375 String setting = Settings.Global.getString(
376 mContext.getContentResolver(),
377 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
378 if (setting == null) {
379 setting = "";
380 }
381
382 mBackgroundThrottlePackageWhitelist = setting.split(",");
383 updateProvidersLocked();
384 }
385 }
386 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800387 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700388
Victoria Lease38389b62012-09-30 11:44:22 -0700389 // listen for user change
390 IntentFilter intentFilter = new IntentFilter();
391 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700392 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
393 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700394 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700395
396 mContext.registerReceiverAsUser(new BroadcastReceiver() {
397 @Override
398 public void onReceive(Context context, Intent intent) {
399 String action = intent.getAction();
400 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
401 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700402 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
403 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
404 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700405 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700406 // shutdown only if UserId indicates whole system, not just one user
407 if(D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
408 if (getSendingUserId() == UserHandle.USER_ALL) {
409 shutdownComponents();
410 }
Victoria Lease38389b62012-09-30 11:44:22 -0700411 }
412 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800413 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700414 }
415
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800416 private static boolean isImportanceForeground(int importance) {
417 return importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
418 }
419
Amith Yamasanib27528d2014-06-05 15:02:10 -0700420 /**
destradaab9026982015-08-27 17:34:54 -0700421 * Provides a way for components held by the {@link LocationManagerService} to clean-up
422 * gracefully on system's shutdown.
423 *
424 * NOTES:
425 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
426 * support for components that do not wish to handle such event.
427 */
428 private void shutdownComponents() {
429 if(D) Log.d(TAG, "Shutting down components...");
430
431 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
432 if (gpsProvider != null && gpsProvider.isEnabled()) {
433 gpsProvider.disable();
434 }
435
destradaa2e385072015-10-14 16:45:58 -0700436 // it is needed to check if FLP HW provider is supported before accessing the instance, this
437 // avoids an exception to be thrown by the singleton factory method
438 if (FlpHardwareProvider.isSupported()) {
439 FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaab9026982015-08-27 17:34:54 -0700440 flpHardwareProvider.cleanup();
441 }
442 }
443
444 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700445 * Makes a list of userids that are related to the current user. This is
446 * relevant when using managed profiles. Otherwise the list only contains
447 * the current user.
448 *
449 * @param currentUserId the current user, who might have an alter-ego.
450 */
451 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700452 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700453 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700454 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700455 }
456 }
457
458 /**
459 * Checks if the specified userId matches any of the current foreground
460 * users stored in mCurrentUserProfiles.
461 */
462 private boolean isCurrentProfile(int userId) {
463 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700464 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700465 }
466 }
467
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500468 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
469 PackageManager pm = mContext.getPackageManager();
470 String systemPackageName = mContext.getPackageName();
471 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
472
473 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
474 new Intent(FUSED_LOCATION_SERVICE_ACTION),
475 PackageManager.GET_META_DATA, mCurrentUserId);
476 for (ResolveInfo rInfo : rInfos) {
477 String packageName = rInfo.serviceInfo.packageName;
478
479 // Check that the signature is in the list of supported sigs. If it's not in
480 // this list the standard provider binding logic won't bind to it.
481 try {
482 PackageInfo pInfo;
483 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
484 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
485 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
486 ", but has wrong signature, ignoring");
487 continue;
488 }
489 } catch (NameNotFoundException e) {
490 Log.e(TAG, "missing package: " + packageName);
491 continue;
492 }
493
494 // Get the version info
495 if (rInfo.serviceInfo.metaData == null) {
496 Log.w(TAG, "Found fused provider without metadata: " + packageName);
497 continue;
498 }
499
500 int version = rInfo.serviceInfo.metaData.getInt(
501 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
502 if (version == 0) {
503 // This should be the fallback fused location provider.
504
505 // Make sure it's in the system partition.
506 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
507 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
508 continue;
509 }
510
511 // Check that the fallback is signed the same as the OS
512 // as a proxy for coreApp="true"
513 if (pm.checkSignatures(systemPackageName, packageName)
514 != PackageManager.SIGNATURE_MATCH) {
515 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
516 + packageName);
517 continue;
518 }
519
520 // Found a valid fallback.
521 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
522 return;
523 } else {
524 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
525 }
526 }
527
528 throw new IllegalStateException("Unable to find a fused location provider that is in the "
529 + "system partition with version 0 and signed with the platform certificate. "
530 + "Such a package is needed to provide a default fused location provider in the "
531 + "event that no other fused location provider has been installed or is currently "
532 + "available. For example, coreOnly boot mode when decrypting the data "
533 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
534 }
535
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700536 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700537 // create a passive location provider, which is always enabled
538 PassiveProvider passiveProvider = new PassiveProvider(this);
539 addProviderLocked(passiveProvider);
540 mEnabledProviders.add(passiveProvider.getName());
541 mPassiveProvider = passiveProvider;
542
Lifu Tang30f95a72016-01-07 23:20:38 -0800543 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700544 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800545 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700546 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800547 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800548 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
549 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
550 addProviderLocked(gnssProvider);
551 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800552 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
553 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800554 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700555 }
556
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700557 /*
558 Load package name(s) containing location provider support.
559 These packages can contain services implementing location providers:
560 Geocoder Provider, Network Location Provider, and
561 Fused Location Provider. They will each be searched for
562 service components implementing these providers.
563 The location framework also has support for installation
564 of new location providers at run-time. The new package does not
565 have to be explicitly listed here, however it must have a signature
566 that matches the signature of at least one package on this list.
567 */
568 Resources resources = mContext.getResources();
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800569 ArrayList<String> providerPackageNames = new ArrayList<>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500570 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700571 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500572 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
573 Arrays.toString(pkgs));
574 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
575
576 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700577
578 // bind to network provider
579 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
580 mContext,
581 LocationManager.NETWORK_PROVIDER,
582 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700583 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
584 com.android.internal.R.string.config_networkLocationProviderPackageName,
585 com.android.internal.R.array.config_locationProviderPackageNames,
586 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700587 if (networkProvider != null) {
588 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
589 mProxyProviders.add(networkProvider);
590 addProviderLocked(networkProvider);
591 } else {
592 Slog.w(TAG, "no network location provider found");
593 }
594
595 // bind to fused provider
596 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
597 mContext,
598 LocationManager.FUSED_PROVIDER,
599 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700600 com.android.internal.R.bool.config_enableFusedLocationOverlay,
601 com.android.internal.R.string.config_fusedLocationProviderPackageName,
602 com.android.internal.R.array.config_locationProviderPackageNames,
603 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700604 if (fusedLocationProvider != null) {
605 addProviderLocked(fusedLocationProvider);
606 mProxyProviders.add(fusedLocationProvider);
607 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700608 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700609 } else {
610 Slog.e(TAG, "no fused location provider found",
611 new IllegalStateException("Location service needs a fused location provider"));
612 }
613
614 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700615 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
616 com.android.internal.R.bool.config_enableGeocoderOverlay,
617 com.android.internal.R.string.config_geocoderProviderPackageName,
618 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800619 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700620 if (mGeocodeProvider == null) {
621 Slog.e(TAG, "no geocoder provider found");
622 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700623
destradaaa4fa3b52014-07-09 10:46:39 -0700624 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700625 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
626 // exception, so make sure we only do that when supported
627 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700628 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700629 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700630 FusedProxy fusedProxy = FusedProxy.createAndBind(
631 mContext,
632 mLocationHandler,
633 flpHardwareProvider.getLocationHardware(),
634 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
635 com.android.internal.R.string.config_hardwareFlpPackageName,
636 com.android.internal.R.array.config_locationProviderPackageNames);
637 if (fusedProxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700638 Slog.d(TAG, "Unable to bind FusedProxy.");
destradaaf9a274c2014-07-25 15:11:56 -0700639 }
destradaacfbdcd22014-04-30 11:29:11 -0700640 } else {
destradaabeea4422014-07-30 18:17:21 -0700641 flpHardwareProvider = null;
destradaa6b4893a2016-05-03 15:33:43 -0700642 Slog.d(TAG, "FLP HAL not supported");
destradaaf9a274c2014-07-25 15:11:56 -0700643 }
644
645 // bind to geofence provider
646 GeofenceProxy provider = GeofenceProxy.createAndBind(
647 mContext,com.android.internal.R.bool.config_enableGeofenceOverlay,
648 com.android.internal.R.string.config_geofenceProviderPackageName,
649 com.android.internal.R.array.config_locationProviderPackageNames,
650 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700651 mGpsGeofenceProxy,
destradaabeea4422014-07-30 18:17:21 -0700652 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700653 if (provider == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700654 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700655 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900656
destradaa6e2fe752015-06-23 17:25:53 -0700657 // bind to hardware activity recognition
658 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
659 ActivityRecognitionHardware activityRecognitionHardware = null;
660 if (activityRecognitionHardwareIsSupported) {
661 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700662 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700663 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700664 }
destradaa6e2fe752015-06-23 17:25:53 -0700665 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
666 mContext,
667 mLocationHandler,
668 activityRecognitionHardwareIsSupported,
669 activityRecognitionHardware,
670 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
671 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
672 com.android.internal.R.array.config_locationProviderPackageNames);
673 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700674 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700675 }
destradaaa4fa3b52014-07-09 10:46:39 -0700676
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900677 String[] testProviderStrings = resources.getStringArray(
678 com.android.internal.R.array.config_testLocationProviders);
679 for (String testProviderString : testProviderStrings) {
680 String fragments[] = testProviderString.split(",");
681 String name = fragments[0].trim();
682 if (mProvidersByName.get(name) != null) {
683 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
684 }
685 ProviderProperties properties = new ProviderProperties(
686 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
687 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
688 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
689 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
690 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
691 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
692 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
693 Integer.parseInt(fragments[8]) /* powerRequirement */,
694 Integer.parseInt(fragments[9]) /* accuracy */);
695 addTestProviderLocked(name, properties);
696 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700697 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800699 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700700 * Called when the device's active user changes.
701 * @param userId the new active user's UserId
702 */
703 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800704 if (mCurrentUserId == userId) {
705 return;
706 }
Victoria Lease83762d22012-10-03 13:51:17 -0700707 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800708 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700709 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700710 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700711 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700712 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700713 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700714 }
Victoria Lease38389b62012-09-30 11:44:22 -0700715 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700716 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700717 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700718 }
719 }
720
721 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800722 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
723 * location updates.
724 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700725 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700726 final int mUid; // uid of receiver
727 final int mPid; // pid of receiver
728 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700729 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700730
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800731 final ILocationListener mListener;
732 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700733 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700734 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700736
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800737 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700738
David Christie0b837452013-07-29 16:02:13 -0700739 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700740 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700741 // True if app ops has started monitoring this receiver for high power (gps) locations.
742 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700743 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700744 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800745
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700746 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700747 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800749 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700750 if (listener != null) {
751 mKey = listener.asBinder();
752 } else {
753 mKey = intent;
754 }
Victoria Lease37425c32012-10-16 16:08:48 -0700755 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700756 mUid = uid;
757 mPid = pid;
758 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700759 if (workSource != null && workSource.size() <= 0) {
760 workSource = null;
761 }
762 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700763 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700764
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700765 updateMonitoring(true);
766
Victoria Lease0aa28602013-05-29 15:28:26 -0700767 // construct/configure wakelock
768 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700769 if (workSource == null) {
770 workSource = new WorkSource(mUid, mPackageName);
771 }
772 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 }
774
775 @Override
776 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800777 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 }
779
780 @Override
781 public int hashCode() {
782 return mKey.hashCode();
783 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400784
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 @Override
786 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700787 StringBuilder s = new StringBuilder();
788 s.append("Reciever[");
789 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700791 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800792 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700793 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700795 for (String p : mUpdateRecords.keySet()) {
796 s.append(" ").append(mUpdateRecords.get(p).toString());
797 }
798 s.append("]");
799 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 }
801
David Christie15b31912013-08-13 15:54:32 -0700802 /**
803 * Update AppOp monitoring for this receiver.
804 *
805 * @param allow If true receiver is currently active, if false it's been removed.
806 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700807 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700808 if (mHideFromAppOps) {
809 return;
810 }
811
David Christie15b31912013-08-13 15:54:32 -0700812 boolean requestingLocation = false;
813 boolean requestingHighPowerLocation = false;
814 if (allow) {
815 // See if receiver has any enabled update records. Also note if any update records
816 // are high power (has a high power provider with an interval under a threshold).
817 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
818 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
819 requestingLocation = true;
820 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800821 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700822 ProviderProperties properties = locationProvider != null
823 ? locationProvider.getProperties() : null;
824 if (properties != null
825 && properties.mPowerRequirement == Criteria.POWER_HIGH
826 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
827 requestingHighPowerLocation = true;
828 break;
829 }
830 }
831 }
832 }
833
David Christie0b837452013-07-29 16:02:13 -0700834 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700835 mOpMonitoring = updateMonitoring(
836 requestingLocation,
837 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700838 AppOpsManager.OP_MONITOR_LOCATION);
839
840 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700841 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700842 mOpHighPowerMonitoring = updateMonitoring(
843 requestingHighPowerLocation,
844 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700845 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700846 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700847 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700848 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
849 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
850 }
David Christie0b837452013-07-29 16:02:13 -0700851 }
852
853 /**
854 * Update AppOps monitoring for a single location request and op type.
855 *
856 * @param allowMonitoring True if monitoring is allowed for this request/op.
857 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
858 * @param op AppOps code for the op to update.
859 * @return True if monitoring is on for this request/op after updating.
860 */
861 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
862 int op) {
863 if (!currentlyMonitoring) {
864 if (allowMonitoring) {
865 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
866 == AppOpsManager.MODE_ALLOWED;
867 }
868 } else {
869 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
870 != AppOpsManager.MODE_ALLOWED) {
871 mAppOps.finishOp(op, mUid, mPackageName);
872 return false;
873 }
874 }
875
876 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700877 }
878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 public boolean isListener() {
880 return mListener != null;
881 }
882
883 public boolean isPendingIntent() {
884 return mPendingIntent != null;
885 }
886
887 public ILocationListener getListener() {
888 if (mListener != null) {
889 return mListener;
890 }
891 throw new IllegalStateException("Request for non-existent listener");
892 }
893
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800894 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
895 if (mListener != null) {
896 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700897 synchronized (this) {
898 // synchronize to ensure incrementPendingBroadcastsLocked()
899 // is called before decrementPendingBroadcasts()
900 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700901 // call this after broadcasting so we do not increment
902 // if we throw an exeption.
903 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 } catch (RemoteException e) {
906 return false;
907 }
908 } else {
909 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800910 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
912 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700913 synchronized (this) {
914 // synchronize to ensure incrementPendingBroadcastsLocked()
915 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700916 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700917 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700918 // call this after broadcasting so we do not increment
919 // if we throw an exeption.
920 incrementPendingBroadcastsLocked();
921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 } catch (PendingIntent.CanceledException e) {
923 return false;
924 }
925 }
926 return true;
927 }
928
929 public boolean callLocationChangedLocked(Location location) {
930 if (mListener != null) {
931 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700932 synchronized (this) {
933 // synchronize to ensure incrementPendingBroadcastsLocked()
934 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800935 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700936 // call this after broadcasting so we do not increment
937 // if we throw an exeption.
938 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700939 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800940 } catch (RemoteException e) {
941 return false;
942 }
943 } else {
944 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800945 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800946 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700947 synchronized (this) {
948 // synchronize to ensure incrementPendingBroadcastsLocked()
949 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700950 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700951 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700952 // call this after broadcasting so we do not increment
953 // if we throw an exeption.
954 incrementPendingBroadcastsLocked();
955 }
956 } catch (PendingIntent.CanceledException e) {
957 return false;
958 }
959 }
960 return true;
961 }
962
963 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700964 // First update AppOp monitoring.
965 // An app may get/lose location access as providers are enabled/disabled.
966 updateMonitoring(true);
967
Mike Lockwood48f17512009-04-23 09:12:08 -0700968 if (mListener != null) {
969 try {
970 synchronized (this) {
971 // synchronize to ensure incrementPendingBroadcastsLocked()
972 // is called before decrementPendingBroadcasts()
973 if (enabled) {
974 mListener.onProviderEnabled(provider);
975 } else {
976 mListener.onProviderDisabled(provider);
977 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700978 // call this after broadcasting so we do not increment
979 // if we throw an exeption.
980 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700981 }
982 } catch (RemoteException e) {
983 return false;
984 }
985 } else {
986 Intent providerIntent = new Intent();
987 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
988 try {
989 synchronized (this) {
990 // synchronize to ensure incrementPendingBroadcastsLocked()
991 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700992 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700993 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700994 // call this after broadcasting so we do not increment
995 // if we throw an exeption.
996 incrementPendingBroadcastsLocked();
997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 } catch (PendingIntent.CanceledException e) {
999 return false;
1000 }
1001 }
1002 return true;
1003 }
1004
Nick Pellyf1be6862012-05-15 10:53:42 -07001005 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001007 if (D) Log.d(TAG, "Location listener died");
1008
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001009 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001010 removeUpdatesLocked(this);
1011 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001012 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001013 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001014 }
1015 }
1016
Nick Pellye0fd6932012-07-11 10:26:13 -07001017 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001018 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1019 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001020 synchronized (this) {
1021 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001022 }
1023 }
1024
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001025 // this must be called while synchronized by caller in a synchronized block
1026 // containing the sending of the broadcaset
1027 private void incrementPendingBroadcastsLocked() {
1028 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001029 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001030 }
1031 }
1032
1033 private void decrementPendingBroadcastsLocked() {
1034 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001035 if (mWakeLock.isHeld()) {
1036 mWakeLock.release();
1037 }
1038 }
1039 }
1040
1041 public void clearPendingBroadcastsLocked() {
1042 if (mPendingBroadcasts > 0) {
1043 mPendingBroadcasts = 0;
1044 if (mWakeLock.isHeld()) {
1045 mWakeLock.release();
1046 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001047 }
1048 }
1049 }
1050
Nick Pellye0fd6932012-07-11 10:26:13 -07001051 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001052 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001053 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001054 //the receiver list if it is not found. If it is not found then the
1055 //LocationListener was removed when it had a pending broadcast and should
1056 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001057 synchronized (mLock) {
1058 IBinder binder = listener.asBinder();
1059 Receiver receiver = mReceivers.get(binder);
1060 if (receiver != null) {
1061 synchronized (receiver) {
1062 // so wakelock calls will succeed
1063 long identity = Binder.clearCallingIdentity();
1064 receiver.decrementPendingBroadcastsLocked();
1065 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001066 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 }
1069 }
1070
Lifu Tang82f893d2016-01-21 18:15:33 -08001071 /**
Lifu Tang9363b942016-02-16 18:07:00 -08001072 * Returns the system information of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001073 */
1074 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001075 public int getGnssYearOfHardware() {
Lifu Tang818aa2c2016-02-01 01:52:00 -08001076 if (mGnssNavigationMessageProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001077 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001078 } else {
1079 return 0;
1080 }
1081 }
1082
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001083 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001084 mProviders.add(provider);
1085 mProvidersByName.put(provider.getName(), provider);
1086 }
1087
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001088 private void removeProviderLocked(LocationProviderInterface provider) {
1089 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001090 mProviders.remove(provider);
1091 mProvidersByName.remove(provider.getName());
1092 }
1093
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001094 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001095 * Returns "true" if access to the specified location provider is allowed by the current
1096 * user's settings. Access to all location providers is forbidden to non-location-provider
1097 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001098 *
1099 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001100 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001101 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 if (mEnabledProviders.contains(provider)) {
1103 return true;
1104 }
1105 if (mDisabledProviders.contains(provider)) {
1106 return false;
1107 }
1108 // Use system settings
1109 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110
Victoria Leaseb711d572012-10-02 13:14:11 -07001111 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001112 }
1113
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001114 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001115 * Returns "true" if access to the specified location provider is allowed by the specified
1116 * user's settings. Access to all location providers is forbidden to non-location-provider
1117 * processes belonging to background users.
1118 *
1119 * @param provider the name of the location provider
1120 * @param uid the requestor's UID
Victoria Lease09eeaec2013-02-05 11:34:13 -08001121 */
1122 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001123 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001124 return false;
1125 }
1126 return isAllowedByCurrentUserSettingsLocked(provider);
1127 }
1128
1129 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001130 * Returns the permission string associated with the specified resolution level.
1131 *
1132 * @param resolutionLevel the resolution level
1133 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001134 */
Victoria Lease37425c32012-10-16 16:08:48 -07001135 private String getResolutionPermission(int resolutionLevel) {
1136 switch (resolutionLevel) {
1137 case RESOLUTION_LEVEL_FINE:
1138 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1139 case RESOLUTION_LEVEL_COARSE:
1140 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1141 default:
1142 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001144 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001145
Victoria Leaseda479c52012-10-15 15:24:16 -07001146 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001147 * Returns the resolution level allowed to the given PID/UID pair.
1148 *
1149 * @param pid the PID
1150 * @param uid the UID
1151 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001152 */
Victoria Lease37425c32012-10-16 16:08:48 -07001153 private int getAllowedResolutionLevel(int pid, int uid) {
1154 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1155 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1156 return RESOLUTION_LEVEL_FINE;
1157 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1158 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1159 return RESOLUTION_LEVEL_COARSE;
1160 } else {
1161 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001162 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001163 }
1164
1165 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001166 * Returns the resolution level allowed to the caller
1167 *
1168 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001169 */
Victoria Lease37425c32012-10-16 16:08:48 -07001170 private int getCallerAllowedResolutionLevel() {
1171 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1172 }
1173
1174 /**
1175 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1176 *
1177 * @param allowedResolutionLevel resolution level allowed to caller
1178 */
1179 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1180 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001181 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
1184
Victoria Lease37425c32012-10-16 16:08:48 -07001185 /**
1186 * Return the minimum resolution level required to use the specified location provider.
1187 *
1188 * @param provider the name of the location provider
1189 * @return minimum resolution level required for provider
1190 */
1191 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001192 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1193 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1194 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001195 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001196 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1197 LocationManager.FUSED_PROVIDER.equals(provider)) {
1198 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001199 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001200 } else {
1201 // mock providers
1202 LocationProviderInterface lp = mMockProviders.get(provider);
1203 if (lp != null) {
1204 ProviderProperties properties = lp.getProperties();
1205 if (properties != null) {
1206 if (properties.mRequiresSatellite) {
1207 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001208 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001209 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1210 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001211 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001212 }
1213 }
1214 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001215 }
Victoria Lease37425c32012-10-16 16:08:48 -07001216 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001217 }
1218
Victoria Lease37425c32012-10-16 16:08:48 -07001219 /**
1220 * Throw SecurityException if specified resolution level is insufficient to use the named
1221 * location provider.
1222 *
1223 * @param allowedResolutionLevel resolution level allowed to caller
1224 * @param providerName the name of the location provider
1225 */
1226 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1227 String providerName) {
1228 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1229 if (allowedResolutionLevel < requiredResolutionLevel) {
1230 switch (requiredResolutionLevel) {
1231 case RESOLUTION_LEVEL_FINE:
1232 throw new SecurityException("\"" + providerName + "\" location provider " +
1233 "requires ACCESS_FINE_LOCATION permission.");
1234 case RESOLUTION_LEVEL_COARSE:
1235 throw new SecurityException("\"" + providerName + "\" location provider " +
1236 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1237 default:
1238 throw new SecurityException("Insufficient permission for \"" + providerName +
1239 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001240 }
1241 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001242 }
1243
David Christie82edc9b2013-07-19 11:31:42 -07001244 /**
1245 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1246 * for battery).
1247 */
David Christie40e57822013-07-30 11:36:48 -07001248 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001249 mContext.enforceCallingOrSelfPermission(
1250 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1251 }
1252
David Christie40e57822013-07-30 11:36:48 -07001253 private void checkUpdateAppOpsAllowed() {
1254 mContext.enforceCallingOrSelfPermission(
1255 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1256 }
1257
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001258 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001259 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1260 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001261 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001262 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001263 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001264 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001265 }
1266 return -1;
1267 }
1268
David Christieb870dbf2015-06-22 12:42:53 -07001269 boolean reportLocationAccessNoThrow(
1270 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001271 int op = resolutionLevelToOp(allowedResolutionLevel);
1272 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001273 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1274 return false;
1275 }
1276 }
David Christieb870dbf2015-06-22 12:42:53 -07001277
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001278 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001279 }
1280
David Christieb870dbf2015-06-22 12:42:53 -07001281 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001282 int op = resolutionLevelToOp(allowedResolutionLevel);
1283 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001284 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1285 return false;
1286 }
1287 }
David Christieb870dbf2015-06-22 12:42:53 -07001288
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001289 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001290 }
1291
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001292 /**
1293 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001294 * fused, also including ones that are not permitted to
1295 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001296 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001297 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001299 ArrayList<String> out;
1300 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001301 out = new ArrayList<>(mProviders.size());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001302 for (LocationProviderInterface provider : mProviders) {
1303 String name = provider.getName();
1304 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001305 continue;
1306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 out.add(name);
1308 }
1309 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001310
1311 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 return out;
1313 }
1314
Mike Lockwood03ca2162010-04-01 08:10:09 -07001315 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001316 * Return all providers by name, that match criteria and are optionally
1317 * enabled.
1318 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001319 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001320 @Override
1321 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001322 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001323 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001324 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001325 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001326 try {
1327 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001328 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001329 for (LocationProviderInterface provider : mProviders) {
1330 String name = provider.getName();
1331 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001332 continue;
1333 }
Victoria Lease37425c32012-10-16 16:08:48 -07001334 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001335 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001336 continue;
1337 }
1338 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1339 name, provider.getProperties(), criteria)) {
1340 continue;
1341 }
1342 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001343 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001344 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001345 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001346 } finally {
1347 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001348 }
1349
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001350 if (D) Log.d(TAG, "getProviders()=" + out);
1351 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001352 }
1353
1354 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001355 * Return the name of the best provider given a Criteria object.
1356 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001357 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001358 * has been deprecated as well. So this method now uses
1359 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001360 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001361 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001362 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001363 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001364
1365 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001366 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001367 result = pickBest(providers);
1368 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1369 return result;
1370 }
1371 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001372 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001373 result = pickBest(providers);
1374 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1375 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001376 }
1377
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001378 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001379 return null;
1380 }
1381
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001382 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001383 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001384 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001385 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1386 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001387 } else {
1388 return providers.get(0);
1389 }
1390 }
1391
Nick Pellye0fd6932012-07-11 10:26:13 -07001392 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001393 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1394 LocationProviderInterface p = mProvidersByName.get(provider);
1395 if (p == null) {
1396 throw new IllegalArgumentException("provider=" + provider);
1397 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001398
1399 boolean result = LocationProvider.propertiesMeetCriteria(
1400 p.getName(), p.getProperties(), criteria);
1401 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1402 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001403 }
1404
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001406 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001407 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001408 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 boolean isEnabled = p.isEnabled();
1410 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001411 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001413 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001414 // If any provider has been disabled, clear all last locations for all providers.
1415 // This is to be on the safe side in case a provider has location derived from
1416 // this disabled provider.
1417 mLastLocation.clear();
1418 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001419 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001421 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001422 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001424 }
1425 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001426 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1427 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001428 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1429 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
1431 }
1432
Amith Yamasanib27528d2014-06-05 15:02:10 -07001433 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 int listeners = 0;
1435
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001436 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001437 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438
1439 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001440
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1442 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001443 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001444 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001445 // Sends a notification message to the receiver
1446 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1447 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001448 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001449 }
1450 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001452 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001453 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001454 }
1455 }
1456
1457 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001458 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 removeUpdatesLocked(deadReceivers.get(i));
1460 }
1461 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 if (enabled) {
1464 p.enable();
1465 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001466 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001473 private void applyRequirementsLocked(String provider) {
1474 LocationProviderInterface p = mProvidersByName.get(provider);
1475 if (p == null) return;
1476
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001477 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001478 WorkSource worksource = new WorkSource();
1479 ProviderRequest providerRequest = new ProviderRequest();
1480
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001481 ContentResolver resolver = mContext.getContentResolver();
1482 long backgroundThrottleInterval = Settings.Global.getLong(
1483 resolver,
1484 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1485 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
1486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001488 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001489 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001490 if (checkLocationAccess(
1491 record.mReceiver.mPid,
1492 record.mReceiver.mUid,
1493 record.mReceiver.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001494 record.mReceiver.mAllowedResolutionLevel)) {
1495 LocationRequest locationRequest = record.mRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001496 long interval = locationRequest.getInterval();
1497
1498 if (!isThrottlingExemptLocked(record.mReceiver)) {
1499 if (!record.mIsForegroundUid) {
1500 interval = Math.max(interval, backgroundThrottleInterval);
1501 }
1502 if (interval != locationRequest.getInterval()) {
1503 locationRequest = new LocationRequest(locationRequest);
1504 locationRequest.setInterval(interval);
1505 }
1506 }
1507
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001508 providerRequest.locationRequests.add(locationRequest);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001509 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001510 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001511 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001512 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001513 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001514 }
1515 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001516
1517 if (providerRequest.reportLocation) {
1518 // calculate who to blame for power
1519 // This is somewhat arbitrary. We pick a threshold interval
1520 // that is slightly higher that the minimum interval, and
1521 // spread the blame across all applications with a request
1522 // under that threshold.
1523 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1524 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001525 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001526 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001527
1528 // Don't assign battery blame for update records whose
1529 // client has no permission to receive location data.
1530 if (!providerRequest.locationRequests.contains(locationRequest)) {
1531 continue;
1532 }
1533
Victoria Leaseb711d572012-10-02 13:14:11 -07001534 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001535 if (record.mReceiver.mWorkSource != null
1536 && record.mReceiver.mWorkSource.size() > 0
1537 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001538 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001539 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001540 worksource.add(record.mReceiver.mWorkSource);
1541 } else {
1542 // Assign blame to caller.
1543 worksource.add(
1544 record.mReceiver.mUid,
1545 record.mReceiver.mPackageName);
1546 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001547 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001548 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001549 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001550 }
1551 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001552
1553 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1554 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001557 private boolean isThrottlingExemptLocked(Receiver receiver) {
1558 if (receiver.mUid == Process.SYSTEM_UID) {
1559 return true;
1560 }
1561
1562 if (receiver.mPackageName.equals(GMSCORE_PACKAGE)) {
1563 return true;
1564 }
1565
1566 for (LocationProviderProxy provider : mProxyProviders) {
1567 if (receiver.mPackageName.equals(provider.getConnectedPackageName())) {
1568 return true;
1569 }
1570 }
1571
1572 for (String whitelistedPackage : mBackgroundThrottlePackageWhitelist) {
1573 if (receiver.mPackageName.equals(whitelistedPackage)) {
1574 return true;
1575 }
1576 }
1577
1578 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001579 }
1580
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001581 private class UpdateRecord {
1582 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001583 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001585 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001586 Location mLastFixBroadcast;
1587 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588
1589 /**
1590 * Note: must be constructed with lock held.
1591 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001592 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001594 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001596 mIsForegroundUid = isImportanceForeground(
1597 mActivityManager.getPackageImportance(mReceiver.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598
1599 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1600 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001601 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 mRecordsByProvider.put(provider, records);
1603 }
1604 if (!records.contains(this)) {
1605 records.add(this);
1606 }
David Christie2ff96af2014-01-30 16:09:37 -08001607
1608 // Update statistics for historical location requests by package/provider
1609 mRequestStatistics.startRequesting(
1610 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
1613 /**
David Christie2ff96af2014-01-30 16:09:37 -08001614 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001615 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001616 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001617 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1618
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001619 // remove from mRecordsByProvider
1620 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1621 if (globalRecords != null) {
1622 globalRecords.remove(this);
1623 }
1624
1625 if (!removeReceiver) return; // the caller will handle the rest
1626
1627 // remove from Receiver#mUpdateRecords
1628 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1629 if (receiverRecords != null) {
1630 receiverRecords.remove(this.mProvider);
1631
1632 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001633 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001634 removeUpdatesLocked(mReceiver);
1635 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
1639 @Override
1640 public String toString() {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001641 return "UpdateRecord[" + mProvider + " " + mReceiver.mPackageName
1642 + "(" + mReceiver.mUid + (mIsForegroundUid ? " foreground" : " background")
1643 + ")" + " " + mRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001647 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001648 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001649 IBinder binder = listener.asBinder();
1650 Receiver receiver = mReceivers.get(binder);
1651 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001652 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1653 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001654 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001655 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001656 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001657 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001658 return null;
1659 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001660 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001661 }
1662 return receiver;
1663 }
1664
David Christie82edc9b2013-07-19 11:31:42 -07001665 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001666 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001667 Receiver receiver = mReceivers.get(intent);
1668 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001669 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1670 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001671 mReceivers.put(intent, receiver);
1672 }
1673 return receiver;
1674 }
1675
Victoria Lease37425c32012-10-16 16:08:48 -07001676 /**
1677 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1678 * and consistency requirements.
1679 *
1680 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001681 * @return a version of request that meets the given resolution and consistency requirements
1682 * @hide
1683 */
1684 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1685 LocationRequest sanitizedRequest = new LocationRequest(request);
1686 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1687 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001688 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001689 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001690 break;
1691 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001692 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001693 break;
1694 }
1695 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001696 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1697 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001698 }
Victoria Lease37425c32012-10-16 16:08:48 -07001699 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1700 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001701 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001702 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001703 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001704 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001705 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001706 }
Victoria Lease37425c32012-10-16 16:08:48 -07001707 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001708 }
1709
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001710 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001711 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001712 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001713 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001714 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001715 String[] packages = mPackageManager.getPackagesForUid(uid);
1716 if (packages == null) {
1717 throw new SecurityException("invalid UID " + uid);
1718 }
1719 for (String pkg : packages) {
1720 if (packageName.equals(pkg)) return;
1721 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001722 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001723 }
1724
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001725 private void checkPendingIntent(PendingIntent intent) {
1726 if (intent == null) {
1727 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001728 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001729 }
1730
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001731 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001732 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001733 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001734 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001735 } else if (intent != null && listener != null) {
1736 throw new IllegalArgumentException("cannot register both listener and intent");
1737 } else if (intent != null) {
1738 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001739 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001740 } else {
David Christie40e57822013-07-30 11:36:48 -07001741 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001742 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001743 }
1744
Nick Pellye0fd6932012-07-11 10:26:13 -07001745 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001746 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1747 PendingIntent intent, String packageName) {
1748 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1749 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001750 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1751 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1752 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07001753 WorkSource workSource = request.getWorkSource();
1754 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07001755 checkDeviceStatsAllowed();
1756 }
1757 boolean hideFromAppOps = request.getHideFromAppOps();
1758 if (hideFromAppOps) {
1759 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07001760 }
Victoria Lease37425c32012-10-16 16:08:48 -07001761 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001763 final int pid = Binder.getCallingPid();
1764 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001765 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 long identity = Binder.clearCallingIdentity();
1767 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001768 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1769 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07001770 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001771
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001772 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001773 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07001774 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07001775 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 } finally {
1778 Binder.restoreCallingIdentity(identity);
1779 }
1780 }
1781
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001782 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1783 int pid, int uid, String packageName) {
1784 // Figure out the provider. Either its explicitly request (legacy use cases), or
1785 // use the fused provider
1786 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1787 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001788 if (name == null) {
1789 throw new IllegalArgumentException("provider name must not be null");
1790 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001791
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001792 LocationProviderInterface provider = mProvidersByName.get(name);
1793 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07001794 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001795 }
1796
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001797 UpdateRecord record = new UpdateRecord(name, request, receiver);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001798 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1799 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
1800 + (record.mIsForegroundUid ? "foreground" : "background")
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001801 + (isThrottlingExemptLocked(receiver) ? " [whitelisted]" : "") + ")");
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001802
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001803 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1804 if (oldRecord != null) {
1805 oldRecord.disposeLocked(false);
1806 }
1807
Victoria Lease09eeaec2013-02-05 11:34:13 -08001808 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001809 if (isProviderEnabled) {
1810 applyRequirementsLocked(name);
1811 } else {
1812 // Notify the listener that updates are currently disabled
1813 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
David Christie0b837452013-07-29 16:02:13 -07001815 // Update the monitoring here just in case multiple location requests were added to the
1816 // same receiver (this request may be high power and the initial might not have been).
1817 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 }
1819
Nick Pellye0fd6932012-07-11 10:26:13 -07001820 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001821 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1822 String packageName) {
1823 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001824
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001825 final int pid = Binder.getCallingPid();
1826 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001827
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001828 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07001829 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07001830 boolean hideFromAppOps = false;
1831 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
1832 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001833
1834 // providers may use public location API's, need to clear identity
1835 long identity = Binder.clearCallingIdentity();
1836 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001837 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001838 } finally {
1839 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 }
1842 }
1843
1844 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001845 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001846
1847 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1848 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1849 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001850 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
1853
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07001854 receiver.updateMonitoring(false);
1855
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001856 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001857 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001858 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1859 if (oldRecords != null) {
1860 // Call dispose() on the obsolete update records.
1861 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08001862 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001863 record.disposeLocked(false);
1864 }
1865 // Accumulate providers
1866 providers.addAll(oldRecords.keySet());
1867 }
1868
1869 // update provider
1870 for (String provider : providers) {
1871 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001872 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001873 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001874 }
1875
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001876 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001877 }
1878 }
1879
Dianne Hackbornc2293022013-02-06 23:14:49 -08001880 private void applyAllProviderRequirementsLocked() {
1881 for (LocationProviderInterface p : mProviders) {
1882 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001883 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001884 continue;
1885 }
1886
1887 applyRequirementsLocked(p.getName());
1888 }
1889 }
1890
Nick Pellye0fd6932012-07-11 10:26:13 -07001891 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001892 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001893 if (D) Log.d(TAG, "getLastLocation: " + request);
1894 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001895 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001896 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001897 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1898 request.getProvider());
1899 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001900
David Christieb870dbf2015-06-22 12:42:53 -07001901 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001902 final int uid = Binder.getCallingUid();
1903 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001904 try {
1905 if (mBlacklist.isBlacklisted(packageName)) {
1906 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1907 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001908 return null;
1909 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001910
David Christieb870dbf2015-06-22 12:42:53 -07001911 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001912 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1913 packageName);
1914 return null;
1915 }
1916
Victoria Leaseb711d572012-10-02 13:14:11 -07001917 synchronized (mLock) {
1918 // Figure out the provider. Either its explicitly request (deprecated API's),
1919 // or use the fused provider
1920 String name = request.getProvider();
1921 if (name == null) name = LocationManager.FUSED_PROVIDER;
1922 LocationProviderInterface provider = mProvidersByName.get(name);
1923 if (provider == null) return null;
1924
Victoria Lease09eeaec2013-02-05 11:34:13 -08001925 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001926
David Christie1b9b7b12013-04-15 15:31:11 -07001927 Location location;
1928 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1929 // Make sure that an app with coarse permissions can't get frequent location
1930 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1931 location = mLastLocationCoarseInterval.get(name);
1932 } else {
1933 location = mLastLocation.get(name);
1934 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001935 if (location == null) {
1936 return null;
1937 }
Victoria Lease37425c32012-10-16 16:08:48 -07001938 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001939 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1940 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001941 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001942 }
Victoria Lease37425c32012-10-16 16:08:48 -07001943 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001944 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001945 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001946 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001947 return null;
1948 } finally {
1949 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001950 }
1951 }
1952
1953 @Override
1954 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1955 String packageName) {
1956 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001957 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1958 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001959 checkPendingIntent(intent);
1960 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001961 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1962 request.getProvider());
1963 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001964
Victoria Lease37425c32012-10-16 16:08:48 -07001965 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001966
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001967 // geo-fence manager uses the public location API, need to clear identity
1968 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07001969 // TODO: http://b/23822629
1970 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08001971 // temporary measure until geofences work for secondary users
1972 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1973 return;
1974 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001975 long identity = Binder.clearCallingIdentity();
1976 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001977 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1978 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001979 } finally {
1980 Binder.restoreCallingIdentity(identity);
1981 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001982 }
1983
1984 @Override
1985 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001986 checkPendingIntent(intent);
1987 checkPackageName(packageName);
1988
1989 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1990
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001991 // geo-fence manager uses the public location API, need to clear identity
1992 long identity = Binder.clearCallingIdentity();
1993 try {
1994 mGeofenceManager.removeFence(geofence, intent);
1995 } finally {
1996 Binder.restoreCallingIdentity(identity);
1997 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001998 }
1999
2000
2001 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002002 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08002003 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2004 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07002005 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006
David Christieb870dbf2015-06-22 12:42:53 -07002007 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002008 final int uid = Binder.getCallingUid();
2009 final long ident = Binder.clearCallingIdentity();
2010 try {
David Christieb870dbf2015-06-22 12:42:53 -07002011 if (!checkLocationAccess(pid, uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002012 return false;
2013 }
2014 } finally {
2015 Binder.restoreCallingIdentity(ident);
2016 }
2017
Lifu Tang30f95a72016-01-07 23:20:38 -08002018 if (mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002019 return false;
2020 }
2021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002023 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002025 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 return false;
2027 }
2028 return true;
2029 }
2030
Nick Pellye0fd6932012-07-11 10:26:13 -07002031 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002032 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002033 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002034 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002035 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002036 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002037 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002038 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002039 }
2040 }
2041
Nick Pellye0fd6932012-07-11 10:26:13 -07002042 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002043 public boolean addGnssMeasurementsListener(
2044 IGnssMeasurementsListener listener,
destradaaea8a8a62014-06-23 18:19:03 -07002045 String packageName) {
2046 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2047 checkResolutionLevelIsSufficientForProviderUse(
2048 allowedResolutionLevel,
2049 LocationManager.GPS_PROVIDER);
2050
David Christieb870dbf2015-06-22 12:42:53 -07002051 int pid = Binder.getCallingPid();
destradaaea8a8a62014-06-23 18:19:03 -07002052 int uid = Binder.getCallingUid();
2053 long identity = Binder.clearCallingIdentity();
2054 boolean hasLocationAccess;
2055 try {
David Christieb870dbf2015-06-22 12:42:53 -07002056 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
destradaaea8a8a62014-06-23 18:19:03 -07002057 } finally {
2058 Binder.restoreCallingIdentity(identity);
2059 }
2060
Lifu Tang818aa2c2016-02-01 01:52:00 -08002061 if (!hasLocationAccess || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002062 return false;
2063 }
Lifu Tang818aa2c2016-02-01 01:52:00 -08002064 return mGnssMeasurementsProvider.addListener(listener);
destradaaea8a8a62014-06-23 18:19:03 -07002065 }
2066
2067 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002068 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2069 if (mGnssMeasurementsProvider != null) {
2070 mGnssMeasurementsProvider.removeListener(listener);
Wei Liu5241a4c2015-05-11 14:00:36 -07002071 }
destradaaea8a8a62014-06-23 18:19:03 -07002072 }
2073
2074 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002075 public boolean addGnssNavigationMessageListener(
2076 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002077 String packageName) {
2078 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2079 checkResolutionLevelIsSufficientForProviderUse(
2080 allowedResolutionLevel,
2081 LocationManager.GPS_PROVIDER);
2082
David Christieb870dbf2015-06-22 12:42:53 -07002083 int pid = Binder.getCallingPid();
destradaa4b3e3932014-07-21 18:01:47 -07002084 int uid = Binder.getCallingUid();
2085 long identity = Binder.clearCallingIdentity();
2086 boolean hasLocationAccess;
2087 try {
David Christieb870dbf2015-06-22 12:42:53 -07002088 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
destradaa4b3e3932014-07-21 18:01:47 -07002089 } finally {
2090 Binder.restoreCallingIdentity(identity);
2091 }
2092
Lifu Tang818aa2c2016-02-01 01:52:00 -08002093 if (!hasLocationAccess || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002094 return false;
2095 }
Lifu Tang818aa2c2016-02-01 01:52:00 -08002096 return mGnssNavigationMessageProvider.addListener(listener);
destradaa4b3e3932014-07-21 18:01:47 -07002097 }
2098
2099 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002100 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2101 if (mGnssNavigationMessageProvider != null) {
2102 mGnssNavigationMessageProvider.removeListener(listener);
Wei Liu5241a4c2015-05-11 14:00:36 -07002103 }
destradaa4b3e3932014-07-21 18:01:47 -07002104 }
2105
2106 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002108 if (provider == null) {
2109 // throw NullPointerException to remain compatible with previous implementation
2110 throw new NullPointerException();
2111 }
Victoria Lease37425c32012-10-16 16:08:48 -07002112 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2113 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002114
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002115 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002116 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 != PackageManager.PERMISSION_GRANTED)) {
2118 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2119 }
2120
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002121 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002122 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002123 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002124
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002125 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 }
2127 }
2128
Nick Pellye0fd6932012-07-11 10:26:13 -07002129 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002130 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002131 if (Binder.getCallingUid() != Process.myUid()) {
2132 throw new SecurityException(
2133 "calling sendNiResponse from outside of the system is not allowed");
2134 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002135 try {
2136 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002137 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002138 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002139 return false;
2140 }
2141 }
2142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002143 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002144 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002145 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 * accessed by the caller
2147 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002148 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002149 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002150 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002151 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002152 }
2153
Victoria Lease37425c32012-10-16 16:08:48 -07002154 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2155 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002157 LocationProviderInterface p;
2158 synchronized (mLock) {
2159 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002160 }
2161
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002162 if (p == null) return null;
2163 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002164 }
2165
Jason Monkb71218a2015-06-17 14:44:39 -04002166 /**
2167 * @return null if the provider does not exist
2168 * @throws SecurityException if the provider is not allowed to be
2169 * accessed by the caller
2170 */
2171 @Override
2172 public String getNetworkProviderPackage() {
2173 LocationProviderInterface p;
2174 synchronized (mLock) {
2175 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2176 return null;
2177 }
2178 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2179 }
2180
2181 if (p instanceof LocationProviderProxy) {
2182 return ((LocationProviderProxy) p).getConnectedPackageName();
2183 }
2184 return null;
2185 }
2186
Nick Pellye0fd6932012-07-11 10:26:13 -07002187 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002188 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07002189 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2190 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002191 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2192
Victoria Lease09eeaec2013-02-05 11:34:13 -08002193 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002194 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002195 try {
2196 synchronized (mLock) {
2197 LocationProviderInterface p = mProvidersByName.get(provider);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002198 return p != null && isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07002199 }
2200 } finally {
2201 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002202 }
2203 }
2204
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002205 /**
2206 * Returns "true" if the UID belongs to a bound location provider.
2207 *
2208 * @param uid the uid
2209 * @return true if uid belongs to a bound location provider
2210 */
2211 private boolean isUidALocationProvider(int uid) {
2212 if (uid == Process.SYSTEM_UID) {
2213 return true;
2214 }
2215 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002216 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002217 }
2218 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002219 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002220 }
2221 return false;
2222 }
2223
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002224 private void checkCallerIsProvider() {
2225 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
2226 == PackageManager.PERMISSION_GRANTED) {
2227 return;
2228 }
2229
2230 // Previously we only used the INSTALL_LOCATION_PROVIDER
2231 // check. But that is system or signature
2232 // protection level which is not flexible enough for
2233 // providers installed oustide the system image. So
2234 // also allow providers with a UID matching the
2235 // currently bound package name
2236
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002237 if (isUidALocationProvider(Binder.getCallingUid())) {
2238 return;
2239 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002240
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002241 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2242 "or UID of a currently bound location provider");
2243 }
2244
David Christie1f141c12014-05-14 15:11:15 -07002245 /**
2246 * Returns true if the given package belongs to the given uid.
2247 */
2248 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002249 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 return false;
2251 }
David Christie1f141c12014-05-14 15:11:15 -07002252 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2253 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002254 return false;
2255 }
David Christie1f141c12014-05-14 15:11:15 -07002256 for (String name : packageNames) {
2257 if (packageName.equals(name)) {
2258 return true;
2259 }
2260 }
2261 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 }
2263
Nick Pellye0fd6932012-07-11 10:26:13 -07002264 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002265 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002266 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002267
Nick Pelly2eeeec22012-07-18 13:13:37 -07002268 if (!location.isComplete()) {
2269 Log.w(TAG, "Dropping incomplete location: " + location);
2270 return;
2271 }
2272
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002273 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2274 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002275 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002276 mLocationHandler.sendMessageAtFrontOfQueue(m);
2277 }
2278
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002279
Laurent Tu75defb62012-11-01 16:21:52 -07002280 private static boolean shouldBroadcastSafe(
2281 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002282 // Always broadcast the first update
2283 if (lastLoc == null) {
2284 return true;
2285 }
2286
Nick Pellyf1be6862012-05-15 10:53:42 -07002287 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002288 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002289 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2290 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002291 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 return false;
2293 }
2294
2295 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002296 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002297 if (minDistance > 0.0) {
2298 if (loc.distanceTo(lastLoc) <= minDistance) {
2299 return false;
2300 }
2301 }
2302
Laurent Tu75defb62012-11-01 16:21:52 -07002303 // Check whether sufficient number of udpates is left
2304 if (record.mRequest.getNumUpdates() <= 0) {
2305 return false;
2306 }
2307
2308 // Check whether the expiry date has passed
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002309 return record.mRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 }
2311
Mike Lockwooda4903f22010-02-17 06:42:23 -05002312 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002313 if (D) Log.d(TAG, "incoming location: " + location);
2314
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002315 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002316 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317
Laurent Tu60ec50a2012-10-04 17:00:10 -07002318 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002319 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002320 if (p == null) return;
2321
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002322 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002323 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002324 Location lastNoGPSLocation;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002325 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002326 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002327 lastLocation = new Location(provider);
2328 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002329 } else {
2330 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2331 if (noGPSLocation == null && lastNoGPSLocation != null) {
2332 // New location has no no-GPS location: adopt last no-GPS location. This is set
2333 // directly into location because we do not want to notify COARSE clients.
2334 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2335 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002336 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002337 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338
David Christie1b9b7b12013-04-15 15:31:11 -07002339 // Update last known coarse interval location if enough time has passed.
2340 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2341 if (lastLocationCoarseInterval == null) {
2342 lastLocationCoarseInterval = new Location(location);
2343 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2344 }
2345 long timeDiffNanos = location.getElapsedRealtimeNanos()
2346 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2347 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2348 lastLocationCoarseInterval.set(location);
2349 }
2350 // Don't ever return a coarse location that is more recent than the allowed update
2351 // interval (i.e. don't allow an app to keep registering and unregistering for
2352 // location updates to overcome the minimum interval).
2353 noGPSLocation =
2354 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2355
Laurent Tu60ec50a2012-10-04 17:00:10 -07002356 // Skip if there are no UpdateRecords for this provider.
2357 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2358 if (records == null || records.size() == 0) return;
2359
Victoria Lease09016ab2012-09-16 12:33:15 -07002360 // Fetch coarse location
2361 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002362 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002363 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2364 }
2365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 // Fetch latest status update time
2367 long newStatusUpdateTime = p.getStatusUpdateTime();
2368
David Christie2ff96af2014-01-30 16:09:37 -08002369 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002370 Bundle extras = new Bundle();
2371 int status = p.getStatus(extras);
2372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002373 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002374 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002375
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002377 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002379 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002380
Victoria Lease269518e2012-10-29 08:25:39 -07002381 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002382 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002383 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002384 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002385 " (current user: " + mCurrentUserId + ", app: " +
2386 receiver.mPackageName + ")");
2387 }
2388 continue;
2389 }
2390
Nick Pelly4035f5a2012-08-17 14:43:49 -07002391 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2392 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2393 receiver.mPackageName);
2394 continue;
2395 }
2396
David Christieb870dbf2015-06-22 12:42:53 -07002397 if (!reportLocationAccessNoThrow(receiver.mPid, receiver.mUid, receiver.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002398 receiver.mAllowedResolutionLevel)) {
2399 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2400 receiver.mPackageName);
2401 continue;
2402 }
2403
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002404 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002405 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2406 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002407 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002408 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002409 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002410 if (notifyLocation != null) {
2411 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002412 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002413 if (lastLoc == null) {
2414 lastLoc = new Location(notifyLocation);
2415 r.mLastFixBroadcast = lastLoc;
2416 } else {
2417 lastLoc.set(notifyLocation);
2418 }
2419 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2420 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2421 receiverDead = true;
2422 }
Laurent Tu75defb62012-11-01 16:21:52 -07002423 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 }
2425 }
2426
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002427 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002429 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002431 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002432 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002433 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002434 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002435 }
2436 }
2437
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002438 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002439 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002440 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002441 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002442 }
2443 deadUpdateRecords.add(r);
2444 }
2445 // track dead receivers
2446 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002447 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002448 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07002449 }
2450 if (!deadReceivers.contains(receiver)) {
2451 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002452 }
2453 }
2454 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002455
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002456 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002458 for (Receiver receiver : deadReceivers) {
2459 removeUpdatesLocked(receiver);
2460 }
2461 }
2462 if (deadUpdateRecords != null) {
2463 for (UpdateRecord r : deadUpdateRecords) {
2464 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002466 applyRequirementsLocked(provider);
2467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 }
2469
2470 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002471 public LocationWorkerHandler(Looper looper) {
2472 super(looper, null, true);
2473 }
2474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002475 @Override
2476 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002477 switch (msg.what) {
2478 case MSG_LOCATION_CHANGED:
2479 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2480 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 }
2482 }
2483 }
2484
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002485 private boolean isMockProvider(String provider) {
2486 synchronized (mLock) {
2487 return mMockProviders.containsKey(provider);
2488 }
2489 }
2490
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002491 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002492 // create a working copy of the incoming Location so that the service can modify it without
2493 // disturbing the caller's copy
2494 Location myLocation = new Location(location);
2495 String provider = myLocation.getProvider();
2496
2497 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2498 // bit if location did not come from a mock provider because passive/fused providers can
2499 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2500 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2501 myLocation.setIsFromMockProvider(true);
2502 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002503
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002504 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002505 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2506 if (!passive) {
2507 // notify passive provider of the new location
2508 mPassiveProvider.updateLocation(myLocation);
2509 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002510 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002511 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002512 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002513 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514
Mike Lockwoode97ae402010-09-29 15:23:46 -04002515 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2516 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002517 public void onPackageDisappeared(String packageName, int reason) {
2518 // remove all receivers associated with this package name
2519 synchronized (mLock) {
2520 ArrayList<Receiver> deadReceivers = null;
2521
2522 for (Receiver receiver : mReceivers.values()) {
2523 if (receiver.mPackageName.equals(packageName)) {
2524 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002525 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002526 }
2527 deadReceivers.add(receiver);
2528 }
2529 }
2530
2531 // perform removal outside of mReceivers loop
2532 if (deadReceivers != null) {
2533 for (Receiver receiver : deadReceivers) {
2534 removeUpdatesLocked(receiver);
2535 }
2536 }
2537 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002538 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002539 };
2540
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 // Geocoder
2542
Nick Pellye0fd6932012-07-11 10:26:13 -07002543 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002544 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002545 return mGeocodeProvider != null;
2546 }
2547
Nick Pellye0fd6932012-07-11 10:26:13 -07002548 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002550 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002551 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002552 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2553 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002555 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 }
2557
Mike Lockwooda55c3212009-04-15 11:10:11 -04002558
Nick Pellye0fd6932012-07-11 10:26:13 -07002559 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002561 double lowerLeftLatitude, double lowerLeftLongitude,
2562 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002563 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002564
2565 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002566 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2567 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2568 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002569 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002570 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572
2573 // Mock Providers
2574
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002575 private boolean canCallerAccessMockLocation(String opPackageName) {
2576 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
2577 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579
Nick Pellye0fd6932012-07-11 10:26:13 -07002580 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002581 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
2582 if (!canCallerAccessMockLocation(opPackageName)) {
2583 return;
2584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585
Mike Lockwooda4903f22010-02-17 06:42:23 -05002586 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2587 throw new IllegalArgumentException("Cannot mock the passive location provider");
2588 }
2589
Mike Lockwood86328a92009-10-23 08:38:25 -04002590 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002591 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002592 // remove the real provider if we are replacing GPS or network provider
2593 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002594 || LocationManager.NETWORK_PROVIDER.equals(name)
2595 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002596 LocationProviderInterface p = mProvidersByName.get(name);
2597 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002598 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002599 }
2600 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002601 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 updateProvidersLocked();
2603 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002604 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
2606
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002607 private void addTestProviderLocked(String name, ProviderProperties properties) {
2608 if (mProvidersByName.get(name) != null) {
2609 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2610 }
2611 MockProvider provider = new MockProvider(name, this, properties);
2612 addProviderLocked(provider);
2613 mMockProviders.put(name, provider);
2614 mLastLocation.put(name, null);
2615 mLastLocationCoarseInterval.put(name, null);
2616 }
2617
Nick Pellye0fd6932012-07-11 10:26:13 -07002618 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002619 public void removeTestProvider(String provider, String opPackageName) {
2620 if (!canCallerAccessMockLocation(opPackageName)) {
2621 return;
2622 }
2623
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002624 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002625
2626 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002627 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002628 clearTestProviderEnabled(provider, opPackageName);
2629 clearTestProviderLocation(provider, opPackageName);
2630 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002631
You Kima6d0b6f2012-10-28 03:58:44 +09002632 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002633 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002634 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2635 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002636 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002637 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002638
2639 // reinstate real provider if available
2640 LocationProviderInterface realProvider = mRealProviders.get(provider);
2641 if (realProvider != null) {
2642 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002643 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002644 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002645 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002646 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002647 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002648 }
2649 }
2650
Nick Pellye0fd6932012-07-11 10:26:13 -07002651 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002652 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
2653 if (!canCallerAccessMockLocation(opPackageName)) {
2654 return;
2655 }
2656
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002657 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002658 MockProvider mockProvider = mMockProviders.get(provider);
2659 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002660 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2661 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002662
2663 // Ensure that the location is marked as being mock. There's some logic to do this in
2664 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
2665 Location mock = new Location(loc);
2666 mock.setIsFromMockProvider(true);
2667
2668 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
2669 // The location has an explicit provider that is different from the mock provider
2670 // name. The caller may be trying to fool us via bug 33091107.
2671 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
2672 provider + "!=" + loc.getProvider());
2673 }
2674
Mike Lockwood95427cd2009-05-07 13:27:54 -04002675 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2676 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002677 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002678 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 }
2681
Nick Pellye0fd6932012-07-11 10:26:13 -07002682 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002683 public void clearTestProviderLocation(String provider, String opPackageName) {
2684 if (!canCallerAccessMockLocation(opPackageName)) {
2685 return;
2686 }
2687
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002688 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002689 MockProvider mockProvider = mMockProviders.get(provider);
2690 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002691 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2692 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002693 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 }
2695 }
2696
Nick Pellye0fd6932012-07-11 10:26:13 -07002697 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002698 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
2699 if (!canCallerAccessMockLocation(opPackageName)) {
2700 return;
2701 }
2702
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002703 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002704 MockProvider mockProvider = mMockProviders.get(provider);
2705 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002706 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2707 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002708 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002709 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002710 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002711 mEnabledProviders.add(provider);
2712 mDisabledProviders.remove(provider);
2713 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002714 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 mEnabledProviders.remove(provider);
2716 mDisabledProviders.add(provider);
2717 }
2718 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002719 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
2721 }
2722
Nick Pellye0fd6932012-07-11 10:26:13 -07002723 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002724 public void clearTestProviderEnabled(String provider, String opPackageName) {
2725 if (!canCallerAccessMockLocation(opPackageName)) {
2726 return;
2727 }
2728
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002729 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002730 MockProvider mockProvider = mMockProviders.get(provider);
2731 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002732 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2733 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002734 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 mEnabledProviders.remove(provider);
2736 mDisabledProviders.remove(provider);
2737 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002738 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 }
2740 }
2741
Nick Pellye0fd6932012-07-11 10:26:13 -07002742 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002743 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
2744 String opPackageName) {
2745 if (!canCallerAccessMockLocation(opPackageName)) {
2746 return;
2747 }
2748
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002749 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002750 MockProvider mockProvider = mMockProviders.get(provider);
2751 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2753 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002754 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002755 }
2756 }
2757
Nick Pellye0fd6932012-07-11 10:26:13 -07002758 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002759 public void clearTestProviderStatus(String provider, String opPackageName) {
2760 if (!canCallerAccessMockLocation(opPackageName)) {
2761 return;
2762 }
2763
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002764 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002765 MockProvider mockProvider = mMockProviders.get(provider);
2766 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2768 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002769 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002770 }
2771 }
2772
2773 private void log(String log) {
2774 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002775 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 }
2777 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002778
2779 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002780 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2781 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2782 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002783 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 + Binder.getCallingPid()
2785 + ", uid=" + Binder.getCallingUid());
2786 return;
2787 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002788
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002789 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002790 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002792 for (Receiver receiver : mReceivers.values()) {
2793 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
David Christie2ff96af2014-01-30 16:09:37 -08002795 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002796 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2797 pw.println(" " + entry.getKey() + ":");
2798 for (UpdateRecord record : entry.getValue()) {
2799 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 }
2801 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002802 pw.println(" Overlay Provider Packages:");
2803 for (LocationProviderInterface provider : mProviders) {
2804 if (provider instanceof LocationProviderProxy) {
2805 pw.println(" " + provider.getName() + ": "
2806 + ((LocationProviderProxy) provider).getConnectedPackageName());
2807 }
2808 }
David Christie2ff96af2014-01-30 16:09:37 -08002809 pw.println(" Historical Records by Provider:");
2810 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2811 : mRequestStatistics.statistics.entrySet()) {
2812 PackageProviderKey key = entry.getKey();
2813 PackageStatistics stats = entry.getValue();
2814 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2815 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002817 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2818 String provider = entry.getKey();
2819 Location location = entry.getValue();
2820 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002822
David Christie1b9b7b12013-04-15 15:31:11 -07002823 pw.println(" Last Known Locations Coarse Intervals:");
2824 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2825 String provider = entry.getKey();
2826 Location location = entry.getValue();
2827 pw.println(" " + provider + ": " + location);
2828 }
2829
Nick Pellye0fd6932012-07-11 10:26:13 -07002830 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002831
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002832 if (mEnabledProviders.size() > 0) {
2833 pw.println(" Enabled Providers:");
2834 for (String i : mEnabledProviders) {
2835 pw.println(" " + i);
2836 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 }
2839 if (mDisabledProviders.size() > 0) {
2840 pw.println(" Disabled Providers:");
2841 for (String i : mDisabledProviders) {
2842 pw.println(" " + i);
2843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002845 pw.append(" ");
2846 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002847 if (mMockProviders.size() > 0) {
2848 pw.println(" Mock Providers:");
2849 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002850 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 }
2852 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002853
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002854 pw.append(" fudger: ");
2855 mLocationFudger.dump(fd, pw, args);
2856
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002857 if (args.length > 0 && "short".equals(args[0])) {
2858 return;
2859 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002860 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002861 pw.print(provider.getName() + " Internal State");
2862 if (provider instanceof LocationProviderProxy) {
2863 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2864 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002865 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002866 pw.println(":");
2867 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870 }
2871}