blob: cc7bf3373bdd4754637558dd2dd7ee6f72a41498 [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
Maggieaa080f92018-01-04 15:35:11 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Soonil Nagarkar94749f72018-11-08 11:46:43 -080020import static android.provider.Settings.Global.LOCATION_DISABLE_STATUS_CALLBACKS;
Maggieaa080f92018-01-04 15:35:11 -080021
Wyatt Rileycf879db2017-01-12 13:57:38 -080022import android.annotation.NonNull;
Wyatt Riley49097c02018-03-15 09:14:43 -070023import android.annotation.Nullable;
Maggieaa080f92018-01-04 15:35:11 -080024import android.app.ActivityManager;
25import android.app.AppOpsManager;
26import android.app.PendingIntent;
27import android.content.BroadcastReceiver;
28import android.content.ContentResolver;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.ApplicationInfo;
33import android.content.pm.PackageInfo;
34import android.content.pm.PackageManager;
35import android.content.pm.PackageManager.NameNotFoundException;
36import android.content.pm.PackageManagerInternal;
37import android.content.pm.ResolveInfo;
38import android.content.pm.Signature;
39import android.content.res.Resources;
40import android.database.ContentObserver;
41import android.hardware.location.ActivityRecognitionHardware;
42import android.location.Address;
43import android.location.Criteria;
44import android.location.GeocoderParams;
45import android.location.Geofence;
46import android.location.IBatchedLocationCallback;
47import android.location.IGnssMeasurementsListener;
48import android.location.IGnssNavigationMessageListener;
49import android.location.IGnssStatusListener;
50import android.location.IGnssStatusProvider;
51import android.location.IGpsGeofenceHardware;
52import android.location.ILocationListener;
53import android.location.ILocationManager;
54import android.location.INetInitiatedListener;
55import android.location.Location;
56import android.location.LocationManager;
57import android.location.LocationProvider;
58import android.location.LocationRequest;
59import android.os.Binder;
60import android.os.Bundle;
61import android.os.Handler;
62import android.os.IBinder;
63import android.os.Looper;
64import android.os.Message;
65import android.os.PowerManager;
66import android.os.Process;
67import android.os.RemoteException;
68import android.os.SystemClock;
69import android.os.UserHandle;
70import android.os.UserManager;
71import android.os.WorkSource;
Narayan Kamath32684dd2018-01-08 17:32:51 +000072import android.os.WorkSource.WorkChain;
Maggieaa080f92018-01-04 15:35:11 -080073import android.provider.Settings;
74import android.text.TextUtils;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080075import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080076import android.util.ArraySet;
Maggieaa080f92018-01-04 15:35:11 -080077import android.util.EventLog;
78import android.util.Log;
79import android.util.Slog;
Yu-Han Yanga4d250e2018-10-02 21:29:20 -070080
destradaaea8a8a62014-06-23 18:19:03 -070081import com.android.internal.content.PackageMonitor;
82import com.android.internal.location.ProviderProperties;
83import com.android.internal.location.ProviderRequest;
84import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070085import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060086import com.android.internal.util.DumpUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070087import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070088import com.android.server.location.GeocoderProxy;
89import com.android.server.location.GeofenceManager;
90import com.android.server.location.GeofenceProxy;
Yu-Han Yang3557cc72018-03-21 12:48:36 -070091import com.android.server.location.GnssBatchingProvider;
Lifu Tang818aa2c2016-02-01 01:52:00 -080092import com.android.server.location.GnssLocationProvider;
93import com.android.server.location.GnssMeasurementsProvider;
94import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070095import com.android.server.location.LocationBlacklist;
96import com.android.server.location.LocationFudger;
97import com.android.server.location.LocationProviderInterface;
98import com.android.server.location.LocationProviderProxy;
99import com.android.server.location.LocationRequestStatistics;
100import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
101import com.android.server.location.LocationRequestStatistics.PackageStatistics;
102import com.android.server.location.MockProvider;
103import com.android.server.location.PassiveProvider;
Yu-Han Yanga4d250e2018-10-02 21:29:20 -0700104
Mike Lockwood43e33f22010-03-26 10:41:48 -0400105import java.io.FileDescriptor;
106import java.io.PrintWriter;
107import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700108import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400109import java.util.HashMap;
110import java.util.HashSet;
111import java.util.List;
112import java.util.Map;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800113import java.util.Map.Entry;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800114import java.util.NoSuchElementException;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400115import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
117/**
118 * The service class that manages LocationProviders and issues location
119 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800121public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800123 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700124
Olivier Gaillard7a222662017-11-20 16:07:24 +0000125 private static final String WAKELOCK_KEY = "*location*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126
Victoria Lease37425c32012-10-16 16:08:48 -0700127 // Location resolution level: no location data whatsoever
128 private static final int RESOLUTION_LEVEL_NONE = 0;
129 // Location resolution level: coarse location data only
130 private static final int RESOLUTION_LEVEL_COARSE = 1;
131 // Location resolution level: fine location data
132 private static final int RESOLUTION_LEVEL_FINE = 2;
133
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800134 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700135 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700137 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400138 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700139 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
140
141 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700142 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700143 private static final String FUSED_LOCATION_SERVICE_ACTION =
144 "com.android.location.service.FusedLocationProvider";
145
146 private static final int MSG_LOCATION_CHANGED = 1;
147
David Christie1b9b7b12013-04-15 15:31:11 -0700148 private static final long NANOS_PER_MILLI = 1000000L;
149
David Christie0b837452013-07-29 16:02:13 -0700150 // The maximum interval a location request can have and still be considered "high power".
151 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
152
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700153 private static final int FOREGROUND_IMPORTANCE_CUTOFF
gomo48f1a642017-11-10 20:35:46 -0800154 = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700155
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800156 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800157 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800158
Wei Wangdd070f22018-06-21 11:29:40 -0700159 // Default value for maximum age of last location returned to applications with foreground-only
160 // location permissions.
161 private static final long DEFAULT_LAST_LOCATION_MAX_AGE_MS = 20 * 60 * 1000;
162
Nick Pellyf1be6862012-05-15 10:53:42 -0700163 // Location Providers may sometimes deliver location updates
164 // slightly faster that requested - provide grace period so
165 // we don't unnecessarily filter events that are otherwise on
166 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700167 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700168
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700169 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
170
171 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800172 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700173
174 // used internally for synchronization
175 private final Object mLock = new Object();
176
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700177 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700178 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700179 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700180 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700181 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800182 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700183 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700184 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800185 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 private INetInitiatedListener mNetInitiatedListener;
187 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700188 private PassiveProvider mPassiveProvider; // track passive provider for special cases
189 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800190 private GnssMeasurementsProvider mGnssMeasurementsProvider;
191 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700192 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700193
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700194 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800195 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700196 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800197 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
199 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800200 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700202 // Mock (test) providers
203 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800204 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700206 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800207 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500210 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800211 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400212
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700213 // real providers, saved here when mocked out
214 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800215 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700217 // mapping from provider name to provider
218 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800219 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700221 // mapping from provider name to all its UpdateRecords
222 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800223 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700224
David Christie2ff96af2014-01-30 16:09:37 -0800225 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
226
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700227 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800228 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
David Christie1b9b7b12013-04-15 15:31:11 -0700230 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
231 // locations stored here are not fudged for coarse permissions.
232 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800233 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700234
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800235 // all providers that operate over proxy, for authorizing incoming location and whitelisting
236 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700237 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800238 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800240 private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800241
Wyatt Riley11cc7492018-01-17 08:48:27 -0800242 private final ArrayMap<IBinder, Identity> mGnssMeasurementsListeners = new ArrayMap<>();
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800243
Wyatt Riley11cc7492018-01-17 08:48:27 -0800244 private final ArrayMap<IBinder, Identity>
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800245 mGnssNavigationMessageListeners = new ArrayMap<>();
246
Victoria Lease38389b62012-09-30 11:44:22 -0700247 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700248 private int mCurrentUserId = UserHandle.USER_SYSTEM;
gomo48f1a642017-11-10 20:35:46 -0800249 private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
Victoria Lease38389b62012-09-30 11:44:22 -0700250
Wei Wangdd070f22018-06-21 11:29:40 -0700251 // Maximum age of last location returned to clients with foreground-only location permissions.
252 private long mLastLocationMaxAgeMs;
253
Lifu Tang9363b942016-02-16 18:07:00 -0800254 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800255
Siddharth Raybb608c82017-03-16 11:33:34 -0700256 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700257
Yu-Han Yang3557cc72018-03-21 12:48:36 -0700258 private GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800259 private IBatchedLocationCallback mGnssBatchingCallback;
260 private LinkedCallback mGnssBatchingDeathCallback;
261 private boolean mGnssBatchingInProgress = false;
262
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700263 public LocationManagerService(Context context) {
264 super();
265 mContext = context;
gomo48f1a642017-11-10 20:35:46 -0800266 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800267
Svet Ganovadc1cf42015-06-15 16:36:24 -0700268 // Let the package manager query which are the default location
269 // providers as they get certain permissions granted by default.
270 PackageManagerInternal packageManagerInternal = LocalServices.getService(
271 PackageManagerInternal.class);
272 packageManagerInternal.setLocationPackagesProvider(
273 new PackageManagerInternal.PackagesProvider() {
274 @Override
275 public String[] getPackages(int userId) {
276 return mContext.getResources().getStringArray(
277 com.android.internal.R.array.config_locationProviderPackageNames);
278 }
279 });
280
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700281 if (D) Log.d(TAG, "Constructed");
282
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700283 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700284 }
285
Svetoslav Ganova0027152013-06-25 14:59:53 -0700286 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700287 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700288 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700289
Victoria Lease5cd731a2012-12-19 15:04:21 -0800290 // fetch package manager
291 mPackageManager = mContext.getPackageManager();
292
Victoria Lease0aa28602013-05-29 15:28:26 -0700293 // fetch power manager
294 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800295
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800296 // fetch activity manager
297 mActivityManager
298 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
299
Victoria Lease5cd731a2012-12-19 15:04:21 -0800300 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700301 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800302
303 // prepare mLocationHandler's dependents
304 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
305 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
306 mBlacklist.init();
307 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
308
Dianne Hackbornc2293022013-02-06 23:14:49 -0800309 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700310 AppOpsManager.OnOpChangedListener callback
311 = new AppOpsManager.OnOpChangedInternalListener() {
312 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800313 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700314 for (Receiver receiver : mReceivers.values()) {
315 receiver.updateMonitoring(true);
316 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800317 applyAllProviderRequirementsLocked();
318 }
319 }
320 };
Wei Wangdd070f22018-06-21 11:29:40 -0700321 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null,
322 AppOpsManager.WATCH_FOREGROUND_CHANGES, callback);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800323
David Christieb870dbf2015-06-22 12:42:53 -0700324 PackageManager.OnPermissionsChangedListener permissionListener
325 = new PackageManager.OnPermissionsChangedListener() {
326 @Override
327 public void onPermissionsChanged(final int uid) {
328 synchronized (mLock) {
329 applyAllProviderRequirementsLocked();
330 }
331 }
332 };
333 mPackageManager.addOnPermissionsChangeListener(permissionListener);
334
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800335 // listen for background/foreground changes
336 ActivityManager.OnUidImportanceListener uidImportanceListener
337 = new ActivityManager.OnUidImportanceListener() {
338 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700339 public void onUidImportance(final int uid, final int importance) {
340 mLocationHandler.post(new Runnable() {
341 @Override
342 public void run() {
343 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800344 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700345 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800346 }
347 };
348 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700349 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800350
Amith Yamasanib27528d2014-06-05 15:02:10 -0700351 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
352 updateUserProfiles(mCurrentUserId);
353
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800354 updateBackgroundThrottlingWhitelistLocked();
Wei Wangdd070f22018-06-21 11:29:40 -0700355 updateLastLocationMaxAgeLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800356
Victoria Lease5cd731a2012-12-19 15:04:21 -0800357 // prepare providers
358 loadProvidersLocked();
359 updateProvidersLocked();
360 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700361
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700362 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700363 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700364 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700365 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800366 @Override
367 public void onChange(boolean selfChange) {
368 synchronized (mLock) {
369 updateProvidersLocked();
370 }
371 }
372 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800373 mContext.getContentResolver().registerContentObserver(
374 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
375 true,
376 new ContentObserver(mLocationHandler) {
377 @Override
378 public void onChange(boolean selfChange) {
379 synchronized (mLock) {
380 updateProvidersLocked();
381 }
382 }
383 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800384 mContext.getContentResolver().registerContentObserver(
Wei Wangdd070f22018-06-21 11:29:40 -0700385 Settings.Global.getUriFor(Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS),
386 true,
387 new ContentObserver(mLocationHandler) {
388 @Override
389 public void onChange(boolean selfChange) {
390 synchronized (mLock) {
391 updateLastLocationMaxAgeLocked();
392 }
393 }
394 }
395 );
396 mContext.getContentResolver().registerContentObserver(
gomo48f1a642017-11-10 20:35:46 -0800397 Settings.Global.getUriFor(
398 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
399 true,
400 new ContentObserver(mLocationHandler) {
401 @Override
402 public void onChange(boolean selfChange) {
403 synchronized (mLock) {
404 updateBackgroundThrottlingWhitelistLocked();
405 updateProvidersLocked();
406 }
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800407 }
gomo48f1a642017-11-10 20:35:46 -0800408 }, UserHandle.USER_ALL);
Wei Wangdd070f22018-06-21 11:29:40 -0700409
Victoria Lease5cd731a2012-12-19 15:04:21 -0800410 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700411
Victoria Lease38389b62012-09-30 11:44:22 -0700412 // listen for user change
413 IntentFilter intentFilter = new IntentFilter();
414 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700415 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
416 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700417 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700418
419 mContext.registerReceiverAsUser(new BroadcastReceiver() {
420 @Override
421 public void onReceive(Context context, Intent intent) {
422 String action = intent.getAction();
423 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
424 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700425 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
426 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
427 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700428 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700429 // shutdown only if UserId indicates whole system, not just one user
gomo48f1a642017-11-10 20:35:46 -0800430 if (D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700431 if (getSendingUserId() == UserHandle.USER_ALL) {
432 shutdownComponents();
433 }
Victoria Lease38389b62012-09-30 11:44:22 -0700434 }
435 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800436 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700437 }
438
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700439 private void onUidImportanceChanged(int uid, int importance) {
440 boolean foreground = isImportanceForeground(importance);
441 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
442 synchronized (mLock) {
443 for (Entry<String, ArrayList<UpdateRecord>> entry
gomo48f1a642017-11-10 20:35:46 -0800444 : mRecordsByProvider.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700445 String provider = entry.getKey();
446 for (UpdateRecord record : entry.getValue()) {
447 if (record.mReceiver.mIdentity.mUid == uid
gomo48f1a642017-11-10 20:35:46 -0800448 && record.mIsForegroundUid != foreground) {
449 if (D) {
450 Log.d(TAG, "request from uid " + uid + " is now "
451 + (foreground ? "foreground" : "background)"));
452 }
Wyatt Rileyf7075e02018-04-12 17:54:26 -0700453 record.updateForeground(foreground);
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700454
455 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
456 affectedProviders.add(provider);
457 }
458 }
459 }
460 }
461 for (String provider : affectedProviders) {
462 applyRequirementsLocked(provider);
463 }
464
Wyatt Riley11cc7492018-01-17 08:48:27 -0800465 for (Entry<IBinder, Identity> entry : mGnssMeasurementsListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700466 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800467 if (D) {
468 Log.d(TAG, "gnss measurements listener from uid " + uid
469 + " is now " + (foreground ? "foreground" : "background)"));
470 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700471 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800472 mGnssMeasurementsProvider.addListener(
473 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700474 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800475 mGnssMeasurementsProvider.removeListener(
476 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700477 }
478 }
479 }
480
Wyatt Riley11cc7492018-01-17 08:48:27 -0800481 for (Entry<IBinder, Identity> entry : mGnssNavigationMessageListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700482 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800483 if (D) {
484 Log.d(TAG, "gnss navigation message listener from uid "
485 + uid + " is now "
486 + (foreground ? "foreground" : "background)"));
487 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700488 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800489 mGnssNavigationMessageProvider.addListener(
490 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700491 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800492 mGnssNavigationMessageProvider.removeListener(
493 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700494 }
495 }
496 }
497 }
498 }
499
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800500 private static boolean isImportanceForeground(int importance) {
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700501 return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800502 }
503
Amith Yamasanib27528d2014-06-05 15:02:10 -0700504 /**
destradaab9026982015-08-27 17:34:54 -0700505 * Provides a way for components held by the {@link LocationManagerService} to clean-up
506 * gracefully on system's shutdown.
507 *
508 * NOTES:
509 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
510 * support for components that do not wish to handle such event.
511 */
512 private void shutdownComponents() {
gomo48f1a642017-11-10 20:35:46 -0800513 if (D) Log.d(TAG, "Shutting down components...");
destradaab9026982015-08-27 17:34:54 -0700514
515 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
516 if (gpsProvider != null && gpsProvider.isEnabled()) {
517 gpsProvider.disable();
518 }
destradaab9026982015-08-27 17:34:54 -0700519 }
520
521 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700522 * Makes a list of userids that are related to the current user. This is
523 * relevant when using managed profiles. Otherwise the list only contains
524 * the current user.
525 *
526 * @param currentUserId the current user, who might have an alter-ego.
527 */
528 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700529 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700530 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700531 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700532 }
533 }
534
535 /**
536 * Checks if the specified userId matches any of the current foreground
537 * users stored in mCurrentUserProfiles.
538 */
539 private boolean isCurrentProfile(int userId) {
540 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700541 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700542 }
543 }
544
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700545 private void ensureFallbackFusedProviderPresentLocked(String[] pkgs) {
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500546 PackageManager pm = mContext.getPackageManager();
547 String systemPackageName = mContext.getPackageName();
548 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
549
550 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
551 new Intent(FUSED_LOCATION_SERVICE_ACTION),
552 PackageManager.GET_META_DATA, mCurrentUserId);
553 for (ResolveInfo rInfo : rInfos) {
554 String packageName = rInfo.serviceInfo.packageName;
555
556 // Check that the signature is in the list of supported sigs. If it's not in
557 // this list the standard provider binding logic won't bind to it.
558 try {
559 PackageInfo pInfo;
560 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
561 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
562 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
563 ", but has wrong signature, ignoring");
564 continue;
565 }
566 } catch (NameNotFoundException e) {
567 Log.e(TAG, "missing package: " + packageName);
568 continue;
569 }
570
571 // Get the version info
572 if (rInfo.serviceInfo.metaData == null) {
573 Log.w(TAG, "Found fused provider without metadata: " + packageName);
574 continue;
575 }
576
577 int version = rInfo.serviceInfo.metaData.getInt(
578 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
579 if (version == 0) {
580 // This should be the fallback fused location provider.
581
582 // Make sure it's in the system partition.
583 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
584 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
585 continue;
586 }
587
588 // Check that the fallback is signed the same as the OS
589 // as a proxy for coreApp="true"
590 if (pm.checkSignatures(systemPackageName, packageName)
591 != PackageManager.SIGNATURE_MATCH) {
gomo48f1a642017-11-10 20:35:46 -0800592 if (D) {
593 Log.d(TAG, "Fallback candidate not signed the same as system: "
594 + packageName);
595 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500596 continue;
597 }
598
599 // Found a valid fallback.
600 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
601 return;
602 } else {
603 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
604 }
605 }
606
607 throw new IllegalStateException("Unable to find a fused location provider that is in the "
608 + "system partition with version 0 and signed with the platform certificate. "
609 + "Such a package is needed to provide a default fused location provider in the "
610 + "event that no other fused location provider has been installed or is currently "
611 + "available. For example, coreOnly boot mode when decrypting the data "
612 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
613 }
614
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700615 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700616 // create a passive location provider, which is always enabled
617 PassiveProvider passiveProvider = new PassiveProvider(this);
618 addProviderLocked(passiveProvider);
619 mEnabledProviders.add(passiveProvider.getName());
620 mPassiveProvider = passiveProvider;
621
Lifu Tang30f95a72016-01-07 23:20:38 -0800622 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700623 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800624 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700625 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800626 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Wyatt Rileycf879db2017-01-12 13:57:38 -0800627 mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
Siddharth Raybb608c82017-03-16 11:33:34 -0700628 mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800629 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
630 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
631 addProviderLocked(gnssProvider);
632 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800633 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
634 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800635 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700636 }
637
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700638 /*
639 Load package name(s) containing location provider support.
640 These packages can contain services implementing location providers:
641 Geocoder Provider, Network Location Provider, and
642 Fused Location Provider. They will each be searched for
643 service components implementing these providers.
644 The location framework also has support for installation
645 of new location providers at run-time. The new package does not
646 have to be explicitly listed here, however it must have a signature
647 that matches the signature of at least one package on this list.
648 */
649 Resources resources = mContext.getResources();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500650 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700651 com.android.internal.R.array.config_locationProviderPackageNames);
gomo48f1a642017-11-10 20:35:46 -0800652 if (D) {
653 Log.d(TAG, "certificates for location providers pulled from: " +
654 Arrays.toString(pkgs));
655 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500656
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700657 ensureFallbackFusedProviderPresentLocked(pkgs);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700658
659 // bind to network provider
660 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
661 mContext,
662 LocationManager.NETWORK_PROVIDER,
663 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700664 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
665 com.android.internal.R.string.config_networkLocationProviderPackageName,
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700666 com.android.internal.R.array.config_locationProviderPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700667 if (networkProvider != null) {
668 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
669 mProxyProviders.add(networkProvider);
670 addProviderLocked(networkProvider);
671 } else {
gomo48f1a642017-11-10 20:35:46 -0800672 Slog.w(TAG, "no network location provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700673 }
674
675 // bind to fused provider
676 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
677 mContext,
678 LocationManager.FUSED_PROVIDER,
679 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700680 com.android.internal.R.bool.config_enableFusedLocationOverlay,
681 com.android.internal.R.string.config_fusedLocationProviderPackageName,
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700682 com.android.internal.R.array.config_locationProviderPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700683 if (fusedLocationProvider != null) {
684 addProviderLocked(fusedLocationProvider);
685 mProxyProviders.add(fusedLocationProvider);
686 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700687 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700688 } else {
689 Slog.e(TAG, "no fused location provider found",
690 new IllegalStateException("Location service needs a fused location provider"));
691 }
692
693 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700694 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
695 com.android.internal.R.bool.config_enableGeocoderOverlay,
696 com.android.internal.R.string.config_geocoderProviderPackageName,
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700697 com.android.internal.R.array.config_locationProviderPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700698 if (mGeocodeProvider == null) {
gomo48f1a642017-11-10 20:35:46 -0800699 Slog.e(TAG, "no geocoder provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700700 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700701
destradaaf9a274c2014-07-25 15:11:56 -0700702 // bind to geofence provider
703 GeofenceProxy provider = GeofenceProxy.createAndBind(
gomo48f1a642017-11-10 20:35:46 -0800704 mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
destradaaf9a274c2014-07-25 15:11:56 -0700705 com.android.internal.R.string.config_geofenceProviderPackageName,
706 com.android.internal.R.array.config_locationProviderPackageNames,
Wei Liu5241a4c2015-05-11 14:00:36 -0700707 mGpsGeofenceProxy,
Jiyong Park4cc3a1c2018-03-08 16:43:07 +0900708 null);
destradaaf9a274c2014-07-25 15:11:56 -0700709 if (provider == null) {
gomo48f1a642017-11-10 20:35:46 -0800710 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700711 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900712
destradaa6e2fe752015-06-23 17:25:53 -0700713 // bind to hardware activity recognition
714 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
715 ActivityRecognitionHardware activityRecognitionHardware = null;
716 if (activityRecognitionHardwareIsSupported) {
717 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700718 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700719 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700720 }
destradaa6e2fe752015-06-23 17:25:53 -0700721 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
722 mContext,
destradaa6e2fe752015-06-23 17:25:53 -0700723 activityRecognitionHardwareIsSupported,
724 activityRecognitionHardware,
725 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
726 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
727 com.android.internal.R.array.config_locationProviderPackageNames);
728 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700729 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700730 }
destradaaa4fa3b52014-07-09 10:46:39 -0700731
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900732 String[] testProviderStrings = resources.getStringArray(
733 com.android.internal.R.array.config_testLocationProviders);
734 for (String testProviderString : testProviderStrings) {
735 String fragments[] = testProviderString.split(",");
736 String name = fragments[0].trim();
737 if (mProvidersByName.get(name) != null) {
738 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
739 }
740 ProviderProperties properties = new ProviderProperties(
741 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
742 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
743 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
744 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
745 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
746 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
747 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
748 Integer.parseInt(fragments[8]) /* powerRequirement */,
749 Integer.parseInt(fragments[9]) /* accuracy */);
750 addTestProviderLocked(name, properties);
751 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700752 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700753
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700755 * Called when the device's active user changes.
gomo48f1a642017-11-10 20:35:46 -0800756 *
Victoria Lease38389b62012-09-30 11:44:22 -0700757 * @param userId the new active user's UserId
758 */
759 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800760 if (mCurrentUserId == userId) {
761 return;
762 }
Victoria Lease83762d22012-10-03 13:51:17 -0700763 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800764 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700765 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700766 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700767 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700768 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700769 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700770 }
Victoria Lease38389b62012-09-30 11:44:22 -0700771 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700772 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700773 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700774 }
775 }
776
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800777 private static final class Identity {
778 final int mUid;
779 final int mPid;
780 final String mPackageName;
781
782 Identity(int uid, int pid, String packageName) {
783 mUid = uid;
784 mPid = pid;
785 mPackageName = packageName;
786 }
787 }
788
Victoria Lease38389b62012-09-30 11:44:22 -0700789 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800790 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
791 * location updates.
792 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700793 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Yu-Han Yang24189822018-07-11 15:24:11 -0700794 private static final long WAKELOCK_TIMEOUT_MILLIS = 60 * 1000;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800795 final Identity mIdentity;
Victoria Lease37425c32012-10-16 16:08:48 -0700796 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 final ILocationListener mListener;
799 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700800 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700801 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700803
gomo48f1a642017-11-10 20:35:46 -0800804 final HashMap<String, UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700805
David Christie0b837452013-07-29 16:02:13 -0700806 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700807 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700808 // True if app ops has started monitoring this receiver for high power (gps) locations.
809 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700810 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700811 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700813 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700814 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800816 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700817 if (listener != null) {
818 mKey = listener.asBinder();
819 } else {
820 mKey = intent;
821 }
Victoria Lease37425c32012-10-16 16:08:48 -0700822 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800823 mIdentity = new Identity(uid, pid, packageName);
Narayan Kamath32684dd2018-01-08 17:32:51 +0000824 if (workSource != null && workSource.isEmpty()) {
David Christie82edc9b2013-07-19 11:31:42 -0700825 workSource = null;
826 }
827 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700828 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700829
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700830 updateMonitoring(true);
831
Victoria Lease0aa28602013-05-29 15:28:26 -0700832 // construct/configure wakelock
833 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700834 if (workSource == null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800835 workSource = new WorkSource(mIdentity.mUid, mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -0700836 }
837 mWakeLock.setWorkSource(workSource);
Yu-Han Yang24189822018-07-11 15:24:11 -0700838
839 // For a non-reference counted wakelock, each acquire will reset the timeout, and we
840 // only need to release it once.
841 mWakeLock.setReferenceCounted(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800842 }
843
844 @Override
845 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800846 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
848
849 @Override
850 public int hashCode() {
851 return mKey.hashCode();
852 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 @Override
855 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700856 StringBuilder s = new StringBuilder();
857 s.append("Reciever[");
858 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700860 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700862 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700864 for (String p : mUpdateRecords.keySet()) {
865 s.append(" ").append(mUpdateRecords.get(p).toString());
866 }
Wei Wangdd070f22018-06-21 11:29:40 -0700867 s.append(" monitoring location: ").append(mOpMonitoring);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700868 s.append("]");
869 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870 }
871
David Christie15b31912013-08-13 15:54:32 -0700872 /**
873 * Update AppOp monitoring for this receiver.
874 *
875 * @param allow If true receiver is currently active, if false it's been removed.
876 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700877 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700878 if (mHideFromAppOps) {
879 return;
880 }
881
David Christie15b31912013-08-13 15:54:32 -0700882 boolean requestingLocation = false;
883 boolean requestingHighPowerLocation = false;
884 if (allow) {
885 // See if receiver has any enabled update records. Also note if any update records
886 // are high power (has a high power provider with an interval under a threshold).
887 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
888 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
889 requestingLocation = true;
890 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800891 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700892 ProviderProperties properties = locationProvider != null
893 ? locationProvider.getProperties() : null;
894 if (properties != null
895 && properties.mPowerRequirement == Criteria.POWER_HIGH
896 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
897 requestingHighPowerLocation = true;
898 break;
899 }
900 }
901 }
902 }
903
David Christie0b837452013-07-29 16:02:13 -0700904 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700905 mOpMonitoring = updateMonitoring(
906 requestingLocation,
907 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700908 AppOpsManager.OP_MONITOR_LOCATION);
909
910 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700911 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700912 mOpHighPowerMonitoring = updateMonitoring(
913 requestingHighPowerLocation,
914 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700915 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700916 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700917 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700918 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
919 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
920 }
David Christie0b837452013-07-29 16:02:13 -0700921 }
922
923 /**
924 * Update AppOps monitoring for a single location request and op type.
925 *
gomo48f1a642017-11-10 20:35:46 -0800926 * @param allowMonitoring True if monitoring is allowed for this request/op.
David Christie0b837452013-07-29 16:02:13 -0700927 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
gomo48f1a642017-11-10 20:35:46 -0800928 * @param op AppOps code for the op to update.
David Christie0b837452013-07-29 16:02:13 -0700929 * @return True if monitoring is on for this request/op after updating.
930 */
931 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
932 int op) {
933 if (!currentlyMonitoring) {
934 if (allowMonitoring) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800935 return mAppOps.startOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700936 == AppOpsManager.MODE_ALLOWED;
937 }
938 } else {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800939 if (!allowMonitoring
Wei Wangdd070f22018-06-21 11:29:40 -0700940 || mAppOps.noteOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700941 != AppOpsManager.MODE_ALLOWED) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800942 mAppOps.finishOp(op, mIdentity.mUid, mIdentity.mPackageName);
David Christie0b837452013-07-29 16:02:13 -0700943 return false;
944 }
945 }
946
947 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700948 }
949
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 public boolean isListener() {
951 return mListener != null;
952 }
953
954 public boolean isPendingIntent() {
955 return mPendingIntent != null;
956 }
957
958 public ILocationListener getListener() {
959 if (mListener != null) {
960 return mListener;
961 }
962 throw new IllegalStateException("Request for non-existent listener");
963 }
964
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
966 if (mListener != null) {
967 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700968 synchronized (this) {
969 // synchronize to ensure incrementPendingBroadcastsLocked()
970 // is called before decrementPendingBroadcasts()
971 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700972 // call this after broadcasting so we do not increment
973 // if we throw an exeption.
974 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800976 } catch (RemoteException e) {
977 return false;
978 }
979 } else {
980 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800981 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800982 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
983 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700984 synchronized (this) {
985 // synchronize to ensure incrementPendingBroadcastsLocked()
986 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700987 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -0700988 getResolutionPermission(mAllowedResolutionLevel),
989 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -0700990 // call this after broadcasting so we do not increment
991 // if we throw an exeption.
992 incrementPendingBroadcastsLocked();
993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 } catch (PendingIntent.CanceledException e) {
995 return false;
996 }
997 }
998 return true;
999 }
1000
1001 public boolean callLocationChangedLocked(Location location) {
1002 if (mListener != null) {
1003 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001004 synchronized (this) {
1005 // synchronize to ensure incrementPendingBroadcastsLocked()
1006 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001007 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -07001008 // call this after broadcasting so we do not increment
1009 // if we throw an exeption.
1010 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001011 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 } catch (RemoteException e) {
1013 return false;
1014 }
1015 } else {
1016 Intent locationChanged = new Intent();
gomo48f1a642017-11-10 20:35:46 -08001017 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED,
1018 new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001019 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001020 synchronized (this) {
1021 // synchronize to ensure incrementPendingBroadcastsLocked()
1022 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001023 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -07001024 getResolutionPermission(mAllowedResolutionLevel),
1025 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -07001026 // call this after broadcasting so we do not increment
1027 // if we throw an exeption.
1028 incrementPendingBroadcastsLocked();
1029 }
1030 } catch (PendingIntent.CanceledException e) {
1031 return false;
1032 }
1033 }
1034 return true;
1035 }
1036
1037 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001038 // First update AppOp monitoring.
1039 // An app may get/lose location access as providers are enabled/disabled.
1040 updateMonitoring(true);
1041
Mike Lockwood48f17512009-04-23 09:12:08 -07001042 if (mListener != null) {
1043 try {
1044 synchronized (this) {
1045 // synchronize to ensure incrementPendingBroadcastsLocked()
1046 // is called before decrementPendingBroadcasts()
1047 if (enabled) {
1048 mListener.onProviderEnabled(provider);
1049 } else {
1050 mListener.onProviderDisabled(provider);
1051 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001052 // call this after broadcasting so we do not increment
1053 // if we throw an exeption.
1054 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001055 }
1056 } catch (RemoteException e) {
1057 return false;
1058 }
1059 } else {
1060 Intent providerIntent = new Intent();
1061 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1062 try {
1063 synchronized (this) {
1064 // synchronize to ensure incrementPendingBroadcastsLocked()
1065 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001066 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -07001067 getResolutionPermission(mAllowedResolutionLevel),
1068 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -07001069 // call this after broadcasting so we do not increment
1070 // if we throw an exeption.
1071 incrementPendingBroadcastsLocked();
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 } catch (PendingIntent.CanceledException e) {
1074 return false;
1075 }
1076 }
1077 return true;
1078 }
1079
Nick Pellyf1be6862012-05-15 10:53:42 -07001080 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001082 if (D) Log.d(TAG, "Location listener died");
1083
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001084 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 removeUpdatesLocked(this);
1086 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001087 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001088 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001089 }
1090 }
1091
Nick Pellye0fd6932012-07-11 10:26:13 -07001092 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001093 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1094 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001095 synchronized (this) {
1096 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001097 }
1098 }
1099
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001100 // this must be called while synchronized by caller in a synchronized block
1101 // containing the sending of the broadcaset
1102 private void incrementPendingBroadcastsLocked() {
Yu-Han Yang24189822018-07-11 15:24:11 -07001103 mPendingBroadcasts++;
1104 mWakeLock.acquire(WAKELOCK_TIMEOUT_MILLIS);
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001105 }
1106
1107 private void decrementPendingBroadcastsLocked() {
1108 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001109 if (mWakeLock.isHeld()) {
1110 mWakeLock.release();
1111 }
1112 }
1113 }
1114
1115 public void clearPendingBroadcastsLocked() {
1116 if (mPendingBroadcasts > 0) {
1117 mPendingBroadcasts = 0;
1118 if (mWakeLock.isHeld()) {
1119 mWakeLock.release();
1120 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001121 }
1122 }
1123 }
1124
Nick Pellye0fd6932012-07-11 10:26:13 -07001125 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001126 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001127 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001128 //the receiver list if it is not found. If it is not found then the
1129 //LocationListener was removed when it had a pending broadcast and should
1130 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001131 synchronized (mLock) {
1132 IBinder binder = listener.asBinder();
1133 Receiver receiver = mReceivers.get(binder);
1134 if (receiver != null) {
1135 synchronized (receiver) {
1136 // so wakelock calls will succeed
1137 long identity = Binder.clearCallingIdentity();
1138 receiver.decrementPendingBroadcastsLocked();
1139 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001140 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 }
1143 }
1144
Lifu Tang82f893d2016-01-21 18:15:33 -08001145 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001146 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001147 */
1148 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001149 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001150 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001151 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001152 } else {
1153 return 0;
1154 }
1155 }
1156
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001157
1158 /**
1159 * Returns the model name of the GNSS hardware.
1160 */
1161 @Override
Wyatt Riley49097c02018-03-15 09:14:43 -07001162 @Nullable
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001163 public String getGnssHardwareModelName() {
1164 if (mGnssSystemInfoProvider != null) {
1165 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1166 } else {
Wyatt Riley49097c02018-03-15 09:14:43 -07001167 return null;
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001168 }
1169 }
1170
Wyatt Rileycf879db2017-01-12 13:57:38 -08001171 /**
1172 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1173 * (try to) access GNSS information at this layer.
1174 */
1175 private boolean hasGnssPermissions(String packageName) {
1176 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1177 checkResolutionLevelIsSufficientForProviderUse(
1178 allowedResolutionLevel,
1179 LocationManager.GPS_PROVIDER);
1180
1181 int pid = Binder.getCallingPid();
1182 int uid = Binder.getCallingUid();
1183 long identity = Binder.clearCallingIdentity();
1184 boolean hasLocationAccess;
1185 try {
1186 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1187 } finally {
1188 Binder.restoreCallingIdentity(identity);
1189 }
1190
1191 return hasLocationAccess;
1192 }
1193
1194 /**
1195 * Returns the GNSS batching size, if available.
1196 */
1197 @Override
1198 public int getGnssBatchSize(String packageName) {
1199 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1200 "Location Hardware permission not granted to access hardware batching");
1201
1202 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
Yu-Han Yang3557cc72018-03-21 12:48:36 -07001203 return mGnssBatchingProvider.getBatchSize();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001204 } else {
1205 return 0;
1206 }
1207 }
1208
1209 /**
1210 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1211 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1212 */
1213 @Override
1214 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1215 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1216 "Location Hardware permission not granted to access hardware batching");
1217
1218 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1219 return false;
1220 }
1221
1222 mGnssBatchingCallback = callback;
1223 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1224 try {
1225 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1226 } catch (RemoteException e) {
1227 // if the remote process registering the listener is already dead, just swallow the
1228 // exception and return
1229 Log.e(TAG, "Remote listener already died.", e);
1230 return false;
1231 }
1232
1233 return true;
1234 }
1235
1236 private class LinkedCallback implements IBinder.DeathRecipient {
1237 private final IBatchedLocationCallback mCallback;
1238
1239 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1240 mCallback = callback;
1241 }
1242
1243 @NonNull
1244 public IBatchedLocationCallback getUnderlyingListener() {
1245 return mCallback;
1246 }
1247
1248 @Override
1249 public void binderDied() {
1250 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1251 stopGnssBatch();
1252 removeGnssBatchingCallback();
1253 }
1254 }
1255
1256 /**
1257 * Removes callback for GNSS batching
1258 */
1259 @Override
1260 public void removeGnssBatchingCallback() {
1261 try {
1262 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1263 0 /* flags */);
1264 } catch (NoSuchElementException e) {
1265 // if the death callback isn't connected (it should be...), log error, swallow the
1266 // exception and return
1267 Log.e(TAG, "Couldn't unlink death callback.", e);
1268 }
1269 mGnssBatchingCallback = null;
1270 mGnssBatchingDeathCallback = null;
1271 }
1272
1273
1274 /**
1275 * Starts GNSS batching, if available.
1276 */
1277 @Override
1278 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1279 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1280 "Location Hardware permission not granted to access hardware batching");
1281
1282 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1283 return false;
1284 }
1285
1286 if (mGnssBatchingInProgress) {
1287 // Current design does not expect multiple starts to be called repeatedly
1288 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1289 // Try to clean up anyway, and continue
1290 stopGnssBatch();
1291 }
1292
1293 mGnssBatchingInProgress = true;
1294 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1295 }
1296
1297 /**
1298 * Flushes a GNSS batch in progress
1299 */
1300 @Override
1301 public void flushGnssBatch(String packageName) {
1302 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1303 "Location Hardware permission not granted to access hardware batching");
1304
1305 if (!hasGnssPermissions(packageName)) {
1306 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1307 return;
1308 }
1309
1310 if (!mGnssBatchingInProgress) {
1311 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1312 }
1313
1314 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001315 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001316 }
1317 }
1318
1319 /**
1320 * Stops GNSS batching
1321 */
1322 @Override
1323 public boolean stopGnssBatch() {
1324 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1325 "Location Hardware permission not granted to access hardware batching");
1326
1327 if (mGnssBatchingProvider != null) {
1328 mGnssBatchingInProgress = false;
1329 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001330 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001331 return false;
1332 }
1333 }
1334
1335 @Override
1336 public void reportLocationBatch(List<Location> locations) {
1337 checkCallerIsProvider();
1338
1339 // Currently used only for GNSS locations - update permissions check if changed
1340 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1341 if (mGnssBatchingCallback == null) {
1342 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1343 return;
1344 }
1345 try {
1346 mGnssBatchingCallback.onLocationBatch(locations);
1347 } catch (RemoteException e) {
1348 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1349 }
1350 } else {
1351 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1352 }
1353 }
1354
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001355 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001356 mProviders.add(provider);
1357 mProvidersByName.put(provider.getName(), provider);
1358 }
1359
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001360 private void removeProviderLocked(LocationProviderInterface provider) {
1361 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001362 mProviders.remove(provider);
1363 mProvidersByName.remove(provider.getName());
1364 }
1365
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001366 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001367 * Returns "true" if access to the specified location provider is allowed by the current
1368 * user's settings. Access to all location providers is forbidden to non-location-provider
1369 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001370 *
1371 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001372 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001373 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
Maggie2a9409e2018-03-21 11:47:28 -07001374 return isAllowedByUserSettingsLockedForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 }
1376
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001377 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001378 * Returns "true" if access to the specified location provider is allowed by the specified
1379 * user's settings. Access to all location providers is forbidden to non-location-provider
1380 * processes belonging to background users.
1381 *
1382 * @param provider the name of the location provider
Maggie2a9409e2018-03-21 11:47:28 -07001383 * @param userId the user id to query
Victoria Lease09eeaec2013-02-05 11:34:13 -08001384 */
Maggie2a9409e2018-03-21 11:47:28 -07001385 private boolean isAllowedByUserSettingsLockedForUser(String provider, int userId) {
1386 if (mEnabledProviders.contains(provider)) {
1387 return true;
1388 }
1389 if (mDisabledProviders.contains(provider)) {
1390 return false;
1391 }
1392 return isLocationProviderEnabledForUser(provider, userId);
1393 }
1394
1395
1396 /**
1397 * Returns "true" if access to the specified location provider is allowed by the specified
1398 * user's settings. Access to all location providers is forbidden to non-location-provider
1399 * processes belonging to background users.
1400 *
1401 * @param provider the name of the location provider
1402 * @param uid the requestor's UID
1403 * @param userId the user id to query
1404 */
1405 private boolean isAllowedByUserSettingsLocked(String provider, int uid, int userId) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001406 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001407 return false;
1408 }
Maggie2a9409e2018-03-21 11:47:28 -07001409 return isAllowedByUserSettingsLockedForUser(provider, userId);
Victoria Lease09eeaec2013-02-05 11:34:13 -08001410 }
1411
1412 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001413 * Returns the permission string associated with the specified resolution level.
1414 *
1415 * @param resolutionLevel the resolution level
1416 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001417 */
Victoria Lease37425c32012-10-16 16:08:48 -07001418 private String getResolutionPermission(int resolutionLevel) {
1419 switch (resolutionLevel) {
1420 case RESOLUTION_LEVEL_FINE:
1421 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1422 case RESOLUTION_LEVEL_COARSE:
1423 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1424 default:
1425 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001427 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001428
Victoria Leaseda479c52012-10-15 15:24:16 -07001429 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001430 * Returns the resolution level allowed to the given PID/UID pair.
1431 *
1432 * @param pid the PID
1433 * @param uid the UID
1434 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001435 */
Victoria Lease37425c32012-10-16 16:08:48 -07001436 private int getAllowedResolutionLevel(int pid, int uid) {
1437 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001438 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001439 return RESOLUTION_LEVEL_FINE;
1440 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001441 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001442 return RESOLUTION_LEVEL_COARSE;
1443 } else {
1444 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001445 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001446 }
1447
1448 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001449 * Returns the resolution level allowed to the caller
1450 *
1451 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001452 */
Victoria Lease37425c32012-10-16 16:08:48 -07001453 private int getCallerAllowedResolutionLevel() {
1454 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1455 }
1456
1457 /**
1458 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1459 *
1460 * @param allowedResolutionLevel resolution level allowed to caller
1461 */
1462 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1463 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001464 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
1467
Victoria Lease37425c32012-10-16 16:08:48 -07001468 /**
1469 * Return the minimum resolution level required to use the specified location provider.
1470 *
1471 * @param provider the name of the location provider
1472 * @return minimum resolution level required for provider
1473 */
1474 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001475 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1476 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1477 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001478 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001479 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1480 LocationManager.FUSED_PROVIDER.equals(provider)) {
1481 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001482 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001483 } else {
1484 // mock providers
1485 LocationProviderInterface lp = mMockProviders.get(provider);
1486 if (lp != null) {
1487 ProviderProperties properties = lp.getProperties();
1488 if (properties != null) {
1489 if (properties.mRequiresSatellite) {
1490 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001491 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001492 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1493 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001494 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001495 }
1496 }
1497 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001498 }
Victoria Lease37425c32012-10-16 16:08:48 -07001499 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001500 }
1501
Victoria Lease37425c32012-10-16 16:08:48 -07001502 /**
1503 * Throw SecurityException if specified resolution level is insufficient to use the named
1504 * location provider.
1505 *
1506 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001507 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001508 */
1509 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1510 String providerName) {
1511 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1512 if (allowedResolutionLevel < requiredResolutionLevel) {
1513 switch (requiredResolutionLevel) {
1514 case RESOLUTION_LEVEL_FINE:
1515 throw new SecurityException("\"" + providerName + "\" location provider " +
1516 "requires ACCESS_FINE_LOCATION permission.");
1517 case RESOLUTION_LEVEL_COARSE:
1518 throw new SecurityException("\"" + providerName + "\" location provider " +
1519 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1520 default:
1521 throw new SecurityException("Insufficient permission for \"" + providerName +
1522 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001523 }
1524 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001525 }
1526
David Christie82edc9b2013-07-19 11:31:42 -07001527 /**
1528 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1529 * for battery).
1530 */
David Christie40e57822013-07-30 11:36:48 -07001531 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001532 mContext.enforceCallingOrSelfPermission(
1533 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1534 }
1535
David Christie40e57822013-07-30 11:36:48 -07001536 private void checkUpdateAppOpsAllowed() {
1537 mContext.enforceCallingOrSelfPermission(
1538 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1539 }
1540
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001541 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001542 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1543 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001544 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001545 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001546 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001547 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001548 }
1549 return -1;
1550 }
1551
Wei Wangb86334f2018-07-03 16:33:24 -07001552 private static String resolutionLevelToOpStr(int allowedResolutionLevel) {
1553 switch(allowedResolutionLevel) {
1554 case RESOLUTION_LEVEL_COARSE:
1555 return AppOpsManager.OPSTR_COARSE_LOCATION;
1556 case RESOLUTION_LEVEL_FINE:
1557 return AppOpsManager.OPSTR_FINE_LOCATION;
1558 case RESOLUTION_LEVEL_NONE:
1559 // The client is not allowed to get any location, so both FINE and COARSE ops will
1560 // be denied. Pick the most restrictive one to be safe.
1561 return AppOpsManager.OPSTR_FINE_LOCATION;
1562 default:
1563 // Use the most restrictive ops if not sure.
1564 return AppOpsManager.OPSTR_FINE_LOCATION;
1565 }
1566 }
1567
David Christieb870dbf2015-06-22 12:42:53 -07001568 boolean reportLocationAccessNoThrow(
1569 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001570 int op = resolutionLevelToOp(allowedResolutionLevel);
1571 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001572 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1573 return false;
1574 }
1575 }
David Christieb870dbf2015-06-22 12:42:53 -07001576
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001577 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001578 }
1579
David Christieb870dbf2015-06-22 12:42:53 -07001580 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001581 int op = resolutionLevelToOp(allowedResolutionLevel);
1582 if (op >= 0) {
Wei Wangdd070f22018-06-21 11:29:40 -07001583 if (mAppOps.noteOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001584 return false;
1585 }
1586 }
David Christieb870dbf2015-06-22 12:42:53 -07001587
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001588 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001589 }
1590
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001591 /**
Maggie91e630c2018-01-24 17:31:46 -08001592 * Returns all providers by name, including passive and the ones that are not permitted to
1593 * be accessed by the calling activity or are currently disabled, but excluding fused.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001594 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001595 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 public List<String> getAllProviders() {
Maggie91e630c2018-01-24 17:31:46 -08001597 ArrayList<String> out;
1598 synchronized (mLock) {
1599 out = new ArrayList<>(mProviders.size());
1600 for (LocationProviderInterface provider : mProviders) {
1601 String name = provider.getName();
1602 if (LocationManager.FUSED_PROVIDER.equals(name)) {
1603 continue;
1604 }
1605 out.add(name);
1606 }
1607 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001608 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 return out;
1610 }
1611
Mike Lockwood03ca2162010-04-01 08:10:09 -07001612 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613 * Return all providers by name, that match criteria and are optionally
1614 * enabled.
1615 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001616 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001617 @Override
1618 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001619 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001620 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001621 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001622 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001623 try {
1624 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001625 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001626 for (LocationProviderInterface provider : mProviders) {
1627 String name = provider.getName();
1628 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001629 continue;
1630 }
Victoria Lease37425c32012-10-16 16:08:48 -07001631 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Maggie2a9409e2018-03-21 11:47:28 -07001632 if (enabledOnly
1633 && !isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001634 continue;
1635 }
1636 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1637 name, provider.getProperties(), criteria)) {
1638 continue;
1639 }
1640 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001641 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001642 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001643 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001644 } finally {
1645 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001646 }
1647
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001648 if (D) Log.d(TAG, "getProviders()=" + out);
1649 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001650 }
1651
1652 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001653 * Return the name of the best provider given a Criteria object.
1654 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001655 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001656 * has been deprecated as well. So this method now uses
1657 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001658 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001659 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001660 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001661 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001662
1663 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001664 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001665 result = pickBest(providers);
1666 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1667 return result;
1668 }
1669 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001670 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001671 result = pickBest(providers);
1672 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1673 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001674 }
1675
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001676 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001677 return null;
1678 }
1679
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001680 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001681 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001682 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001683 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1684 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001685 } else {
1686 return providers.get(0);
1687 }
1688 }
1689
Nick Pellye0fd6932012-07-11 10:26:13 -07001690 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001691 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1692 LocationProviderInterface p = mProvidersByName.get(provider);
1693 if (p == null) {
1694 throw new IllegalArgumentException("provider=" + provider);
1695 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001696
1697 boolean result = LocationProvider.propertiesMeetCriteria(
1698 p.getName(), p.getProperties(), criteria);
1699 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1700 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001701 }
1702
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001703 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001704 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001705 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001706 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 boolean isEnabled = p.isEnabled();
1708 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001709 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001711 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001712 // If any provider has been disabled, clear all last locations for all providers.
1713 // This is to be on the safe side in case a provider has location derived from
1714 // this disabled provider.
1715 mLastLocation.clear();
1716 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001717 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001719 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001720 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001722 }
1723 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001724 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1725 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001726 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1727 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729 }
1730
Amith Yamasanib27528d2014-06-05 15:02:10 -07001731 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 int listeners = 0;
1733
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001734 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001735 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736
1737 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001738
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1740 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001741 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001742 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001743 // Sends a notification message to the receiver
1744 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1745 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001746 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001747 }
1748 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001749 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001750 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753 }
1754
1755 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001756 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 removeUpdatesLocked(deadReceivers.get(i));
1758 }
1759 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001760
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 if (enabled) {
1762 p.enable();
Yu-Han Yanga4d250e2018-10-02 21:29:20 -07001763 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001769 private void applyRequirementsLocked(String provider) {
1770 LocationProviderInterface p = mProvidersByName.get(provider);
1771 if (p == null) return;
1772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001774 WorkSource worksource = new WorkSource();
1775 ProviderRequest providerRequest = new ProviderRequest();
1776
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001777 ContentResolver resolver = mContext.getContentResolver();
1778 long backgroundThrottleInterval = Settings.Global.getLong(
1779 resolver,
1780 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1781 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001782 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001783
gomo48f1a642017-11-10 20:35:46 -08001784 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001785 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001786 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001787 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001788 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001789 record.mReceiver.mIdentity.mPid,
1790 record.mReceiver.mIdentity.mUid,
1791 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001792 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001793 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001794 long interval = locationRequest.getInterval();
1795
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001796 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001797 if (!record.mIsForegroundUid) {
1798 interval = Math.max(interval, backgroundThrottleInterval);
1799 }
1800 if (interval != locationRequest.getInterval()) {
1801 locationRequest = new LocationRequest(locationRequest);
1802 locationRequest.setInterval(interval);
1803 }
1804 }
1805
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001806 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001807 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001808 if (!locationRequest.isLowPowerMode()) {
1809 providerRequest.lowPowerMode = false;
1810 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001811 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001812 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001813 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001814 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001815 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001816 }
1817 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001818
1819 if (providerRequest.reportLocation) {
1820 // calculate who to blame for power
1821 // This is somewhat arbitrary. We pick a threshold interval
1822 // that is slightly higher that the minimum interval, and
1823 // spread the blame across all applications with a request
1824 // under that threshold.
1825 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1826 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001827 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001828 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001829
1830 // Don't assign battery blame for update records whose
1831 // client has no permission to receive location data.
1832 if (!providerRequest.locationRequests.contains(locationRequest)) {
1833 continue;
1834 }
1835
Victoria Leaseb711d572012-10-02 13:14:11 -07001836 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001837 if (record.mReceiver.mWorkSource != null
Narayan Kamath32684dd2018-01-08 17:32:51 +00001838 && isValidWorkSource(record.mReceiver.mWorkSource)) {
David Christie82edc9b2013-07-19 11:31:42 -07001839 worksource.add(record.mReceiver.mWorkSource);
1840 } else {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001841 // Assign blame to caller if there's no WorkSource associated with
1842 // the request or if it's invalid.
David Christie82edc9b2013-07-19 11:31:42 -07001843 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001844 record.mReceiver.mIdentity.mUid,
1845 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001846 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001847 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001848 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 }
1851 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001852
1853 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1854 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
Narayan Kamath32684dd2018-01-08 17:32:51 +00001857 /**
1858 * Whether a given {@code WorkSource} associated with a Location request is valid.
1859 */
1860 private static boolean isValidWorkSource(WorkSource workSource) {
1861 if (workSource.size() > 0) {
1862 // If the WorkSource has one or more non-chained UIDs, make sure they're accompanied
1863 // by tags.
1864 return workSource.getName(0) != null;
1865 } else {
1866 // For now, make sure callers have supplied an attribution tag for use with
1867 // AppOpsManager. This might be relaxed in the future.
1868 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
1869 return workChains != null && !workChains.isEmpty() &&
1870 workChains.get(0).getAttributionTag() != null;
1871 }
1872 }
1873
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001874 @Override
1875 public String[] getBackgroundThrottlingWhitelist() {
1876 synchronized (mLock) {
1877 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001878 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001879 }
1880 }
1881
1882 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001883 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001884 mContext.getContentResolver(),
1885 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001886 if (setting == null) {
1887 setting = "";
1888 }
1889
1890 mBackgroundThrottlePackageWhitelist.clear();
1891 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001892 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001893 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001894 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001895 }
1896
Wei Wangdd070f22018-06-21 11:29:40 -07001897 private void updateLastLocationMaxAgeLocked() {
1898 mLastLocationMaxAgeMs =
1899 Settings.Global.getLong(
1900 mContext.getContentResolver(),
1901 Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS,
1902 DEFAULT_LAST_LOCATION_MAX_AGE_MS);
1903 }
1904
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001905 private boolean isThrottlingExemptLocked(Identity identity) {
1906 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001907 return true;
1908 }
1909
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001910 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001911 return true;
1912 }
1913
1914 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001915 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001916 return true;
1917 }
1918 }
1919
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001920 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001921 }
1922
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 private class UpdateRecord {
1924 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001925 final LocationRequest mRealRequest; // original request from client
1926 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001928 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001929 Location mLastFixBroadcast;
1930 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931
1932 /**
1933 * Note: must be constructed with lock held.
1934 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001935 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001937 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001938 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001940 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001941 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942
1943 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1944 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001945 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 mRecordsByProvider.put(provider, records);
1947 }
1948 if (!records.contains(this)) {
1949 records.add(this);
1950 }
David Christie2ff96af2014-01-30 16:09:37 -08001951
1952 // Update statistics for historical location requests by package/provider
1953 mRequestStatistics.startRequesting(
Wyatt Rileyf7075e02018-04-12 17:54:26 -07001954 mReceiver.mIdentity.mPackageName, provider, request.getInterval(),
1955 mIsForegroundUid);
1956 }
1957
1958 /**
1959 * Method to be called when record changes foreground/background
1960 */
1961 void updateForeground(boolean isForeground){
1962 mIsForegroundUid = isForeground;
1963 mRequestStatistics.updateForeground(
1964 mReceiver.mIdentity.mPackageName, mProvider, isForeground);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
1966
1967 /**
David Christie2ff96af2014-01-30 16:09:37 -08001968 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001970 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001971 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001972
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001973 // remove from mRecordsByProvider
1974 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1975 if (globalRecords != null) {
1976 globalRecords.remove(this);
1977 }
1978
1979 if (!removeReceiver) return; // the caller will handle the rest
1980
1981 // remove from Receiver#mUpdateRecords
1982 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1983 if (receiverRecords != null) {
1984 receiverRecords.remove(this.mProvider);
1985
1986 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001987 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001988 removeUpdatesLocked(mReceiver);
1989 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001990 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001991 }
1992
1993 @Override
1994 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001995 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001996 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1997 : " background")
Wyatt Riley19adc022018-05-22 13:30:51 -07001998 + ")" + " " + mRealRequest + " "
1999 + mReceiver.mWorkSource + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002001 }
2002
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002003 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07002004 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002005 IBinder binder = listener.asBinder();
2006 Receiver receiver = mReceivers.get(binder);
2007 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07002008 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
2009 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002010 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002011 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002012 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002013 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002014 return null;
2015 }
Wen Jingcb3ab222014-03-27 13:42:59 +08002016 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002017 }
2018 return receiver;
2019 }
2020
David Christie82edc9b2013-07-19 11:31:42 -07002021 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07002022 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002023 Receiver receiver = mReceivers.get(intent);
2024 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07002025 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
2026 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002027 mReceivers.put(intent, receiver);
2028 }
2029 return receiver;
2030 }
2031
Victoria Lease37425c32012-10-16 16:08:48 -07002032 /**
2033 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
2034 * and consistency requirements.
2035 *
2036 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07002037 * @return a version of request that meets the given resolution and consistency requirements
2038 * @hide
2039 */
gomo48f1a642017-11-10 20:35:46 -08002040 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
2041 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07002042 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08002043 if (!callerHasLocationHardwarePermission) {
2044 // allow setting low power mode only for callers with location hardware permission
2045 sanitizedRequest.setLowPowerMode(false);
2046 }
Victoria Lease37425c32012-10-16 16:08:48 -07002047 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
2048 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002049 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07002050 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07002051 break;
2052 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07002053 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07002054 break;
2055 }
2056 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07002057 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2058 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002059 }
Victoria Lease37425c32012-10-16 16:08:48 -07002060 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2061 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002062 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002063 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002064 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002065 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002066 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002067 }
Victoria Lease37425c32012-10-16 16:08:48 -07002068 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002069 }
2070
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002071 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002072 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002073 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002074 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002075 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002076 String[] packages = mPackageManager.getPackagesForUid(uid);
2077 if (packages == null) {
2078 throw new SecurityException("invalid UID " + uid);
2079 }
2080 for (String pkg : packages) {
2081 if (packageName.equals(pkg)) return;
2082 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002083 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002084 }
2085
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002086 private void checkPendingIntent(PendingIntent intent) {
2087 if (intent == null) {
2088 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002089 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002090 }
2091
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002092 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002093 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002094 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002095 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002096 } else if (intent != null && listener != null) {
2097 throw new IllegalArgumentException("cannot register both listener and intent");
2098 } else if (intent != null) {
2099 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002100 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002101 } else {
David Christie40e57822013-07-30 11:36:48 -07002102 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002103 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002104 }
2105
Nick Pellye0fd6932012-07-11 10:26:13 -07002106 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002107 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2108 PendingIntent intent, String packageName) {
2109 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2110 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002111 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2112 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2113 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002114 WorkSource workSource = request.getWorkSource();
Narayan Kamath32684dd2018-01-08 17:32:51 +00002115 if (workSource != null && !workSource.isEmpty()) {
David Christie40e57822013-07-30 11:36:48 -07002116 checkDeviceStatsAllowed();
2117 }
2118 boolean hideFromAppOps = request.getHideFromAppOps();
2119 if (hideFromAppOps) {
2120 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002121 }
gomo48f1a642017-11-10 20:35:46 -08002122 boolean callerHasLocationHardwarePermission =
2123 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002124 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002125 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2126 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002128 final int pid = Binder.getCallingPid();
2129 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002130 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 long identity = Binder.clearCallingIdentity();
2132 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002133 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2134 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002135 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002136
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002137 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002138 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002139 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002140 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 } finally {
2143 Binder.restoreCallingIdentity(identity);
2144 }
2145 }
2146
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002147 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2148 int pid, int uid, String packageName) {
2149 // Figure out the provider. Either its explicitly request (legacy use cases), or
2150 // use the fused provider
2151 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2152 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002153 if (name == null) {
2154 throw new IllegalArgumentException("provider name must not be null");
2155 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002156
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002157 LocationProviderInterface provider = mProvidersByName.get(name);
2158 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002159 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002160 }
2161
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002162 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002163 if (D) {
2164 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2165 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2166 + (record.mIsForegroundUid ? "foreground" : "background")
2167 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002168 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002169 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002170
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002171 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2172 if (oldRecord != null) {
2173 oldRecord.disposeLocked(false);
2174 }
2175
Maggie2a9409e2018-03-21 11:47:28 -07002176 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid, mCurrentUserId);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002177 if (isProviderEnabled) {
2178 applyRequirementsLocked(name);
2179 } else {
2180 // Notify the listener that updates are currently disabled
2181 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002182 }
David Christie0b837452013-07-29 16:02:13 -07002183 // Update the monitoring here just in case multiple location requests were added to the
2184 // same receiver (this request may be high power and the initial might not have been).
2185 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002186 }
2187
Nick Pellye0fd6932012-07-11 10:26:13 -07002188 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002189 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2190 String packageName) {
2191 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002192
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002193 final int pid = Binder.getCallingPid();
2194 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002195
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002196 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002197 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002198 boolean hideFromAppOps = false;
2199 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2200 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002201
2202 // providers may use public location API's, need to clear identity
2203 long identity = Binder.clearCallingIdentity();
2204 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002205 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002206 } finally {
2207 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002209 }
2210 }
2211
2212 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002213 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002214
2215 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2216 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2217 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002218 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002219 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002220 }
2221
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002222 receiver.updateMonitoring(false);
2223
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002224 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002225 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002226 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2227 if (oldRecords != null) {
2228 // Call dispose() on the obsolete update records.
2229 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002230 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002231 record.disposeLocked(false);
2232 }
2233 // Accumulate providers
2234 providers.addAll(oldRecords.keySet());
2235 }
2236
2237 // update provider
2238 for (String provider : providers) {
2239 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002240 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002241 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002242 }
2243
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002244 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246 }
2247
Dianne Hackbornc2293022013-02-06 23:14:49 -08002248 private void applyAllProviderRequirementsLocked() {
2249 for (LocationProviderInterface p : mProviders) {
2250 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002251 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002252 continue;
2253 }
2254
2255 applyRequirementsLocked(p.getName());
2256 }
2257 }
2258
Nick Pellye0fd6932012-07-11 10:26:13 -07002259 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002260 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002261 if (D) Log.d(TAG, "getLastLocation: " + request);
2262 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002263 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002264 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002265 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2266 request.getProvider());
2267 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002268
David Christieb870dbf2015-06-22 12:42:53 -07002269 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002270 final int uid = Binder.getCallingUid();
2271 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002272 try {
2273 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002274 if (D) {
2275 Log.d(TAG, "not returning last loc for blacklisted app: " +
2276 packageName);
2277 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002278 return null;
2279 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002280
David Christieb870dbf2015-06-22 12:42:53 -07002281 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002282 if (D) {
2283 Log.d(TAG, "not returning last loc for no op app: " +
2284 packageName);
2285 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002286 return null;
2287 }
2288
Victoria Leaseb711d572012-10-02 13:14:11 -07002289 synchronized (mLock) {
2290 // Figure out the provider. Either its explicitly request (deprecated API's),
2291 // or use the fused provider
2292 String name = request.getProvider();
2293 if (name == null) name = LocationManager.FUSED_PROVIDER;
2294 LocationProviderInterface provider = mProvidersByName.get(name);
2295 if (provider == null) return null;
2296
Maggie2a9409e2018-03-21 11:47:28 -07002297 if (!isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002298
David Christie1b9b7b12013-04-15 15:31:11 -07002299 Location location;
2300 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2301 // Make sure that an app with coarse permissions can't get frequent location
2302 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2303 location = mLastLocationCoarseInterval.get(name);
2304 } else {
2305 location = mLastLocation.get(name);
2306 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002307 if (location == null) {
2308 return null;
2309 }
Wei Wangdd070f22018-06-21 11:29:40 -07002310
2311 // Don't return stale location to apps with foreground-only location permission.
Wei Wangb86334f2018-07-03 16:33:24 -07002312 String op = resolutionLevelToOpStr(allowedResolutionLevel);
Wei Wangdd070f22018-06-21 11:29:40 -07002313 long locationAgeMs = SystemClock.elapsedRealtime() -
2314 location.getElapsedRealtimeNanos() / NANOS_PER_MILLI;
2315 if ((locationAgeMs > mLastLocationMaxAgeMs)
2316 && (mAppOps.unsafeCheckOp(op, uid, packageName)
2317 == AppOpsManager.MODE_FOREGROUND)) {
2318 return null;
2319 }
2320
Victoria Lease37425c32012-10-16 16:08:48 -07002321 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002322 Location noGPSLocation = location.getExtraLocation(
2323 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002324 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002325 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002326 }
Victoria Lease37425c32012-10-16 16:08:48 -07002327 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002328 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002329 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002330 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002331 return null;
2332 } finally {
2333 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002334 }
2335 }
2336
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002337 /**
2338 * Provides an interface to inject and set the last location if location is not available
2339 * currently.
2340 *
2341 * This helps in cases where the product (Cars for example) has saved the last known location
2342 * before powering off. This interface lets the client inject the saved location while the GPS
2343 * chipset is getting its first fix, there by improving user experience.
2344 *
2345 * @param location - Location object to inject
2346 * @return true if update was successful, false if not
2347 */
2348 @Override
2349 public boolean injectLocation(Location location) {
2350 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2351 "Location Hardware permission not granted to inject location");
2352 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2353 "Access Fine Location permission not granted to inject Location");
2354
2355 if (location == null) {
2356 if (D) {
2357 Log.d(TAG, "injectLocation(): called with null location");
2358 }
2359 return false;
2360 }
2361 LocationProviderInterface p = null;
2362 String provider = location.getProvider();
2363 if (provider != null) {
2364 p = mProvidersByName.get(provider);
2365 }
2366 if (p == null) {
2367 if (D) {
2368 Log.d(TAG, "injectLocation(): unknown provider");
2369 }
2370 return false;
2371 }
2372 synchronized (mLock) {
2373 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2374 if (D) {
2375 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2376 }
2377 return false;
2378 } else {
2379 // NOTE: If last location is already available, location is not injected. If
2380 // provider's normal source (like a GPS chipset) have already provided an output,
2381 // there is no need to inject this location.
2382 if (mLastLocation.get(provider) == null) {
2383 updateLastLocationLocked(location, provider);
2384 } else {
2385 if (D) {
2386 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2387 }
2388 return false;
2389 }
2390 }
2391 }
2392 return true;
2393 }
2394
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002395 @Override
2396 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2397 String packageName) {
2398 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002399 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2400 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002401 checkPendingIntent(intent);
2402 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002403 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2404 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002405 // Require that caller can manage given document
2406 boolean callerHasLocationHardwarePermission =
2407 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002408 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002409 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2410 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002411
Victoria Lease37425c32012-10-16 16:08:48 -07002412 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002413
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002414 // geo-fence manager uses the public location API, need to clear identity
2415 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002416 // TODO: http://b/23822629
2417 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002418 // temporary measure until geofences work for secondary users
2419 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2420 return;
2421 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002422 long identity = Binder.clearCallingIdentity();
2423 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002424 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2425 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002426 } finally {
2427 Binder.restoreCallingIdentity(identity);
2428 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002429 }
2430
2431 @Override
2432 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002433 checkPendingIntent(intent);
2434 checkPackageName(packageName);
2435
2436 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2437
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002438 // geo-fence manager uses the public location API, need to clear identity
2439 long identity = Binder.clearCallingIdentity();
2440 try {
2441 mGeofenceManager.removeFence(geofence, intent);
2442 } finally {
2443 Binder.restoreCallingIdentity(identity);
2444 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002445 }
2446
2447
2448 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002449 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002450 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002451 return false;
2452 }
2453
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002455 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002457 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 return false;
2459 }
2460 return true;
2461 }
2462
Nick Pellye0fd6932012-07-11 10:26:13 -07002463 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002464 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002465 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002466 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002467 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002468 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002469 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002471 }
2472 }
2473
Nick Pellye0fd6932012-07-11 10:26:13 -07002474 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002475 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002476 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002477 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002478 return false;
2479 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002480
2481 synchronized (mLock) {
2482 Identity callerIdentity
2483 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002484 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002485 long identity = Binder.clearCallingIdentity();
2486 try {
2487 if (isThrottlingExemptLocked(callerIdentity)
2488 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002489 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002490 return mGnssMeasurementsProvider.addListener(listener);
2491 }
2492 } finally {
2493 Binder.restoreCallingIdentity(identity);
2494 }
2495
2496 return true;
2497 }
destradaaea8a8a62014-06-23 18:19:03 -07002498 }
2499
2500 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002501 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2502 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002503 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002504 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002505 mGnssMeasurementsProvider.removeListener(listener);
2506 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002507 }
destradaaea8a8a62014-06-23 18:19:03 -07002508 }
2509
2510 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002511 public boolean addGnssNavigationMessageListener(
2512 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002513 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002514 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002515 return false;
2516 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002517
2518 synchronized (mLock) {
2519 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002520 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002521 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002522 long identity = Binder.clearCallingIdentity();
2523 try {
2524 if (isThrottlingExemptLocked(callerIdentity)
2525 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002526 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002527 return mGnssNavigationMessageProvider.addListener(listener);
2528 }
2529 } finally {
2530 Binder.restoreCallingIdentity(identity);
2531 }
2532
2533 return true;
2534 }
destradaa4b3e3932014-07-21 18:01:47 -07002535 }
2536
2537 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002538 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2539 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002540 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002541 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002542 mGnssNavigationMessageProvider.removeListener(listener);
2543 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002544 }
destradaa4b3e3932014-07-21 18:01:47 -07002545 }
2546
2547 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002549 if (provider == null) {
2550 // throw NullPointerException to remain compatible with previous implementation
2551 throw new NullPointerException();
2552 }
Victoria Lease37425c32012-10-16 16:08:48 -07002553 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2554 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002557 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002558 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2560 }
2561
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002562 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002563 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002564 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002565
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002566 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
2568 }
2569
Nick Pellye0fd6932012-07-11 10:26:13 -07002570 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002571 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002572 if (Binder.getCallingUid() != Process.myUid()) {
2573 throw new SecurityException(
2574 "calling sendNiResponse from outside of the system is not allowed");
2575 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002576 try {
2577 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002578 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002579 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002580 return false;
2581 }
2582 }
2583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002585 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002586 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002587 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002588 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002589 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002590 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002591 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002592 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002593 }
2594
Victoria Lease37425c32012-10-16 16:08:48 -07002595 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2596 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002597
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002598 LocationProviderInterface p;
2599 synchronized (mLock) {
2600 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002601 }
2602
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002603 if (p == null) return null;
2604 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002605 }
2606
Jason Monkb71218a2015-06-17 14:44:39 -04002607 /**
2608 * @return null if the provider does not exist
2609 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002610 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002611 */
2612 @Override
2613 public String getNetworkProviderPackage() {
2614 LocationProviderInterface p;
2615 synchronized (mLock) {
2616 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2617 return null;
2618 }
2619 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2620 }
2621
2622 if (p instanceof LocationProviderProxy) {
2623 return ((LocationProviderProxy) p).getConnectedPackageName();
2624 }
2625 return null;
2626 }
2627
Maggieaa080f92018-01-04 15:35:11 -08002628 /**
Maggie2a9409e2018-03-21 11:47:28 -07002629 * Returns the current location enabled/disabled status for a user
2630 *
2631 * @param userId the id of the user
2632 * @return true if location is enabled
2633 */
2634 @Override
2635 public boolean isLocationEnabledForUser(int userId) {
2636 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2637 checkInteractAcrossUsersPermission(userId);
2638
2639 long identity = Binder.clearCallingIdentity();
2640 try {
2641 synchronized (mLock) {
2642 final String allowedProviders = Settings.Secure.getStringForUser(
2643 mContext.getContentResolver(),
2644 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2645 userId);
2646 if (allowedProviders == null) {
2647 return false;
2648 }
2649 final List<String> providerList = Arrays.asList(allowedProviders.split(","));
2650 for(String provider : mRealProviders.keySet()) {
2651 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2652 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2653 continue;
2654 }
2655 if (providerList.contains(provider)) {
2656 return true;
2657 }
2658 }
2659 return false;
2660 }
2661 } finally {
2662 Binder.restoreCallingIdentity(identity);
2663 }
2664 }
2665
2666 /**
2667 * Enable or disable location for a user
2668 *
2669 * @param enabled true to enable location, false to disable location
2670 * @param userId the id of the user
2671 */
2672 @Override
2673 public void setLocationEnabledForUser(boolean enabled, int userId) {
2674 mContext.enforceCallingPermission(
2675 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2676 "Requires WRITE_SECURE_SETTINGS permission");
2677
2678 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2679 checkInteractAcrossUsersPermission(userId);
2680
2681 long identity = Binder.clearCallingIdentity();
2682 try {
2683 synchronized (mLock) {
2684 final Set<String> allRealProviders = mRealProviders.keySet();
2685 // Update all providers on device plus gps and network provider when disabling
2686 // location
2687 Set<String> allProvidersSet = new ArraySet<>(allRealProviders.size() + 2);
2688 allProvidersSet.addAll(allRealProviders);
2689 // When disabling location, disable gps and network provider that could have been
2690 // enabled by location mode api.
2691 if (enabled == false) {
2692 allProvidersSet.add(LocationManager.GPS_PROVIDER);
2693 allProvidersSet.add(LocationManager.NETWORK_PROVIDER);
2694 }
2695 if (allProvidersSet.isEmpty()) {
2696 return;
2697 }
2698 // to ensure thread safety, we write the provider name with a '+' or '-'
2699 // and let the SettingsProvider handle it rather than reading and modifying
2700 // the list of enabled providers.
2701 final String prefix = enabled ? "+" : "-";
2702 StringBuilder locationProvidersAllowed = new StringBuilder();
2703 for (String provider : allProvidersSet) {
2704 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2705 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2706 continue;
2707 }
2708 locationProvidersAllowed.append(prefix);
2709 locationProvidersAllowed.append(provider);
2710 locationProvidersAllowed.append(",");
2711 }
2712 // Remove the trailing comma
2713 locationProvidersAllowed.setLength(locationProvidersAllowed.length() - 1);
2714 Settings.Secure.putStringForUser(
2715 mContext.getContentResolver(),
2716 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2717 locationProvidersAllowed.toString(),
2718 userId);
2719 }
2720 } finally {
2721 Binder.restoreCallingIdentity(identity);
2722 }
2723 }
2724
2725 /**
2726 * Returns the current enabled/disabled status of a location provider and user
2727 *
2728 * @param provider name of the provider
2729 * @param userId the id of the user
2730 * @return true if the provider exists and is enabled
2731 */
2732 @Override
2733 public boolean isProviderEnabledForUser(String provider, int userId) {
2734 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2735 checkInteractAcrossUsersPermission(userId);
2736
2737 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2738 // so we discourage its use
2739 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2740
2741 int uid = Binder.getCallingUid();
2742 synchronized (mLock) {
2743 LocationProviderInterface p = mProvidersByName.get(provider);
2744 return p != null
2745 && isAllowedByUserSettingsLocked(provider, uid, userId);
2746 }
2747 }
2748
2749 /**
2750 * Enable or disable a single location provider.
2751 *
2752 * @param provider name of the provider
2753 * @param enabled true to enable the provider. False to disable the provider
2754 * @param userId the id of the user to set
2755 * @return true if the value was set, false on errors
2756 */
2757 @Override
2758 public boolean setProviderEnabledForUser(String provider, boolean enabled, int userId) {
2759 mContext.enforceCallingPermission(
2760 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2761 "Requires WRITE_SECURE_SETTINGS permission");
2762
2763 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2764 checkInteractAcrossUsersPermission(userId);
2765
2766 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2767 // so we discourage its use
2768 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2769
2770 long identity = Binder.clearCallingIdentity();
2771 try {
2772 synchronized (mLock) {
2773 // No such provider exists
2774 if (!mProvidersByName.containsKey(provider)) return false;
2775
2776 // If it is a test provider, do not write to Settings.Secure
2777 if (mMockProviders.containsKey(provider)) {
2778 setTestProviderEnabled(provider, enabled);
2779 return true;
2780 }
2781
2782 // to ensure thread safety, we write the provider name with a '+' or '-'
2783 // and let the SettingsProvider handle it rather than reading and modifying
2784 // the list of enabled providers.
2785 String providerChange = (enabled ? "+" : "-") + provider;
2786 return Settings.Secure.putStringForUser(
2787 mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2788 providerChange, userId);
2789 }
2790 } finally {
2791 Binder.restoreCallingIdentity(identity);
2792 }
2793 }
2794
2795 /**
Maggieaa080f92018-01-04 15:35:11 -08002796 * Read location provider status from Settings.Secure
2797 *
2798 * @param provider the location provider to query
2799 * @param userId the user id to query
2800 * @return true if the provider is enabled
2801 */
2802 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2803 long identity = Binder.clearCallingIdentity();
2804 try {
2805 // Use system settings
2806 ContentResolver cr = mContext.getContentResolver();
2807 String allowedProviders = Settings.Secure.getStringForUser(
2808 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2809 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2810 } finally {
2811 Binder.restoreCallingIdentity(identity);
2812 }
2813 }
2814
2815 /**
Maggie2a9409e2018-03-21 11:47:28 -07002816 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2817 * current user id
2818 *
2819 * @param userId the user id to get or set value
2820 */
2821 private void checkInteractAcrossUsersPermission(int userId) {
2822 int uid = Binder.getCallingUid();
2823 if (UserHandle.getUserId(uid) != userId) {
2824 if (ActivityManager.checkComponentPermission(
2825 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2826 != PERMISSION_GRANTED) {
2827 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2828 }
2829 }
2830 }
2831
2832 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002833 * Returns "true" if the UID belongs to a bound location provider.
2834 *
2835 * @param uid the uid
2836 * @return true if uid belongs to a bound location provider
2837 */
2838 private boolean isUidALocationProvider(int uid) {
2839 if (uid == Process.SYSTEM_UID) {
2840 return true;
2841 }
2842 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002843 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002844 }
2845 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002846 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002847 }
2848 return false;
2849 }
2850
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002851 private void checkCallerIsProvider() {
2852 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002853 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002854 return;
2855 }
2856
2857 // Previously we only used the INSTALL_LOCATION_PROVIDER
2858 // check. But that is system or signature
2859 // protection level which is not flexible enough for
2860 // providers installed oustide the system image. So
2861 // also allow providers with a UID matching the
2862 // currently bound package name
2863
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002864 if (isUidALocationProvider(Binder.getCallingUid())) {
2865 return;
2866 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002867
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002868 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2869 "or UID of a currently bound location provider");
2870 }
2871
David Christie1f141c12014-05-14 15:11:15 -07002872 /**
2873 * Returns true if the given package belongs to the given uid.
2874 */
2875 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002876 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 return false;
2878 }
David Christie1f141c12014-05-14 15:11:15 -07002879 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2880 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002881 return false;
2882 }
David Christie1f141c12014-05-14 15:11:15 -07002883 for (String name : packageNames) {
2884 if (packageName.equals(name)) {
2885 return true;
2886 }
2887 }
2888 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 }
2890
Nick Pellye0fd6932012-07-11 10:26:13 -07002891 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002892 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002893 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002894
Nick Pelly2eeeec22012-07-18 13:13:37 -07002895 if (!location.isComplete()) {
2896 Log.w(TAG, "Dropping incomplete location: " + location);
2897 return;
2898 }
2899
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002900 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2901 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002902 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002903 mLocationHandler.sendMessageAtFrontOfQueue(m);
2904 }
2905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002906
Laurent Tu75defb62012-11-01 16:21:52 -07002907 private static boolean shouldBroadcastSafe(
2908 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 // Always broadcast the first update
2910 if (lastLoc == null) {
2911 return true;
2912 }
2913
Nick Pellyf1be6862012-05-15 10:53:42 -07002914 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002915 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002916 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2917 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002918 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002919 return false;
2920 }
2921
2922 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002923 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002924 if (minDistance > 0.0) {
2925 if (loc.distanceTo(lastLoc) <= minDistance) {
2926 return false;
2927 }
2928 }
2929
Laurent Tu75defb62012-11-01 16:21:52 -07002930 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002931 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002932 return false;
2933 }
2934
2935 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002936 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
2938
Mike Lockwooda4903f22010-02-17 06:42:23 -05002939 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002940 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002941 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002942 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002943 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002944 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002945 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002946 updateLastLocationLocked(location, provider);
2947 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002948 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002949 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002950 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2951 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002952 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953
David Christie1b9b7b12013-04-15 15:31:11 -07002954 // Update last known coarse interval location if enough time has passed.
2955 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2956 if (lastLocationCoarseInterval == null) {
2957 lastLocationCoarseInterval = new Location(location);
2958 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2959 }
2960 long timeDiffNanos = location.getElapsedRealtimeNanos()
2961 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2962 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2963 lastLocationCoarseInterval.set(location);
2964 }
2965 // Don't ever return a coarse location that is more recent than the allowed update
2966 // interval (i.e. don't allow an app to keep registering and unregistering for
2967 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002968 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002969 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2970
Laurent Tu60ec50a2012-10-04 17:00:10 -07002971 // Skip if there are no UpdateRecords for this provider.
2972 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2973 if (records == null || records.size() == 0) return;
2974
Victoria Lease09016ab2012-09-16 12:33:15 -07002975 // Fetch coarse location
2976 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002977 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002978 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2979 }
2980
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981 // Fetch latest status update time
2982 long newStatusUpdateTime = p.getStatusUpdateTime();
2983
David Christie2ff96af2014-01-30 16:09:37 -08002984 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 Bundle extras = new Bundle();
2986 int status = p.getStatus(extras);
2987
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002989 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002990
Soonil Nagarkar94749f72018-11-08 11:46:43 -08002991 // Broadcast location to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002992 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002994 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002995
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002996 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2997 if (!isCurrentProfile(receiverUserId)
2998 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002999 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07003000 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07003001 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003002 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07003003 }
3004 continue;
3005 }
3006
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003007 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08003008 if (D) {
3009 Log.d(TAG, "skipping loc update for blacklisted app: " +
3010 receiver.mIdentity.mPackageName);
3011 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003012 continue;
3013 }
3014
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003015 if (!reportLocationAccessNoThrow(
3016 receiver.mIdentity.mPid,
3017 receiver.mIdentity.mUid,
3018 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003019 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08003020 if (D) {
3021 Log.d(TAG, "skipping loc update for no op app: " +
3022 receiver.mIdentity.mPackageName);
3023 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003024 continue;
3025 }
3026
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003027 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07003028 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
3029 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003030 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07003031 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003032 }
Victoria Lease09016ab2012-09-16 12:33:15 -07003033 if (notifyLocation != null) {
3034 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07003035 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07003036 if (lastLoc == null) {
3037 lastLoc = new Location(notifyLocation);
3038 r.mLastFixBroadcast = lastLoc;
3039 } else {
3040 lastLoc.set(notifyLocation);
3041 }
3042 if (!receiver.callLocationChangedLocked(notifyLocation)) {
3043 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
3044 receiverDead = true;
3045 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07003046 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003047 }
3048 }
3049
Soonil Nagarkar94749f72018-11-08 11:46:43 -08003050 // TODO: location provider status callbacks have been disabled and deprecated, and are
3051 // guarded behind this setting now. should be removed completely post-Q
3052 if (Settings.Global.getInt(mContext.getContentResolver(),
3053 LOCATION_DISABLE_STATUS_CALLBACKS, 1) == 0) {
3054 long prevStatusUpdateTime = r.mLastStatusBroadcast;
3055 if ((newStatusUpdateTime > prevStatusUpdateTime)
3056 && (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057
Soonil Nagarkar94749f72018-11-08 11:46:43 -08003058 r.mLastStatusBroadcast = newStatusUpdateTime;
3059 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
3060 receiverDead = true;
3061 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
3062 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07003063 }
3064 }
3065
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003066 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07003067 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003068 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003069 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003070 }
3071 deadUpdateRecords.add(r);
3072 }
3073 // track dead receivers
3074 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07003075 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003076 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07003077 }
3078 if (!deadReceivers.contains(receiver)) {
3079 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003080 }
3081 }
3082 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003083
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003084 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003086 for (Receiver receiver : deadReceivers) {
3087 removeUpdatesLocked(receiver);
3088 }
3089 }
3090 if (deadUpdateRecords != null) {
3091 for (UpdateRecord r : deadUpdateRecords) {
3092 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
Victoria Lease8b38b292012-12-04 15:04:43 -08003094 applyRequirementsLocked(provider);
3095 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 }
3097
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08003098 /**
3099 * Updates last location with the given location
3100 *
3101 * @param location new location to update
3102 * @param provider Location provider to update for
3103 */
3104 private void updateLastLocationLocked(Location location, String provider) {
3105 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3106 Location lastNoGPSLocation;
3107 Location lastLocation = mLastLocation.get(provider);
3108 if (lastLocation == null) {
3109 lastLocation = new Location(provider);
3110 mLastLocation.put(provider, lastLocation);
3111 } else {
3112 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3113 if (noGPSLocation == null && lastNoGPSLocation != null) {
3114 // New location has no no-GPS location: adopt last no-GPS location. This is set
3115 // directly into location because we do not want to notify COARSE clients.
3116 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
3117 }
3118 }
3119 lastLocation.set(location);
3120 }
3121
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003122 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003123 public LocationWorkerHandler(Looper looper) {
3124 super(looper, null, true);
3125 }
3126
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 @Override
3128 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003129 switch (msg.what) {
3130 case MSG_LOCATION_CHANGED:
3131 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3132 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 }
3134 }
3135 }
3136
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003137 private boolean isMockProvider(String provider) {
3138 synchronized (mLock) {
3139 return mMockProviders.containsKey(provider);
3140 }
3141 }
3142
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003143 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003144 // create a working copy of the incoming Location so that the service can modify it without
3145 // disturbing the caller's copy
3146 Location myLocation = new Location(location);
3147 String provider = myLocation.getProvider();
3148
3149 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3150 // bit if location did not come from a mock provider because passive/fused providers can
3151 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3152 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3153 myLocation.setIsFromMockProvider(true);
3154 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003155
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003156 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003157 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3158 if (!passive) {
3159 // notify passive provider of the new location
3160 mPassiveProvider.updateLocation(myLocation);
3161 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003162 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166
Mike Lockwoode97ae402010-09-29 15:23:46 -04003167 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3168 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003169 public void onPackageDisappeared(String packageName, int reason) {
3170 // remove all receivers associated with this package name
3171 synchronized (mLock) {
3172 ArrayList<Receiver> deadReceivers = null;
3173
3174 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003175 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003176 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003177 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003178 }
3179 deadReceivers.add(receiver);
3180 }
3181 }
3182
3183 // perform removal outside of mReceivers loop
3184 if (deadReceivers != null) {
3185 for (Receiver receiver : deadReceivers) {
3186 removeUpdatesLocked(receiver);
3187 }
3188 }
3189 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003190 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003191 };
3192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003193 // Geocoder
3194
Nick Pellye0fd6932012-07-11 10:26:13 -07003195 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003196 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003197 return mGeocodeProvider != null;
3198 }
3199
Nick Pellye0fd6932012-07-11 10:26:13 -07003200 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003201 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003202 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003203 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003204 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3205 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003207 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
3209
Mike Lockwooda55c3212009-04-15 11:10:11 -04003210
Nick Pellye0fd6932012-07-11 10:26:13 -07003211 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003213 double lowerLeftLatitude, double lowerLeftLongitude,
3214 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003215 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003216
3217 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003218 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3219 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3220 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003221 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003222 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224
3225 // Mock Providers
3226
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003227 private boolean canCallerAccessMockLocation(String opPackageName) {
3228 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3229 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 }
3231
Nick Pellye0fd6932012-07-11 10:26:13 -07003232 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003233 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3234 if (!canCallerAccessMockLocation(opPackageName)) {
3235 return;
3236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003237
Mike Lockwooda4903f22010-02-17 06:42:23 -05003238 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3239 throw new IllegalArgumentException("Cannot mock the passive location provider");
3240 }
3241
Mike Lockwood86328a92009-10-23 08:38:25 -04003242 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003243 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003244 // remove the real provider if we are replacing GPS or network provider
3245 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003246 || LocationManager.NETWORK_PROVIDER.equals(name)
3247 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003248 LocationProviderInterface p = mProvidersByName.get(name);
3249 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003250 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003251 }
3252 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003253 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 updateProvidersLocked();
3255 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003256 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 }
3258
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003259 private void addTestProviderLocked(String name, ProviderProperties properties) {
3260 if (mProvidersByName.get(name) != null) {
3261 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3262 }
3263 MockProvider provider = new MockProvider(name, this, properties);
3264 addProviderLocked(provider);
3265 mMockProviders.put(name, provider);
3266 mLastLocation.put(name, null);
3267 mLastLocationCoarseInterval.put(name, null);
3268 }
3269
Nick Pellye0fd6932012-07-11 10:26:13 -07003270 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003271 public void removeTestProvider(String provider, String opPackageName) {
3272 if (!canCallerAccessMockLocation(opPackageName)) {
3273 return;
3274 }
3275
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003276 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003277
3278 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003279 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003280 clearTestProviderEnabled(provider, opPackageName);
3281 clearTestProviderLocation(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003282
You Kima6d0b6f2012-10-28 03:58:44 +09003283 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003284 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3286 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003287 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003288 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003289
3290 // reinstate real provider if available
3291 LocationProviderInterface realProvider = mRealProviders.get(provider);
3292 if (realProvider != null) {
3293 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003294 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003295 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003296 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003298 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
3300 }
3301
Nick Pellye0fd6932012-07-11 10:26:13 -07003302 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003303 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3304 if (!canCallerAccessMockLocation(opPackageName)) {
3305 return;
3306 }
3307
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003308 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003309 MockProvider mockProvider = mMockProviders.get(provider);
3310 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3312 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003313
3314 // Ensure that the location is marked as being mock. There's some logic to do this in
3315 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3316 Location mock = new Location(loc);
3317 mock.setIsFromMockProvider(true);
3318
3319 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3320 // The location has an explicit provider that is different from the mock provider
3321 // name. The caller may be trying to fool us via bug 33091107.
3322 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3323 provider + "!=" + loc.getProvider());
3324 }
3325
Mike Lockwood95427cd2009-05-07 13:27:54 -04003326 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3327 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003328 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003329 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 }
3331 }
3332
Nick Pellye0fd6932012-07-11 10:26:13 -07003333 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003334 public void clearTestProviderLocation(String provider, String opPackageName) {
3335 if (!canCallerAccessMockLocation(opPackageName)) {
3336 return;
3337 }
3338
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003339 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003340 MockProvider mockProvider = mMockProviders.get(provider);
3341 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003342 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3343 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003344 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 }
3346 }
3347
Nick Pellye0fd6932012-07-11 10:26:13 -07003348 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003349 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3350 if (!canCallerAccessMockLocation(opPackageName)) {
3351 return;
3352 }
Maggie2a9409e2018-03-21 11:47:28 -07003353 setTestProviderEnabled(provider, enabled);
3354 }
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003355
Maggie2a9409e2018-03-21 11:47:28 -07003356 /** Enable or disable a test location provider. */
3357 private void setTestProviderEnabled(String provider, boolean enabled) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003358 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003359 MockProvider mockProvider = mMockProviders.get(provider);
3360 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3362 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003363 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003365 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 mEnabledProviders.add(provider);
3367 mDisabledProviders.remove(provider);
3368 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003369 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 mEnabledProviders.remove(provider);
3371 mDisabledProviders.add(provider);
3372 }
3373 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003374 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003375 }
3376 }
3377
Nick Pellye0fd6932012-07-11 10:26:13 -07003378 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003379 public void clearTestProviderEnabled(String provider, String opPackageName) {
3380 if (!canCallerAccessMockLocation(opPackageName)) {
3381 return;
3382 }
3383
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003384 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003385 MockProvider mockProvider = mMockProviders.get(provider);
3386 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003387 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3388 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003389 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 mEnabledProviders.remove(provider);
3391 mDisabledProviders.remove(provider);
3392 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003393 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003394 }
3395 }
3396
Nick Pellye0fd6932012-07-11 10:26:13 -07003397 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003398 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3399 String opPackageName) {
3400 if (!canCallerAccessMockLocation(opPackageName)) {
3401 return;
3402 }
3403
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003404 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003405 MockProvider mockProvider = mMockProviders.get(provider);
3406 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3408 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003409 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
3411 }
3412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 private void log(String log) {
3414 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003415 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003416 }
3417 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003418
3419 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003421 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003422
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003423 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003424 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3425 if (mGnssMetricsProvider != null) {
3426 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3427 }
3428 return;
3429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003432 for (Receiver receiver : mReceivers.values()) {
3433 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003434 }
David Christie2ff96af2014-01-30 16:09:37 -08003435 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003436 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3437 pw.println(" " + entry.getKey() + ":");
3438 for (UpdateRecord record : entry.getValue()) {
3439 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 }
3441 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003442 pw.println(" Active GnssMeasurement Listeners:");
3443 for (Identity identity : mGnssMeasurementsListeners.values()) {
3444 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3445 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3446 }
3447 pw.println(" Active GnssNavigationMessage Listeners:");
3448 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3449 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3450 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3451 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003452 pw.println(" Overlay Provider Packages:");
3453 for (LocationProviderInterface provider : mProviders) {
3454 if (provider instanceof LocationProviderProxy) {
3455 pw.println(" " + provider.getName() + ": "
3456 + ((LocationProviderProxy) provider).getConnectedPackageName());
3457 }
3458 }
David Christie2ff96af2014-01-30 16:09:37 -08003459 pw.println(" Historical Records by Provider:");
3460 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3461 : mRequestStatistics.statistics.entrySet()) {
3462 PackageProviderKey key = entry.getKey();
3463 PackageStatistics stats = entry.getValue();
3464 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003467 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3468 String provider = entry.getKey();
3469 Location location = entry.getValue();
3470 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003471 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003472
David Christie1b9b7b12013-04-15 15:31:11 -07003473 pw.println(" Last Known Locations Coarse Intervals:");
3474 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3475 String provider = entry.getKey();
3476 Location location = entry.getValue();
3477 pw.println(" " + provider + ": " + location);
3478 }
3479
Nick Pellye0fd6932012-07-11 10:26:13 -07003480 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 if (mEnabledProviders.size() > 0) {
3483 pw.println(" Enabled Providers:");
3484 for (String i : mEnabledProviders) {
3485 pw.println(" " + i);
3486 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003487
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 }
3489 if (mDisabledProviders.size() > 0) {
3490 pw.println(" Disabled Providers:");
3491 for (String i : mDisabledProviders) {
3492 pw.println(" " + i);
3493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003495 pw.append(" ");
3496 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 if (mMockProviders.size() > 0) {
3498 pw.println(" Mock Providers:");
3499 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003500 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 }
3502 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003503
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003504 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3505 pw.println(" Throttling Whitelisted Packages:");
3506 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3507 pw.println(" " + packageName);
3508 }
3509 }
3510
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003511 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003512 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003513
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003514 if (args.length > 0 && "short".equals(args[0])) {
3515 return;
3516 }
gomo48f1a642017-11-10 20:35:46 -08003517 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003518 pw.print(provider.getName() + " Internal State");
3519 if (provider instanceof LocationProviderProxy) {
3520 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3521 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003522 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003523 pw.println(":");
3524 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003525 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003526 if (mGnssBatchingInProgress) {
3527 pw.println(" GNSS batching in progress");
3528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 }
3530 }
3531}