blob: e5275e50e484ea2dc3fd4730a2f9a3b8ae216bc6 [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
Philip P. Moltmanned988282018-11-07 16:19:42 -080022import android.Manifest;
Wyatt Rileycf879db2017-01-12 13:57:38 -080023import android.annotation.NonNull;
Wyatt Riley49097c02018-03-15 09:14:43 -070024import android.annotation.Nullable;
Maggieaa080f92018-01-04 15:35:11 -080025import android.app.ActivityManager;
26import android.app.AppOpsManager;
27import android.app.PendingIntent;
28import android.content.BroadcastReceiver;
29import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.ApplicationInfo;
34import android.content.pm.PackageInfo;
35import android.content.pm.PackageManager;
36import android.content.pm.PackageManager.NameNotFoundException;
37import android.content.pm.PackageManagerInternal;
38import android.content.pm.ResolveInfo;
39import android.content.pm.Signature;
40import android.content.res.Resources;
41import android.database.ContentObserver;
42import android.hardware.location.ActivityRecognitionHardware;
43import android.location.Address;
44import android.location.Criteria;
45import android.location.GeocoderParams;
46import android.location.Geofence;
47import android.location.IBatchedLocationCallback;
48import android.location.IGnssMeasurementsListener;
49import android.location.IGnssNavigationMessageListener;
50import android.location.IGnssStatusListener;
51import android.location.IGnssStatusProvider;
52import android.location.IGpsGeofenceHardware;
53import android.location.ILocationListener;
54import android.location.ILocationManager;
55import android.location.INetInitiatedListener;
56import android.location.Location;
57import android.location.LocationManager;
58import android.location.LocationProvider;
59import android.location.LocationRequest;
60import android.os.Binder;
61import android.os.Bundle;
62import android.os.Handler;
63import android.os.IBinder;
64import android.os.Looper;
65import android.os.Message;
66import android.os.PowerManager;
67import android.os.Process;
68import android.os.RemoteException;
69import android.os.SystemClock;
70import android.os.UserHandle;
71import android.os.UserManager;
72import android.os.WorkSource;
Narayan Kamath32684dd2018-01-08 17:32:51 +000073import android.os.WorkSource.WorkChain;
Maggieaa080f92018-01-04 15:35:11 -080074import android.provider.Settings;
75import android.text.TextUtils;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080076import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080077import android.util.ArraySet;
Maggieaa080f92018-01-04 15:35:11 -080078import android.util.EventLog;
79import android.util.Log;
80import android.util.Slog;
Yu-Han Yanga4d250e2018-10-02 21:29:20 -070081
destradaaea8a8a62014-06-23 18:19:03 -070082import com.android.internal.content.PackageMonitor;
83import com.android.internal.location.ProviderProperties;
84import com.android.internal.location.ProviderRequest;
85import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070086import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060087import com.android.internal.util.DumpUtils;
Philip P. Moltmanned988282018-11-07 16:19:42 -080088import com.android.internal.util.Preconditions;
destradaaa4fa3b52014-07-09 10:46:39 -070089import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070090import com.android.server.location.GeocoderProxy;
91import com.android.server.location.GeofenceManager;
92import com.android.server.location.GeofenceProxy;
Yu-Han Yang3557cc72018-03-21 12:48:36 -070093import com.android.server.location.GnssBatchingProvider;
Lifu Tang818aa2c2016-02-01 01:52:00 -080094import com.android.server.location.GnssLocationProvider;
95import com.android.server.location.GnssMeasurementsProvider;
96import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070097import com.android.server.location.LocationBlacklist;
98import com.android.server.location.LocationFudger;
99import com.android.server.location.LocationProviderInterface;
100import com.android.server.location.LocationProviderProxy;
101import com.android.server.location.LocationRequestStatistics;
102import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
103import com.android.server.location.LocationRequestStatistics.PackageStatistics;
104import com.android.server.location.MockProvider;
105import com.android.server.location.PassiveProvider;
Yu-Han Yanga4d250e2018-10-02 21:29:20 -0700106
Mike Lockwood43e33f22010-03-26 10:41:48 -0400107import java.io.FileDescriptor;
108import java.io.PrintWriter;
109import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700110import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400111import java.util.HashMap;
112import java.util.HashSet;
113import java.util.List;
114import java.util.Map;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800115import java.util.Map.Entry;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800116import java.util.NoSuchElementException;
Philip P. Moltmanned988282018-11-07 16:19:42 -0800117import java.util.Objects;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400118import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
120/**
121 * The service class that manages LocationProviders and issues location
122 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800124public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800126 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700127
Olivier Gaillard7a222662017-11-20 16:07:24 +0000128 private static final String WAKELOCK_KEY = "*location*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800129
Victoria Lease37425c32012-10-16 16:08:48 -0700130 // Location resolution level: no location data whatsoever
131 private static final int RESOLUTION_LEVEL_NONE = 0;
132 // Location resolution level: coarse location data only
133 private static final int RESOLUTION_LEVEL_COARSE = 1;
134 // Location resolution level: fine location data
135 private static final int RESOLUTION_LEVEL_FINE = 2;
136
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700138 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700140 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400141 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700142 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
143
144 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700145 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700146 private static final String FUSED_LOCATION_SERVICE_ACTION =
147 "com.android.location.service.FusedLocationProvider";
148
149 private static final int MSG_LOCATION_CHANGED = 1;
150
David Christie1b9b7b12013-04-15 15:31:11 -0700151 private static final long NANOS_PER_MILLI = 1000000L;
152
David Christie0b837452013-07-29 16:02:13 -0700153 // The maximum interval a location request can have and still be considered "high power".
154 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
155
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700156 private static final int FOREGROUND_IMPORTANCE_CUTOFF
gomo48f1a642017-11-10 20:35:46 -0800157 = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700158
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800159 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800160 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800161
Wei Wangdd070f22018-06-21 11:29:40 -0700162 // Default value for maximum age of last location returned to applications with foreground-only
163 // location permissions.
164 private static final long DEFAULT_LAST_LOCATION_MAX_AGE_MS = 20 * 60 * 1000;
165
Nick Pellyf1be6862012-05-15 10:53:42 -0700166 // Location Providers may sometimes deliver location updates
167 // slightly faster that requested - provide grace period so
168 // we don't unnecessarily filter events that are otherwise on
169 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700170 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700171
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
173
174 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800175 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700176
177 // used internally for synchronization
178 private final Object mLock = new Object();
179
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700180 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700181 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700182 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700183 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700184 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800185 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700186 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700187 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800188 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700189 private INetInitiatedListener mNetInitiatedListener;
190 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700191 private PassiveProvider mPassiveProvider; // track passive provider for special cases
192 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800193 private GnssMeasurementsProvider mGnssMeasurementsProvider;
194 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700195 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700196
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700197 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700199 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800200 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
202 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800203 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700205 // Mock (test) providers
206 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800207 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800210 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700212 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500213 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800214 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400215
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700216 // real providers, saved here when mocked out
217 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800218 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700220 // mapping from provider name to provider
221 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800222 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700224 // mapping from provider name to all its UpdateRecords
225 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800226 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700227
David Christie2ff96af2014-01-30 16:09:37 -0800228 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
229
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700230 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800231 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
David Christie1b9b7b12013-04-15 15:31:11 -0700233 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
234 // locations stored here are not fudged for coarse permissions.
235 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800236 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700237
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800238 // all providers that operate over proxy, for authorizing incoming location and whitelisting
239 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700240 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800241 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800243 private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800244
Wyatt Riley11cc7492018-01-17 08:48:27 -0800245 private final ArrayMap<IBinder, Identity> mGnssMeasurementsListeners = new ArrayMap<>();
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800246
Wyatt Riley11cc7492018-01-17 08:48:27 -0800247 private final ArrayMap<IBinder, Identity>
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800248 mGnssNavigationMessageListeners = new ArrayMap<>();
249
Victoria Lease38389b62012-09-30 11:44:22 -0700250 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700251 private int mCurrentUserId = UserHandle.USER_SYSTEM;
gomo48f1a642017-11-10 20:35:46 -0800252 private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
Victoria Lease38389b62012-09-30 11:44:22 -0700253
Wei Wangdd070f22018-06-21 11:29:40 -0700254 // Maximum age of last location returned to clients with foreground-only location permissions.
255 private long mLastLocationMaxAgeMs;
256
Lifu Tang9363b942016-02-16 18:07:00 -0800257 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800258
Siddharth Raybb608c82017-03-16 11:33:34 -0700259 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700260
Yu-Han Yang3557cc72018-03-21 12:48:36 -0700261 private GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800262 private IBatchedLocationCallback mGnssBatchingCallback;
263 private LinkedCallback mGnssBatchingDeathCallback;
264 private boolean mGnssBatchingInProgress = false;
265
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700266 public LocationManagerService(Context context) {
267 super();
268 mContext = context;
gomo48f1a642017-11-10 20:35:46 -0800269 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800270
Svet Ganovadc1cf42015-06-15 16:36:24 -0700271 // Let the package manager query which are the default location
272 // providers as they get certain permissions granted by default.
273 PackageManagerInternal packageManagerInternal = LocalServices.getService(
274 PackageManagerInternal.class);
275 packageManagerInternal.setLocationPackagesProvider(
276 new PackageManagerInternal.PackagesProvider() {
277 @Override
278 public String[] getPackages(int userId) {
279 return mContext.getResources().getStringArray(
280 com.android.internal.R.array.config_locationProviderPackageNames);
281 }
282 });
283
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700284 if (D) Log.d(TAG, "Constructed");
285
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700286 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700287 }
288
Svetoslav Ganova0027152013-06-25 14:59:53 -0700289 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700290 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700291 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700292
Victoria Lease5cd731a2012-12-19 15:04:21 -0800293 // fetch package manager
294 mPackageManager = mContext.getPackageManager();
295
Victoria Lease0aa28602013-05-29 15:28:26 -0700296 // fetch power manager
297 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800298
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800299 // fetch activity manager
300 mActivityManager
301 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
302
Victoria Lease5cd731a2012-12-19 15:04:21 -0800303 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700304 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800305
306 // prepare mLocationHandler's dependents
307 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
308 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
309 mBlacklist.init();
310 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
311
Dianne Hackbornc2293022013-02-06 23:14:49 -0800312 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700313 AppOpsManager.OnOpChangedListener callback
314 = new AppOpsManager.OnOpChangedInternalListener() {
315 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800316 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700317 for (Receiver receiver : mReceivers.values()) {
318 receiver.updateMonitoring(true);
319 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800320 applyAllProviderRequirementsLocked();
321 }
322 }
323 };
Wei Wangdd070f22018-06-21 11:29:40 -0700324 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null,
325 AppOpsManager.WATCH_FOREGROUND_CHANGES, callback);
Dianne Hackbornc2293022013-02-06 23:14:49 -0800326
David Christieb870dbf2015-06-22 12:42:53 -0700327 PackageManager.OnPermissionsChangedListener permissionListener
328 = new PackageManager.OnPermissionsChangedListener() {
329 @Override
330 public void onPermissionsChanged(final int uid) {
331 synchronized (mLock) {
332 applyAllProviderRequirementsLocked();
333 }
334 }
335 };
336 mPackageManager.addOnPermissionsChangeListener(permissionListener);
337
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800338 // listen for background/foreground changes
339 ActivityManager.OnUidImportanceListener uidImportanceListener
340 = new ActivityManager.OnUidImportanceListener() {
341 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700342 public void onUidImportance(final int uid, final int importance) {
343 mLocationHandler.post(new Runnable() {
344 @Override
345 public void run() {
346 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800347 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700348 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800349 }
350 };
351 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700352 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800353
Amith Yamasanib27528d2014-06-05 15:02:10 -0700354 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
355 updateUserProfiles(mCurrentUserId);
356
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800357 updateBackgroundThrottlingWhitelistLocked();
Wei Wangdd070f22018-06-21 11:29:40 -0700358 updateLastLocationMaxAgeLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800359
Victoria Lease5cd731a2012-12-19 15:04:21 -0800360 // prepare providers
361 loadProvidersLocked();
362 updateProvidersLocked();
363 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700364
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700365 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700366 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700367 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700368 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800369 @Override
370 public void onChange(boolean selfChange) {
371 synchronized (mLock) {
372 updateProvidersLocked();
373 }
374 }
375 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800376 mContext.getContentResolver().registerContentObserver(
377 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
378 true,
379 new ContentObserver(mLocationHandler) {
380 @Override
381 public void onChange(boolean selfChange) {
382 synchronized (mLock) {
383 updateProvidersLocked();
384 }
385 }
386 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800387 mContext.getContentResolver().registerContentObserver(
Wei Wangdd070f22018-06-21 11:29:40 -0700388 Settings.Global.getUriFor(Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS),
389 true,
390 new ContentObserver(mLocationHandler) {
391 @Override
392 public void onChange(boolean selfChange) {
393 synchronized (mLock) {
394 updateLastLocationMaxAgeLocked();
395 }
396 }
397 }
398 );
399 mContext.getContentResolver().registerContentObserver(
gomo48f1a642017-11-10 20:35:46 -0800400 Settings.Global.getUriFor(
401 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
402 true,
403 new ContentObserver(mLocationHandler) {
404 @Override
405 public void onChange(boolean selfChange) {
406 synchronized (mLock) {
407 updateBackgroundThrottlingWhitelistLocked();
408 updateProvidersLocked();
409 }
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800410 }
gomo48f1a642017-11-10 20:35:46 -0800411 }, UserHandle.USER_ALL);
Wei Wangdd070f22018-06-21 11:29:40 -0700412
Victoria Lease5cd731a2012-12-19 15:04:21 -0800413 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700414
Victoria Lease38389b62012-09-30 11:44:22 -0700415 // listen for user change
416 IntentFilter intentFilter = new IntentFilter();
417 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700418 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
419 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700420 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700421
422 mContext.registerReceiverAsUser(new BroadcastReceiver() {
423 @Override
424 public void onReceive(Context context, Intent intent) {
425 String action = intent.getAction();
426 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
427 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700428 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
429 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
430 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700431 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700432 // shutdown only if UserId indicates whole system, not just one user
gomo48f1a642017-11-10 20:35:46 -0800433 if (D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700434 if (getSendingUserId() == UserHandle.USER_ALL) {
435 shutdownComponents();
436 }
Victoria Lease38389b62012-09-30 11:44:22 -0700437 }
438 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800439 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700440 }
441
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700442 private void onUidImportanceChanged(int uid, int importance) {
443 boolean foreground = isImportanceForeground(importance);
444 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
445 synchronized (mLock) {
446 for (Entry<String, ArrayList<UpdateRecord>> entry
gomo48f1a642017-11-10 20:35:46 -0800447 : mRecordsByProvider.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700448 String provider = entry.getKey();
449 for (UpdateRecord record : entry.getValue()) {
450 if (record.mReceiver.mIdentity.mUid == uid
gomo48f1a642017-11-10 20:35:46 -0800451 && record.mIsForegroundUid != foreground) {
452 if (D) {
453 Log.d(TAG, "request from uid " + uid + " is now "
454 + (foreground ? "foreground" : "background)"));
455 }
Wyatt Rileyf7075e02018-04-12 17:54:26 -0700456 record.updateForeground(foreground);
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700457
458 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
459 affectedProviders.add(provider);
460 }
461 }
462 }
463 }
464 for (String provider : affectedProviders) {
465 applyRequirementsLocked(provider);
466 }
467
Wyatt Riley11cc7492018-01-17 08:48:27 -0800468 for (Entry<IBinder, Identity> entry : mGnssMeasurementsListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700469 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800470 if (D) {
471 Log.d(TAG, "gnss measurements listener from uid " + uid
472 + " is now " + (foreground ? "foreground" : "background)"));
473 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700474 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800475 mGnssMeasurementsProvider.addListener(
476 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700477 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800478 mGnssMeasurementsProvider.removeListener(
479 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700480 }
481 }
482 }
483
Wyatt Riley11cc7492018-01-17 08:48:27 -0800484 for (Entry<IBinder, Identity> entry : mGnssNavigationMessageListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700485 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800486 if (D) {
487 Log.d(TAG, "gnss navigation message listener from uid "
488 + uid + " is now "
489 + (foreground ? "foreground" : "background)"));
490 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700491 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800492 mGnssNavigationMessageProvider.addListener(
493 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700494 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800495 mGnssNavigationMessageProvider.removeListener(
496 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700497 }
498 }
499 }
500 }
501 }
502
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800503 private static boolean isImportanceForeground(int importance) {
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700504 return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800505 }
506
Amith Yamasanib27528d2014-06-05 15:02:10 -0700507 /**
destradaab9026982015-08-27 17:34:54 -0700508 * Provides a way for components held by the {@link LocationManagerService} to clean-up
509 * gracefully on system's shutdown.
510 *
511 * NOTES:
512 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
513 * support for components that do not wish to handle such event.
514 */
515 private void shutdownComponents() {
gomo48f1a642017-11-10 20:35:46 -0800516 if (D) Log.d(TAG, "Shutting down components...");
destradaab9026982015-08-27 17:34:54 -0700517
518 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
519 if (gpsProvider != null && gpsProvider.isEnabled()) {
520 gpsProvider.disable();
521 }
destradaab9026982015-08-27 17:34:54 -0700522 }
523
524 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700525 * Makes a list of userids that are related to the current user. This is
526 * relevant when using managed profiles. Otherwise the list only contains
527 * the current user.
528 *
529 * @param currentUserId the current user, who might have an alter-ego.
530 */
531 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700532 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700533 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700534 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700535 }
536 }
537
538 /**
539 * Checks if the specified userId matches any of the current foreground
540 * users stored in mCurrentUserProfiles.
541 */
542 private boolean isCurrentProfile(int userId) {
543 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700544 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700545 }
546 }
547
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700548 private void ensureFallbackFusedProviderPresentLocked(String[] pkgs) {
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500549 PackageManager pm = mContext.getPackageManager();
550 String systemPackageName = mContext.getPackageName();
551 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
552
553 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
554 new Intent(FUSED_LOCATION_SERVICE_ACTION),
555 PackageManager.GET_META_DATA, mCurrentUserId);
556 for (ResolveInfo rInfo : rInfos) {
557 String packageName = rInfo.serviceInfo.packageName;
558
559 // Check that the signature is in the list of supported sigs. If it's not in
560 // this list the standard provider binding logic won't bind to it.
561 try {
562 PackageInfo pInfo;
563 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
564 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
565 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
566 ", but has wrong signature, ignoring");
567 continue;
568 }
569 } catch (NameNotFoundException e) {
570 Log.e(TAG, "missing package: " + packageName);
571 continue;
572 }
573
574 // Get the version info
575 if (rInfo.serviceInfo.metaData == null) {
576 Log.w(TAG, "Found fused provider without metadata: " + packageName);
577 continue;
578 }
579
580 int version = rInfo.serviceInfo.metaData.getInt(
581 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
582 if (version == 0) {
583 // This should be the fallback fused location provider.
584
585 // Make sure it's in the system partition.
586 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
587 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
588 continue;
589 }
590
591 // Check that the fallback is signed the same as the OS
592 // as a proxy for coreApp="true"
593 if (pm.checkSignatures(systemPackageName, packageName)
594 != PackageManager.SIGNATURE_MATCH) {
gomo48f1a642017-11-10 20:35:46 -0800595 if (D) {
596 Log.d(TAG, "Fallback candidate not signed the same as system: "
597 + packageName);
598 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500599 continue;
600 }
601
602 // Found a valid fallback.
603 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
604 return;
605 } else {
606 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
607 }
608 }
609
610 throw new IllegalStateException("Unable to find a fused location provider that is in the "
611 + "system partition with version 0 and signed with the platform certificate. "
612 + "Such a package is needed to provide a default fused location provider in the "
613 + "event that no other fused location provider has been installed or is currently "
614 + "available. For example, coreOnly boot mode when decrypting the data "
615 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
616 }
617
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700618 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700619 // create a passive location provider, which is always enabled
620 PassiveProvider passiveProvider = new PassiveProvider(this);
621 addProviderLocked(passiveProvider);
622 mEnabledProviders.add(passiveProvider.getName());
623 mPassiveProvider = passiveProvider;
624
Lifu Tang30f95a72016-01-07 23:20:38 -0800625 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700626 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800627 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700628 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800629 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Wyatt Rileycf879db2017-01-12 13:57:38 -0800630 mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
Siddharth Raybb608c82017-03-16 11:33:34 -0700631 mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800632 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
633 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
634 addProviderLocked(gnssProvider);
635 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800636 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
637 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800638 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700639 }
640
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700641 /*
642 Load package name(s) containing location provider support.
643 These packages can contain services implementing location providers:
644 Geocoder Provider, Network Location Provider, and
645 Fused Location Provider. They will each be searched for
646 service components implementing these providers.
647 The location framework also has support for installation
648 of new location providers at run-time. The new package does not
649 have to be explicitly listed here, however it must have a signature
650 that matches the signature of at least one package on this list.
651 */
652 Resources resources = mContext.getResources();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500653 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700654 com.android.internal.R.array.config_locationProviderPackageNames);
gomo48f1a642017-11-10 20:35:46 -0800655 if (D) {
656 Log.d(TAG, "certificates for location providers pulled from: " +
657 Arrays.toString(pkgs));
658 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500659
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700660 ensureFallbackFusedProviderPresentLocked(pkgs);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700661
662 // bind to network provider
663 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
664 mContext,
665 LocationManager.NETWORK_PROVIDER,
666 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700667 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
668 com.android.internal.R.string.config_networkLocationProviderPackageName,
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700669 com.android.internal.R.array.config_locationProviderPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700670 if (networkProvider != null) {
671 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
672 mProxyProviders.add(networkProvider);
673 addProviderLocked(networkProvider);
674 } else {
gomo48f1a642017-11-10 20:35:46 -0800675 Slog.w(TAG, "no network location provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700676 }
677
678 // bind to fused provider
679 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
680 mContext,
681 LocationManager.FUSED_PROVIDER,
682 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700683 com.android.internal.R.bool.config_enableFusedLocationOverlay,
684 com.android.internal.R.string.config_fusedLocationProviderPackageName,
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700685 com.android.internal.R.array.config_locationProviderPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700686 if (fusedLocationProvider != null) {
687 addProviderLocked(fusedLocationProvider);
688 mProxyProviders.add(fusedLocationProvider);
689 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700690 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700691 } else {
692 Slog.e(TAG, "no fused location provider found",
693 new IllegalStateException("Location service needs a fused location provider"));
694 }
695
696 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700697 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
698 com.android.internal.R.bool.config_enableGeocoderOverlay,
699 com.android.internal.R.string.config_geocoderProviderPackageName,
Soonil Nagarkare731ca82018-11-02 13:55:51 -0700700 com.android.internal.R.array.config_locationProviderPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700701 if (mGeocodeProvider == null) {
gomo48f1a642017-11-10 20:35:46 -0800702 Slog.e(TAG, "no geocoder provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700703 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700704
destradaaf9a274c2014-07-25 15:11:56 -0700705 // bind to geofence provider
706 GeofenceProxy provider = GeofenceProxy.createAndBind(
gomo48f1a642017-11-10 20:35:46 -0800707 mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
destradaaf9a274c2014-07-25 15:11:56 -0700708 com.android.internal.R.string.config_geofenceProviderPackageName,
709 com.android.internal.R.array.config_locationProviderPackageNames,
Wei Liu5241a4c2015-05-11 14:00:36 -0700710 mGpsGeofenceProxy,
Jiyong Park4cc3a1c2018-03-08 16:43:07 +0900711 null);
destradaaf9a274c2014-07-25 15:11:56 -0700712 if (provider == null) {
gomo48f1a642017-11-10 20:35:46 -0800713 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700714 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900715
destradaa6e2fe752015-06-23 17:25:53 -0700716 // bind to hardware activity recognition
717 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
718 ActivityRecognitionHardware activityRecognitionHardware = null;
719 if (activityRecognitionHardwareIsSupported) {
720 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700721 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700722 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700723 }
destradaa6e2fe752015-06-23 17:25:53 -0700724 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
725 mContext,
destradaa6e2fe752015-06-23 17:25:53 -0700726 activityRecognitionHardwareIsSupported,
727 activityRecognitionHardware,
728 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
729 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
730 com.android.internal.R.array.config_locationProviderPackageNames);
731 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700732 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700733 }
destradaaa4fa3b52014-07-09 10:46:39 -0700734
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900735 String[] testProviderStrings = resources.getStringArray(
736 com.android.internal.R.array.config_testLocationProviders);
737 for (String testProviderString : testProviderStrings) {
738 String fragments[] = testProviderString.split(",");
739 String name = fragments[0].trim();
740 if (mProvidersByName.get(name) != null) {
741 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
742 }
743 ProviderProperties properties = new ProviderProperties(
744 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
745 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
746 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
747 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
748 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
749 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
750 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
751 Integer.parseInt(fragments[8]) /* powerRequirement */,
752 Integer.parseInt(fragments[9]) /* accuracy */);
753 addTestProviderLocked(name, properties);
754 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700755 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700758 * Called when the device's active user changes.
gomo48f1a642017-11-10 20:35:46 -0800759 *
Victoria Lease38389b62012-09-30 11:44:22 -0700760 * @param userId the new active user's UserId
761 */
762 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800763 if (mCurrentUserId == userId) {
764 return;
765 }
Victoria Lease83762d22012-10-03 13:51:17 -0700766 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800767 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700768 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700769 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700770 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700771 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700772 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700773 }
Victoria Lease38389b62012-09-30 11:44:22 -0700774 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700775 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700776 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700777 }
778 }
779
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800780 private static final class Identity {
781 final int mUid;
782 final int mPid;
783 final String mPackageName;
784
785 Identity(int uid, int pid, String packageName) {
786 mUid = uid;
787 mPid = pid;
788 mPackageName = packageName;
789 }
790 }
791
Victoria Lease38389b62012-09-30 11:44:22 -0700792 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800793 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
794 * location updates.
795 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700796 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Yu-Han Yang24189822018-07-11 15:24:11 -0700797 private static final long WAKELOCK_TIMEOUT_MILLIS = 60 * 1000;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800798 final Identity mIdentity;
Victoria Lease37425c32012-10-16 16:08:48 -0700799 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700800
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800801 final ILocationListener mListener;
802 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700803 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700804 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800805 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700806
gomo48f1a642017-11-10 20:35:46 -0800807 final HashMap<String, UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700808
David Christie0b837452013-07-29 16:02:13 -0700809 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700810 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700811 // True if app ops has started monitoring this receiver for high power (gps) locations.
812 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700813 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700814 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800815
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700816 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700817 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800818 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800819 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700820 if (listener != null) {
821 mKey = listener.asBinder();
822 } else {
823 mKey = intent;
824 }
Victoria Lease37425c32012-10-16 16:08:48 -0700825 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800826 mIdentity = new Identity(uid, pid, packageName);
Narayan Kamath32684dd2018-01-08 17:32:51 +0000827 if (workSource != null && workSource.isEmpty()) {
David Christie82edc9b2013-07-19 11:31:42 -0700828 workSource = null;
829 }
830 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700831 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700832
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700833 updateMonitoring(true);
834
Victoria Lease0aa28602013-05-29 15:28:26 -0700835 // construct/configure wakelock
836 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700837 if (workSource == null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800838 workSource = new WorkSource(mIdentity.mUid, mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -0700839 }
840 mWakeLock.setWorkSource(workSource);
Yu-Han Yang24189822018-07-11 15:24:11 -0700841
842 // For a non-reference counted wakelock, each acquire will reset the timeout, and we
843 // only need to release it once.
844 mWakeLock.setReferenceCounted(false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
846
847 @Override
848 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800849 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
851
852 @Override
853 public int hashCode() {
854 return mKey.hashCode();
855 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800857 @Override
858 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700859 StringBuilder s = new StringBuilder();
860 s.append("Reciever[");
861 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700863 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700865 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700867 for (String p : mUpdateRecords.keySet()) {
868 s.append(" ").append(mUpdateRecords.get(p).toString());
869 }
Wei Wangdd070f22018-06-21 11:29:40 -0700870 s.append(" monitoring location: ").append(mOpMonitoring);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700871 s.append("]");
872 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
David Christie15b31912013-08-13 15:54:32 -0700875 /**
876 * Update AppOp monitoring for this receiver.
877 *
878 * @param allow If true receiver is currently active, if false it's been removed.
879 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700880 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700881 if (mHideFromAppOps) {
882 return;
883 }
884
David Christie15b31912013-08-13 15:54:32 -0700885 boolean requestingLocation = false;
886 boolean requestingHighPowerLocation = false;
887 if (allow) {
888 // See if receiver has any enabled update records. Also note if any update records
889 // are high power (has a high power provider with an interval under a threshold).
890 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
891 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
892 requestingLocation = true;
893 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800894 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700895 ProviderProperties properties = locationProvider != null
896 ? locationProvider.getProperties() : null;
897 if (properties != null
898 && properties.mPowerRequirement == Criteria.POWER_HIGH
899 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
900 requestingHighPowerLocation = true;
901 break;
902 }
903 }
904 }
905 }
906
David Christie0b837452013-07-29 16:02:13 -0700907 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700908 mOpMonitoring = updateMonitoring(
909 requestingLocation,
910 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700911 AppOpsManager.OP_MONITOR_LOCATION);
912
913 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700914 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700915 mOpHighPowerMonitoring = updateMonitoring(
916 requestingHighPowerLocation,
917 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700918 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700919 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700920 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700921 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
922 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
923 }
David Christie0b837452013-07-29 16:02:13 -0700924 }
925
926 /**
927 * Update AppOps monitoring for a single location request and op type.
928 *
gomo48f1a642017-11-10 20:35:46 -0800929 * @param allowMonitoring True if monitoring is allowed for this request/op.
David Christie0b837452013-07-29 16:02:13 -0700930 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
gomo48f1a642017-11-10 20:35:46 -0800931 * @param op AppOps code for the op to update.
David Christie0b837452013-07-29 16:02:13 -0700932 * @return True if monitoring is on for this request/op after updating.
933 */
934 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
935 int op) {
936 if (!currentlyMonitoring) {
937 if (allowMonitoring) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800938 return mAppOps.startOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700939 == AppOpsManager.MODE_ALLOWED;
940 }
941 } else {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800942 if (!allowMonitoring
Wei Wangdd070f22018-06-21 11:29:40 -0700943 || mAppOps.noteOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700944 != AppOpsManager.MODE_ALLOWED) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800945 mAppOps.finishOp(op, mIdentity.mUid, mIdentity.mPackageName);
David Christie0b837452013-07-29 16:02:13 -0700946 return false;
947 }
948 }
949
950 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700951 }
952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 public boolean isListener() {
954 return mListener != null;
955 }
956
957 public boolean isPendingIntent() {
958 return mPendingIntent != null;
959 }
960
961 public ILocationListener getListener() {
962 if (mListener != null) {
963 return mListener;
964 }
965 throw new IllegalStateException("Request for non-existent listener");
966 }
967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
969 if (mListener != null) {
970 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700971 synchronized (this) {
972 // synchronize to ensure incrementPendingBroadcastsLocked()
973 // is called before decrementPendingBroadcasts()
974 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700975 // call this after broadcasting so we do not increment
976 // if we throw an exeption.
977 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 } catch (RemoteException e) {
980 return false;
981 }
982 } else {
983 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800984 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
986 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700987 synchronized (this) {
988 // synchronize to ensure incrementPendingBroadcastsLocked()
989 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700990 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -0700991 getResolutionPermission(mAllowedResolutionLevel),
992 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -0700993 // call this after broadcasting so we do not increment
994 // if we throw an exeption.
995 incrementPendingBroadcastsLocked();
996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 } catch (PendingIntent.CanceledException e) {
998 return false;
999 }
1000 }
1001 return true;
1002 }
1003
1004 public boolean callLocationChangedLocked(Location location) {
1005 if (mListener != null) {
1006 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001007 synchronized (this) {
1008 // synchronize to ensure incrementPendingBroadcastsLocked()
1009 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001010 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -07001011 // call this after broadcasting so we do not increment
1012 // if we throw an exeption.
1013 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001014 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001015 } catch (RemoteException e) {
1016 return false;
1017 }
1018 } else {
1019 Intent locationChanged = new Intent();
gomo48f1a642017-11-10 20:35:46 -08001020 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED,
1021 new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001023 synchronized (this) {
1024 // synchronize to ensure incrementPendingBroadcastsLocked()
1025 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001026 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -07001027 getResolutionPermission(mAllowedResolutionLevel),
1028 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -07001029 // call this after broadcasting so we do not increment
1030 // if we throw an exeption.
1031 incrementPendingBroadcastsLocked();
1032 }
1033 } catch (PendingIntent.CanceledException e) {
1034 return false;
1035 }
1036 }
1037 return true;
1038 }
1039
1040 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001041 // First update AppOp monitoring.
1042 // An app may get/lose location access as providers are enabled/disabled.
1043 updateMonitoring(true);
1044
Mike Lockwood48f17512009-04-23 09:12:08 -07001045 if (mListener != null) {
1046 try {
1047 synchronized (this) {
1048 // synchronize to ensure incrementPendingBroadcastsLocked()
1049 // is called before decrementPendingBroadcasts()
1050 if (enabled) {
1051 mListener.onProviderEnabled(provider);
1052 } else {
1053 mListener.onProviderDisabled(provider);
1054 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001055 // call this after broadcasting so we do not increment
1056 // if we throw an exeption.
1057 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001058 }
1059 } catch (RemoteException e) {
1060 return false;
1061 }
1062 } else {
1063 Intent providerIntent = new Intent();
1064 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1065 try {
1066 synchronized (this) {
1067 // synchronize to ensure incrementPendingBroadcastsLocked()
1068 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001069 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Lifu Tang519f0d02018-04-12 16:39:39 -07001070 getResolutionPermission(mAllowedResolutionLevel),
1071 PendingIntentUtils.createDontSendToRestrictedAppsBundle(null));
Mike Lockwood48f17512009-04-23 09:12:08 -07001072 // call this after broadcasting so we do not increment
1073 // if we throw an exeption.
1074 incrementPendingBroadcastsLocked();
1075 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 } catch (PendingIntent.CanceledException e) {
1077 return false;
1078 }
1079 }
1080 return true;
1081 }
1082
Nick Pellyf1be6862012-05-15 10:53:42 -07001083 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001084 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001085 if (D) Log.d(TAG, "Location listener died");
1086
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001087 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001088 removeUpdatesLocked(this);
1089 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001090 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001091 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001092 }
1093 }
1094
Nick Pellye0fd6932012-07-11 10:26:13 -07001095 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001096 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1097 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001098 synchronized (this) {
1099 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001100 }
1101 }
1102
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001103 // this must be called while synchronized by caller in a synchronized block
1104 // containing the sending of the broadcaset
1105 private void incrementPendingBroadcastsLocked() {
Yu-Han Yang24189822018-07-11 15:24:11 -07001106 mPendingBroadcasts++;
1107 mWakeLock.acquire(WAKELOCK_TIMEOUT_MILLIS);
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001108 }
1109
1110 private void decrementPendingBroadcastsLocked() {
1111 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001112 if (mWakeLock.isHeld()) {
1113 mWakeLock.release();
1114 }
1115 }
1116 }
1117
1118 public void clearPendingBroadcastsLocked() {
1119 if (mPendingBroadcasts > 0) {
1120 mPendingBroadcasts = 0;
1121 if (mWakeLock.isHeld()) {
1122 mWakeLock.release();
1123 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001124 }
1125 }
1126 }
1127
Nick Pellye0fd6932012-07-11 10:26:13 -07001128 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001129 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001130 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001131 //the receiver list if it is not found. If it is not found then the
1132 //LocationListener was removed when it had a pending broadcast and should
1133 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001134 synchronized (mLock) {
1135 IBinder binder = listener.asBinder();
1136 Receiver receiver = mReceivers.get(binder);
1137 if (receiver != null) {
1138 synchronized (receiver) {
1139 // so wakelock calls will succeed
1140 long identity = Binder.clearCallingIdentity();
1141 receiver.decrementPendingBroadcastsLocked();
1142 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001143 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 }
1146 }
1147
Lifu Tang82f893d2016-01-21 18:15:33 -08001148 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001149 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001150 */
1151 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001152 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001153 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001154 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001155 } else {
1156 return 0;
1157 }
1158 }
1159
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001160
1161 /**
1162 * Returns the model name of the GNSS hardware.
1163 */
1164 @Override
Wyatt Riley49097c02018-03-15 09:14:43 -07001165 @Nullable
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001166 public String getGnssHardwareModelName() {
1167 if (mGnssSystemInfoProvider != null) {
1168 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1169 } else {
Wyatt Riley49097c02018-03-15 09:14:43 -07001170 return null;
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001171 }
1172 }
1173
Wyatt Rileycf879db2017-01-12 13:57:38 -08001174 /**
1175 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1176 * (try to) access GNSS information at this layer.
1177 */
1178 private boolean hasGnssPermissions(String packageName) {
1179 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1180 checkResolutionLevelIsSufficientForProviderUse(
1181 allowedResolutionLevel,
1182 LocationManager.GPS_PROVIDER);
1183
1184 int pid = Binder.getCallingPid();
1185 int uid = Binder.getCallingUid();
1186 long identity = Binder.clearCallingIdentity();
1187 boolean hasLocationAccess;
1188 try {
1189 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1190 } finally {
1191 Binder.restoreCallingIdentity(identity);
1192 }
1193
1194 return hasLocationAccess;
1195 }
1196
1197 /**
1198 * Returns the GNSS batching size, if available.
1199 */
1200 @Override
1201 public int getGnssBatchSize(String packageName) {
1202 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1203 "Location Hardware permission not granted to access hardware batching");
1204
1205 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
Yu-Han Yang3557cc72018-03-21 12:48:36 -07001206 return mGnssBatchingProvider.getBatchSize();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001207 } else {
1208 return 0;
1209 }
1210 }
1211
1212 /**
1213 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1214 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1215 */
1216 @Override
1217 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1218 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1219 "Location Hardware permission not granted to access hardware batching");
1220
1221 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1222 return false;
1223 }
1224
1225 mGnssBatchingCallback = callback;
1226 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1227 try {
1228 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1229 } catch (RemoteException e) {
1230 // if the remote process registering the listener is already dead, just swallow the
1231 // exception and return
1232 Log.e(TAG, "Remote listener already died.", e);
1233 return false;
1234 }
1235
1236 return true;
1237 }
1238
1239 private class LinkedCallback implements IBinder.DeathRecipient {
1240 private final IBatchedLocationCallback mCallback;
1241
1242 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1243 mCallback = callback;
1244 }
1245
1246 @NonNull
1247 public IBatchedLocationCallback getUnderlyingListener() {
1248 return mCallback;
1249 }
1250
1251 @Override
1252 public void binderDied() {
1253 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1254 stopGnssBatch();
1255 removeGnssBatchingCallback();
1256 }
1257 }
1258
1259 /**
1260 * Removes callback for GNSS batching
1261 */
1262 @Override
1263 public void removeGnssBatchingCallback() {
1264 try {
1265 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1266 0 /* flags */);
1267 } catch (NoSuchElementException e) {
1268 // if the death callback isn't connected (it should be...), log error, swallow the
1269 // exception and return
1270 Log.e(TAG, "Couldn't unlink death callback.", e);
1271 }
1272 mGnssBatchingCallback = null;
1273 mGnssBatchingDeathCallback = null;
1274 }
1275
1276
1277 /**
1278 * Starts GNSS batching, if available.
1279 */
1280 @Override
1281 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1282 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1283 "Location Hardware permission not granted to access hardware batching");
1284
1285 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1286 return false;
1287 }
1288
1289 if (mGnssBatchingInProgress) {
1290 // Current design does not expect multiple starts to be called repeatedly
1291 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1292 // Try to clean up anyway, and continue
1293 stopGnssBatch();
1294 }
1295
1296 mGnssBatchingInProgress = true;
1297 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1298 }
1299
1300 /**
1301 * Flushes a GNSS batch in progress
1302 */
1303 @Override
1304 public void flushGnssBatch(String packageName) {
1305 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1306 "Location Hardware permission not granted to access hardware batching");
1307
1308 if (!hasGnssPermissions(packageName)) {
1309 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1310 return;
1311 }
1312
1313 if (!mGnssBatchingInProgress) {
1314 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1315 }
1316
1317 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001318 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001319 }
1320 }
1321
1322 /**
1323 * Stops GNSS batching
1324 */
1325 @Override
1326 public boolean stopGnssBatch() {
1327 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1328 "Location Hardware permission not granted to access hardware batching");
1329
1330 if (mGnssBatchingProvider != null) {
1331 mGnssBatchingInProgress = false;
1332 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001333 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001334 return false;
1335 }
1336 }
1337
1338 @Override
1339 public void reportLocationBatch(List<Location> locations) {
1340 checkCallerIsProvider();
1341
1342 // Currently used only for GNSS locations - update permissions check if changed
1343 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1344 if (mGnssBatchingCallback == null) {
1345 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1346 return;
1347 }
1348 try {
1349 mGnssBatchingCallback.onLocationBatch(locations);
1350 } catch (RemoteException e) {
1351 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1352 }
1353 } else {
1354 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1355 }
1356 }
1357
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001358 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001359 mProviders.add(provider);
1360 mProvidersByName.put(provider.getName(), provider);
1361 }
1362
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001363 private void removeProviderLocked(LocationProviderInterface provider) {
1364 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001365 mProviders.remove(provider);
1366 mProvidersByName.remove(provider.getName());
1367 }
1368
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001369 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001370 * Returns "true" if access to the specified location provider is allowed by the current
1371 * user's settings. Access to all location providers is forbidden to non-location-provider
1372 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001373 *
1374 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001375 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001376 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
Maggie2a9409e2018-03-21 11:47:28 -07001377 return isAllowedByUserSettingsLockedForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001380 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001381 * Returns "true" if access to the specified location provider is allowed by the specified
1382 * user's settings. Access to all location providers is forbidden to non-location-provider
1383 * processes belonging to background users.
1384 *
1385 * @param provider the name of the location provider
Maggie2a9409e2018-03-21 11:47:28 -07001386 * @param userId the user id to query
Victoria Lease09eeaec2013-02-05 11:34:13 -08001387 */
Maggie2a9409e2018-03-21 11:47:28 -07001388 private boolean isAllowedByUserSettingsLockedForUser(String provider, int userId) {
1389 if (mEnabledProviders.contains(provider)) {
1390 return true;
1391 }
1392 if (mDisabledProviders.contains(provider)) {
1393 return false;
1394 }
1395 return isLocationProviderEnabledForUser(provider, userId);
1396 }
1397
1398
1399 /**
1400 * Returns "true" if access to the specified location provider is allowed by the specified
1401 * user's settings. Access to all location providers is forbidden to non-location-provider
1402 * processes belonging to background users.
1403 *
1404 * @param provider the name of the location provider
1405 * @param uid the requestor's UID
1406 * @param userId the user id to query
1407 */
1408 private boolean isAllowedByUserSettingsLocked(String provider, int uid, int userId) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001409 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001410 return false;
1411 }
Maggie2a9409e2018-03-21 11:47:28 -07001412 return isAllowedByUserSettingsLockedForUser(provider, userId);
Victoria Lease09eeaec2013-02-05 11:34:13 -08001413 }
1414
1415 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001416 * Returns the permission string associated with the specified resolution level.
1417 *
1418 * @param resolutionLevel the resolution level
1419 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001420 */
Victoria Lease37425c32012-10-16 16:08:48 -07001421 private String getResolutionPermission(int resolutionLevel) {
1422 switch (resolutionLevel) {
1423 case RESOLUTION_LEVEL_FINE:
1424 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1425 case RESOLUTION_LEVEL_COARSE:
1426 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1427 default:
1428 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001430 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001431
Victoria Leaseda479c52012-10-15 15:24:16 -07001432 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001433 * Returns the resolution level allowed to the given PID/UID pair.
1434 *
1435 * @param pid the PID
1436 * @param uid the UID
1437 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001438 */
Victoria Lease37425c32012-10-16 16:08:48 -07001439 private int getAllowedResolutionLevel(int pid, int uid) {
1440 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001441 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001442 return RESOLUTION_LEVEL_FINE;
1443 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001444 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001445 return RESOLUTION_LEVEL_COARSE;
1446 } else {
1447 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001448 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001449 }
1450
1451 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001452 * Returns the resolution level allowed to the caller
1453 *
1454 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001455 */
Victoria Lease37425c32012-10-16 16:08:48 -07001456 private int getCallerAllowedResolutionLevel() {
1457 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1458 }
1459
1460 /**
1461 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1462 *
1463 * @param allowedResolutionLevel resolution level allowed to caller
1464 */
1465 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1466 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001467 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
1470
Victoria Lease37425c32012-10-16 16:08:48 -07001471 /**
1472 * Return the minimum resolution level required to use the specified location provider.
1473 *
1474 * @param provider the name of the location provider
1475 * @return minimum resolution level required for provider
1476 */
1477 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001478 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1479 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1480 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001481 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001482 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1483 LocationManager.FUSED_PROVIDER.equals(provider)) {
1484 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001485 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001486 } else {
1487 // mock providers
1488 LocationProviderInterface lp = mMockProviders.get(provider);
1489 if (lp != null) {
1490 ProviderProperties properties = lp.getProperties();
1491 if (properties != null) {
1492 if (properties.mRequiresSatellite) {
1493 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001494 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001495 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1496 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001497 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001498 }
1499 }
1500 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001501 }
Victoria Lease37425c32012-10-16 16:08:48 -07001502 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001503 }
1504
Victoria Lease37425c32012-10-16 16:08:48 -07001505 /**
1506 * Throw SecurityException if specified resolution level is insufficient to use the named
1507 * location provider.
1508 *
1509 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001510 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001511 */
1512 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1513 String providerName) {
1514 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1515 if (allowedResolutionLevel < requiredResolutionLevel) {
1516 switch (requiredResolutionLevel) {
1517 case RESOLUTION_LEVEL_FINE:
1518 throw new SecurityException("\"" + providerName + "\" location provider " +
1519 "requires ACCESS_FINE_LOCATION permission.");
1520 case RESOLUTION_LEVEL_COARSE:
1521 throw new SecurityException("\"" + providerName + "\" location provider " +
1522 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1523 default:
1524 throw new SecurityException("Insufficient permission for \"" + providerName +
1525 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001526 }
1527 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001528 }
1529
David Christie82edc9b2013-07-19 11:31:42 -07001530 /**
1531 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1532 * for battery).
1533 */
David Christie40e57822013-07-30 11:36:48 -07001534 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001535 mContext.enforceCallingOrSelfPermission(
1536 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1537 }
1538
David Christie40e57822013-07-30 11:36:48 -07001539 private void checkUpdateAppOpsAllowed() {
1540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1542 }
1543
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001544 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001545 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1546 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001547 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001548 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001549 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001550 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001551 }
1552 return -1;
1553 }
1554
Wei Wangb86334f2018-07-03 16:33:24 -07001555 private static String resolutionLevelToOpStr(int allowedResolutionLevel) {
1556 switch(allowedResolutionLevel) {
1557 case RESOLUTION_LEVEL_COARSE:
1558 return AppOpsManager.OPSTR_COARSE_LOCATION;
1559 case RESOLUTION_LEVEL_FINE:
1560 return AppOpsManager.OPSTR_FINE_LOCATION;
1561 case RESOLUTION_LEVEL_NONE:
1562 // The client is not allowed to get any location, so both FINE and COARSE ops will
1563 // be denied. Pick the most restrictive one to be safe.
1564 return AppOpsManager.OPSTR_FINE_LOCATION;
1565 default:
1566 // Use the most restrictive ops if not sure.
1567 return AppOpsManager.OPSTR_FINE_LOCATION;
1568 }
1569 }
1570
David Christieb870dbf2015-06-22 12:42:53 -07001571 boolean reportLocationAccessNoThrow(
1572 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001573 int op = resolutionLevelToOp(allowedResolutionLevel);
1574 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001575 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1576 return false;
1577 }
1578 }
David Christieb870dbf2015-06-22 12:42:53 -07001579
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001580 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001581 }
1582
David Christieb870dbf2015-06-22 12:42:53 -07001583 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001584 int op = resolutionLevelToOp(allowedResolutionLevel);
1585 if (op >= 0) {
Wei Wangdd070f22018-06-21 11:29:40 -07001586 if (mAppOps.noteOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001587 return false;
1588 }
1589 }
David Christieb870dbf2015-06-22 12:42:53 -07001590
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001591 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001592 }
1593
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001594 /**
Maggie91e630c2018-01-24 17:31:46 -08001595 * Returns all providers by name, including passive and the ones that are not permitted to
1596 * be accessed by the calling activity or are currently disabled, but excluding fused.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001597 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001598 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 public List<String> getAllProviders() {
Maggie91e630c2018-01-24 17:31:46 -08001600 ArrayList<String> out;
1601 synchronized (mLock) {
1602 out = new ArrayList<>(mProviders.size());
1603 for (LocationProviderInterface provider : mProviders) {
1604 String name = provider.getName();
1605 if (LocationManager.FUSED_PROVIDER.equals(name)) {
1606 continue;
1607 }
1608 out.add(name);
1609 }
1610 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001611 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 return out;
1613 }
1614
Mike Lockwood03ca2162010-04-01 08:10:09 -07001615 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001616 * Return all providers by name, that match criteria and are optionally
1617 * enabled.
1618 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001619 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001620 @Override
1621 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001622 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001623 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001624 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001625 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001626 try {
1627 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001628 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001629 for (LocationProviderInterface provider : mProviders) {
1630 String name = provider.getName();
1631 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001632 continue;
1633 }
Victoria Lease37425c32012-10-16 16:08:48 -07001634 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Maggie2a9409e2018-03-21 11:47:28 -07001635 if (enabledOnly
1636 && !isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001637 continue;
1638 }
1639 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1640 name, provider.getProperties(), criteria)) {
1641 continue;
1642 }
1643 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001644 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001645 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001646 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001647 } finally {
1648 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001649 }
1650
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001651 if (D) Log.d(TAG, "getProviders()=" + out);
1652 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001653 }
1654
1655 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001656 * Return the name of the best provider given a Criteria object.
1657 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001658 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001659 * has been deprecated as well. So this method now uses
1660 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001661 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001662 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001663 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001664 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001665
1666 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001667 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001668 result = pickBest(providers);
1669 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1670 return result;
1671 }
1672 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001673 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001674 result = pickBest(providers);
1675 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1676 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001677 }
1678
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001679 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001680 return null;
1681 }
1682
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001683 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001684 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001685 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001686 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1687 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001688 } else {
1689 return providers.get(0);
1690 }
1691 }
1692
Nick Pellye0fd6932012-07-11 10:26:13 -07001693 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001694 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1695 LocationProviderInterface p = mProvidersByName.get(provider);
1696 if (p == null) {
1697 throw new IllegalArgumentException("provider=" + provider);
1698 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001699
1700 boolean result = LocationProvider.propertiesMeetCriteria(
1701 p.getName(), p.getProperties(), criteria);
1702 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1703 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001704 }
1705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001707 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001708 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001709 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 boolean isEnabled = p.isEnabled();
1711 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001712 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001714 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001715 // If any provider has been disabled, clear all last locations for all providers.
1716 // This is to be on the safe side in case a provider has location derived from
1717 // this disabled provider.
1718 mLastLocation.clear();
1719 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001720 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001722 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001723 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001725 }
1726 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001727 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1728 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001729 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1730 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
1732 }
1733
Amith Yamasanib27528d2014-06-05 15:02:10 -07001734 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001735 int listeners = 0;
1736
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001737 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001738 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739
1740 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1743 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001744 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001745 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001746 // Sends a notification message to the receiver
1747 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1748 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001749 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001750 }
1751 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001753 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756 }
1757
1758 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001759 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 removeUpdatesLocked(deadReceivers.get(i));
1761 }
1762 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 if (enabled) {
1765 p.enable();
Yu-Han Yanga4d250e2018-10-02 21:29:20 -07001766 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001768 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001770 }
1771
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001772 private void applyRequirementsLocked(String provider) {
1773 LocationProviderInterface p = mProvidersByName.get(provider);
1774 if (p == null) return;
1775
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001777 WorkSource worksource = new WorkSource();
1778 ProviderRequest providerRequest = new ProviderRequest();
1779
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001780 ContentResolver resolver = mContext.getContentResolver();
1781 long backgroundThrottleInterval = Settings.Global.getLong(
1782 resolver,
1783 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1784 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001785 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001786
gomo48f1a642017-11-10 20:35:46 -08001787 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001789 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001790 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001791 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001792 record.mReceiver.mIdentity.mPid,
1793 record.mReceiver.mIdentity.mUid,
1794 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001795 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001796 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001797 long interval = locationRequest.getInterval();
1798
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001799 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001800 if (!record.mIsForegroundUid) {
1801 interval = Math.max(interval, backgroundThrottleInterval);
1802 }
1803 if (interval != locationRequest.getInterval()) {
1804 locationRequest = new LocationRequest(locationRequest);
1805 locationRequest.setInterval(interval);
1806 }
1807 }
1808
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001809 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001810 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001811 if (!locationRequest.isLowPowerMode()) {
1812 providerRequest.lowPowerMode = false;
1813 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001814 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001815 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001816 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001817 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001818 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001819 }
1820 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001821
1822 if (providerRequest.reportLocation) {
1823 // calculate who to blame for power
1824 // This is somewhat arbitrary. We pick a threshold interval
1825 // that is slightly higher that the minimum interval, and
1826 // spread the blame across all applications with a request
1827 // under that threshold.
1828 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1829 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001830 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001831 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001832
1833 // Don't assign battery blame for update records whose
1834 // client has no permission to receive location data.
1835 if (!providerRequest.locationRequests.contains(locationRequest)) {
1836 continue;
1837 }
1838
Victoria Leaseb711d572012-10-02 13:14:11 -07001839 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001840 if (record.mReceiver.mWorkSource != null
Narayan Kamath32684dd2018-01-08 17:32:51 +00001841 && isValidWorkSource(record.mReceiver.mWorkSource)) {
David Christie82edc9b2013-07-19 11:31:42 -07001842 worksource.add(record.mReceiver.mWorkSource);
1843 } else {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001844 // Assign blame to caller if there's no WorkSource associated with
1845 // the request or if it's invalid.
David Christie82edc9b2013-07-19 11:31:42 -07001846 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001847 record.mReceiver.mIdentity.mUid,
1848 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001849 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001850 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001851 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001855
1856 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1857 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001858 }
1859
Narayan Kamath32684dd2018-01-08 17:32:51 +00001860 /**
1861 * Whether a given {@code WorkSource} associated with a Location request is valid.
1862 */
1863 private static boolean isValidWorkSource(WorkSource workSource) {
1864 if (workSource.size() > 0) {
1865 // If the WorkSource has one or more non-chained UIDs, make sure they're accompanied
1866 // by tags.
1867 return workSource.getName(0) != null;
1868 } else {
1869 // For now, make sure callers have supplied an attribution tag for use with
1870 // AppOpsManager. This might be relaxed in the future.
1871 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
1872 return workChains != null && !workChains.isEmpty() &&
1873 workChains.get(0).getAttributionTag() != null;
1874 }
1875 }
1876
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001877 @Override
1878 public String[] getBackgroundThrottlingWhitelist() {
1879 synchronized (mLock) {
1880 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001881 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001882 }
1883 }
1884
1885 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001886 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001887 mContext.getContentResolver(),
1888 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001889 if (setting == null) {
1890 setting = "";
1891 }
1892
1893 mBackgroundThrottlePackageWhitelist.clear();
1894 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001895 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001896 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001897 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001898 }
1899
Wei Wangdd070f22018-06-21 11:29:40 -07001900 private void updateLastLocationMaxAgeLocked() {
1901 mLastLocationMaxAgeMs =
1902 Settings.Global.getLong(
1903 mContext.getContentResolver(),
1904 Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS,
1905 DEFAULT_LAST_LOCATION_MAX_AGE_MS);
1906 }
1907
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001908 private boolean isThrottlingExemptLocked(Identity identity) {
1909 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001910 return true;
1911 }
1912
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001913 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001914 return true;
1915 }
1916
1917 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001918 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001919 return true;
1920 }
1921 }
1922
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001923 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001924 }
1925
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001926 private class UpdateRecord {
1927 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001928 final LocationRequest mRealRequest; // original request from client
1929 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001931 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001932 Location mLastFixBroadcast;
1933 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934
1935 /**
1936 * Note: must be constructed with lock held.
1937 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001938 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001939 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001940 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001941 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001942 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001943 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001944 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945
1946 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1947 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001948 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 mRecordsByProvider.put(provider, records);
1950 }
1951 if (!records.contains(this)) {
1952 records.add(this);
1953 }
David Christie2ff96af2014-01-30 16:09:37 -08001954
1955 // Update statistics for historical location requests by package/provider
1956 mRequestStatistics.startRequesting(
Wyatt Rileyf7075e02018-04-12 17:54:26 -07001957 mReceiver.mIdentity.mPackageName, provider, request.getInterval(),
1958 mIsForegroundUid);
1959 }
1960
1961 /**
1962 * Method to be called when record changes foreground/background
1963 */
1964 void updateForeground(boolean isForeground){
1965 mIsForegroundUid = isForeground;
1966 mRequestStatistics.updateForeground(
1967 mReceiver.mIdentity.mPackageName, mProvider, isForeground);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001968 }
1969
1970 /**
David Christie2ff96af2014-01-30 16:09:37 -08001971 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001972 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001973 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001974 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001975
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001976 // remove from mRecordsByProvider
1977 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1978 if (globalRecords != null) {
1979 globalRecords.remove(this);
1980 }
1981
1982 if (!removeReceiver) return; // the caller will handle the rest
1983
1984 // remove from Receiver#mUpdateRecords
1985 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1986 if (receiverRecords != null) {
1987 receiverRecords.remove(this.mProvider);
1988
1989 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001990 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001991 removeUpdatesLocked(mReceiver);
1992 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001993 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 }
1995
1996 @Override
1997 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001998 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001999 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
2000 : " background")
Wyatt Riley19adc022018-05-22 13:30:51 -07002001 + ")" + " " + mRealRequest + " "
2002 + mReceiver.mWorkSource + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
2005
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002006 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07002007 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002008 IBinder binder = listener.asBinder();
2009 Receiver receiver = mReceivers.get(binder);
2010 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07002011 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
2012 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002013 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002014 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002015 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002016 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002017 return null;
2018 }
Wen Jingcb3ab222014-03-27 13:42:59 +08002019 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002020 }
2021 return receiver;
2022 }
2023
David Christie82edc9b2013-07-19 11:31:42 -07002024 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07002025 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002026 Receiver receiver = mReceivers.get(intent);
2027 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07002028 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
2029 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002030 mReceivers.put(intent, receiver);
2031 }
2032 return receiver;
2033 }
2034
Victoria Lease37425c32012-10-16 16:08:48 -07002035 /**
2036 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
2037 * and consistency requirements.
2038 *
2039 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07002040 * @return a version of request that meets the given resolution and consistency requirements
2041 * @hide
2042 */
gomo48f1a642017-11-10 20:35:46 -08002043 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
2044 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07002045 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08002046 if (!callerHasLocationHardwarePermission) {
2047 // allow setting low power mode only for callers with location hardware permission
2048 sanitizedRequest.setLowPowerMode(false);
2049 }
Victoria Lease37425c32012-10-16 16:08:48 -07002050 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
2051 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002052 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07002053 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07002054 break;
2055 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07002056 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07002057 break;
2058 }
2059 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07002060 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2061 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002062 }
Victoria Lease37425c32012-10-16 16:08:48 -07002063 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2064 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002065 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002066 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002067 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002068 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002069 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002070 }
Victoria Lease37425c32012-10-16 16:08:48 -07002071 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002072 }
2073
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002074 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002075 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002076 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002077 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002078 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002079 String[] packages = mPackageManager.getPackagesForUid(uid);
2080 if (packages == null) {
2081 throw new SecurityException("invalid UID " + uid);
2082 }
2083 for (String pkg : packages) {
2084 if (packageName.equals(pkg)) return;
2085 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002086 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002087 }
2088
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002089 private void checkPendingIntent(PendingIntent intent) {
2090 if (intent == null) {
2091 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002092 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002093 }
2094
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002095 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002096 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002097 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002098 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002099 } else if (intent != null && listener != null) {
2100 throw new IllegalArgumentException("cannot register both listener and intent");
2101 } else if (intent != null) {
2102 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002103 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002104 } else {
David Christie40e57822013-07-30 11:36:48 -07002105 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002106 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002107 }
2108
Nick Pellye0fd6932012-07-11 10:26:13 -07002109 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002110 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2111 PendingIntent intent, String packageName) {
2112 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2113 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002114 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2115 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2116 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002117 WorkSource workSource = request.getWorkSource();
Narayan Kamath32684dd2018-01-08 17:32:51 +00002118 if (workSource != null && !workSource.isEmpty()) {
David Christie40e57822013-07-30 11:36:48 -07002119 checkDeviceStatsAllowed();
2120 }
2121 boolean hideFromAppOps = request.getHideFromAppOps();
2122 if (hideFromAppOps) {
2123 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002124 }
gomo48f1a642017-11-10 20:35:46 -08002125 boolean callerHasLocationHardwarePermission =
2126 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002127 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002128 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2129 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002131 final int pid = Binder.getCallingPid();
2132 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002133 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002134 long identity = Binder.clearCallingIdentity();
2135 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002136 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2137 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002138 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002139
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002140 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002141 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002142 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002143 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 } finally {
2146 Binder.restoreCallingIdentity(identity);
2147 }
2148 }
2149
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002150 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2151 int pid, int uid, String packageName) {
2152 // Figure out the provider. Either its explicitly request (legacy use cases), or
2153 // use the fused provider
2154 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2155 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002156 if (name == null) {
2157 throw new IllegalArgumentException("provider name must not be null");
2158 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002159
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002160 LocationProviderInterface provider = mProvidersByName.get(name);
2161 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002162 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002163 }
2164
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002165 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002166 if (D) {
2167 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2168 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2169 + (record.mIsForegroundUid ? "foreground" : "background")
2170 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002171 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002172 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002173
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002174 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2175 if (oldRecord != null) {
2176 oldRecord.disposeLocked(false);
2177 }
2178
Maggie2a9409e2018-03-21 11:47:28 -07002179 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid, mCurrentUserId);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002180 if (isProviderEnabled) {
2181 applyRequirementsLocked(name);
2182 } else {
2183 // Notify the listener that updates are currently disabled
2184 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
David Christie0b837452013-07-29 16:02:13 -07002186 // Update the monitoring here just in case multiple location requests were added to the
2187 // same receiver (this request may be high power and the initial might not have been).
2188 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002189 }
2190
Nick Pellye0fd6932012-07-11 10:26:13 -07002191 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002192 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2193 String packageName) {
2194 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002195
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002196 final int pid = Binder.getCallingPid();
2197 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002198
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002199 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002200 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002201 boolean hideFromAppOps = false;
2202 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2203 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002204
2205 // providers may use public location API's, need to clear identity
2206 long identity = Binder.clearCallingIdentity();
2207 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002208 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002209 } finally {
2210 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213 }
2214
2215 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002216 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002217
2218 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2219 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2220 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002221 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002223 }
2224
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002225 receiver.updateMonitoring(false);
2226
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002227 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002228 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002229 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2230 if (oldRecords != null) {
2231 // Call dispose() on the obsolete update records.
2232 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002233 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002234 record.disposeLocked(false);
2235 }
2236 // Accumulate providers
2237 providers.addAll(oldRecords.keySet());
2238 }
2239
2240 // update provider
2241 for (String provider : providers) {
2242 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002243 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002244 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
2246
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002247 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 }
2249 }
2250
Dianne Hackbornc2293022013-02-06 23:14:49 -08002251 private void applyAllProviderRequirementsLocked() {
2252 for (LocationProviderInterface p : mProviders) {
2253 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002254 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002255 continue;
2256 }
2257
2258 applyRequirementsLocked(p.getName());
2259 }
2260 }
2261
Nick Pellye0fd6932012-07-11 10:26:13 -07002262 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002263 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002264 if (D) Log.d(TAG, "getLastLocation: " + request);
2265 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002266 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002267 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002268 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2269 request.getProvider());
2270 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002271
David Christieb870dbf2015-06-22 12:42:53 -07002272 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002273 final int uid = Binder.getCallingUid();
2274 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002275 try {
2276 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002277 if (D) {
2278 Log.d(TAG, "not returning last loc for blacklisted app: " +
2279 packageName);
2280 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002281 return null;
2282 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002283
David Christieb870dbf2015-06-22 12:42:53 -07002284 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002285 if (D) {
2286 Log.d(TAG, "not returning last loc for no op app: " +
2287 packageName);
2288 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002289 return null;
2290 }
2291
Victoria Leaseb711d572012-10-02 13:14:11 -07002292 synchronized (mLock) {
2293 // Figure out the provider. Either its explicitly request (deprecated API's),
2294 // or use the fused provider
2295 String name = request.getProvider();
2296 if (name == null) name = LocationManager.FUSED_PROVIDER;
2297 LocationProviderInterface provider = mProvidersByName.get(name);
2298 if (provider == null) return null;
2299
Maggie2a9409e2018-03-21 11:47:28 -07002300 if (!isAllowedByUserSettingsLocked(name, uid, mCurrentUserId)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002301
David Christie1b9b7b12013-04-15 15:31:11 -07002302 Location location;
2303 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2304 // Make sure that an app with coarse permissions can't get frequent location
2305 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2306 location = mLastLocationCoarseInterval.get(name);
2307 } else {
2308 location = mLastLocation.get(name);
2309 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002310 if (location == null) {
2311 return null;
2312 }
Wei Wangdd070f22018-06-21 11:29:40 -07002313
2314 // Don't return stale location to apps with foreground-only location permission.
Wei Wangb86334f2018-07-03 16:33:24 -07002315 String op = resolutionLevelToOpStr(allowedResolutionLevel);
Wei Wangdd070f22018-06-21 11:29:40 -07002316 long locationAgeMs = SystemClock.elapsedRealtime() -
2317 location.getElapsedRealtimeNanos() / NANOS_PER_MILLI;
2318 if ((locationAgeMs > mLastLocationMaxAgeMs)
2319 && (mAppOps.unsafeCheckOp(op, uid, packageName)
2320 == AppOpsManager.MODE_FOREGROUND)) {
2321 return null;
2322 }
2323
Victoria Lease37425c32012-10-16 16:08:48 -07002324 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002325 Location noGPSLocation = location.getExtraLocation(
2326 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002327 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002328 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002329 }
Victoria Lease37425c32012-10-16 16:08:48 -07002330 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002331 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002332 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002333 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002334 return null;
2335 } finally {
2336 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002337 }
2338 }
2339
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002340 /**
2341 * Provides an interface to inject and set the last location if location is not available
2342 * currently.
2343 *
2344 * This helps in cases where the product (Cars for example) has saved the last known location
2345 * before powering off. This interface lets the client inject the saved location while the GPS
2346 * chipset is getting its first fix, there by improving user experience.
2347 *
2348 * @param location - Location object to inject
2349 * @return true if update was successful, false if not
2350 */
2351 @Override
2352 public boolean injectLocation(Location location) {
2353 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2354 "Location Hardware permission not granted to inject location");
2355 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2356 "Access Fine Location permission not granted to inject Location");
2357
2358 if (location == null) {
2359 if (D) {
2360 Log.d(TAG, "injectLocation(): called with null location");
2361 }
2362 return false;
2363 }
2364 LocationProviderInterface p = null;
2365 String provider = location.getProvider();
2366 if (provider != null) {
2367 p = mProvidersByName.get(provider);
2368 }
2369 if (p == null) {
2370 if (D) {
2371 Log.d(TAG, "injectLocation(): unknown provider");
2372 }
2373 return false;
2374 }
2375 synchronized (mLock) {
2376 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2377 if (D) {
2378 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2379 }
2380 return false;
2381 } else {
2382 // NOTE: If last location is already available, location is not injected. If
2383 // provider's normal source (like a GPS chipset) have already provided an output,
2384 // there is no need to inject this location.
2385 if (mLastLocation.get(provider) == null) {
2386 updateLastLocationLocked(location, provider);
2387 } else {
2388 if (D) {
2389 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2390 }
2391 return false;
2392 }
2393 }
2394 }
2395 return true;
2396 }
2397
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002398 @Override
2399 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2400 String packageName) {
2401 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002402 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2403 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002404 checkPendingIntent(intent);
2405 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002406 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2407 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002408 // Require that caller can manage given document
2409 boolean callerHasLocationHardwarePermission =
2410 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002411 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002412 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2413 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002414
Victoria Lease37425c32012-10-16 16:08:48 -07002415 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002416
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002417 // geo-fence manager uses the public location API, need to clear identity
2418 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002419 // TODO: http://b/23822629
2420 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002421 // temporary measure until geofences work for secondary users
2422 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2423 return;
2424 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002425 long identity = Binder.clearCallingIdentity();
2426 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002427 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2428 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002429 } finally {
2430 Binder.restoreCallingIdentity(identity);
2431 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002432 }
2433
2434 @Override
2435 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002436 checkPendingIntent(intent);
2437 checkPackageName(packageName);
2438
2439 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2440
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002441 // geo-fence manager uses the public location API, need to clear identity
2442 long identity = Binder.clearCallingIdentity();
2443 try {
2444 mGeofenceManager.removeFence(geofence, intent);
2445 } finally {
2446 Binder.restoreCallingIdentity(identity);
2447 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002448 }
2449
2450
2451 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002452 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002453 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002454 return false;
2455 }
2456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002457 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002458 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002460 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 return false;
2462 }
2463 return true;
2464 }
2465
Nick Pellye0fd6932012-07-11 10:26:13 -07002466 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002467 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002468 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002469 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002470 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002471 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002472 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 }
2475 }
2476
Nick Pellye0fd6932012-07-11 10:26:13 -07002477 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002478 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002479 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002480 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002481 return false;
2482 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002483
2484 synchronized (mLock) {
2485 Identity callerIdentity
2486 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002487 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002488 long identity = Binder.clearCallingIdentity();
2489 try {
2490 if (isThrottlingExemptLocked(callerIdentity)
2491 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002492 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002493 return mGnssMeasurementsProvider.addListener(listener);
2494 }
2495 } finally {
2496 Binder.restoreCallingIdentity(identity);
2497 }
2498
2499 return true;
2500 }
destradaaea8a8a62014-06-23 18:19:03 -07002501 }
2502
2503 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002504 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2505 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002506 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002507 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002508 mGnssMeasurementsProvider.removeListener(listener);
2509 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002510 }
destradaaea8a8a62014-06-23 18:19:03 -07002511 }
2512
2513 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002514 public boolean addGnssNavigationMessageListener(
2515 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002516 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002517 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002518 return false;
2519 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002520
2521 synchronized (mLock) {
2522 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002523 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002524 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002525 long identity = Binder.clearCallingIdentity();
2526 try {
2527 if (isThrottlingExemptLocked(callerIdentity)
2528 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002529 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002530 return mGnssNavigationMessageProvider.addListener(listener);
2531 }
2532 } finally {
2533 Binder.restoreCallingIdentity(identity);
2534 }
2535
2536 return true;
2537 }
destradaa4b3e3932014-07-21 18:01:47 -07002538 }
2539
2540 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002541 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2542 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002543 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002544 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002545 mGnssNavigationMessageProvider.removeListener(listener);
2546 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002547 }
destradaa4b3e3932014-07-21 18:01:47 -07002548 }
2549
2550 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002552 if (provider == null) {
2553 // throw NullPointerException to remain compatible with previous implementation
2554 throw new NullPointerException();
2555 }
Victoria Lease37425c32012-10-16 16:08:48 -07002556 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2557 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002559 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002560 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002561 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002562 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2563 }
2564
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002565 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002566 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002567 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002568
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002569 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 }
2571 }
2572
Nick Pellye0fd6932012-07-11 10:26:13 -07002573 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002574 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002575 if (Binder.getCallingUid() != Process.myUid()) {
2576 throw new SecurityException(
2577 "calling sendNiResponse from outside of the system is not allowed");
2578 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002579 try {
2580 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002581 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002582 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002583 return false;
2584 }
2585 }
2586
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002588 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002589 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002590 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002592 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002593 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002594 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002595 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002596 }
2597
Victoria Lease37425c32012-10-16 16:08:48 -07002598 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2599 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002601 LocationProviderInterface p;
2602 synchronized (mLock) {
2603 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
2605
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002606 if (p == null) return null;
2607 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002608 }
2609
Jason Monkb71218a2015-06-17 14:44:39 -04002610 /**
2611 * @return null if the provider does not exist
2612 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002613 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002614 */
2615 @Override
2616 public String getNetworkProviderPackage() {
2617 LocationProviderInterface p;
2618 synchronized (mLock) {
2619 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2620 return null;
2621 }
2622 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2623 }
2624
2625 if (p instanceof LocationProviderProxy) {
2626 return ((LocationProviderProxy) p).getConnectedPackageName();
2627 }
2628 return null;
2629 }
2630
Maggieaa080f92018-01-04 15:35:11 -08002631 /**
Maggie2a9409e2018-03-21 11:47:28 -07002632 * Returns the current location enabled/disabled status for a user
2633 *
2634 * @param userId the id of the user
2635 * @return true if location is enabled
2636 */
2637 @Override
2638 public boolean isLocationEnabledForUser(int userId) {
2639 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2640 checkInteractAcrossUsersPermission(userId);
2641
2642 long identity = Binder.clearCallingIdentity();
2643 try {
2644 synchronized (mLock) {
2645 final String allowedProviders = Settings.Secure.getStringForUser(
2646 mContext.getContentResolver(),
2647 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2648 userId);
2649 if (allowedProviders == null) {
2650 return false;
2651 }
2652 final List<String> providerList = Arrays.asList(allowedProviders.split(","));
2653 for(String provider : mRealProviders.keySet()) {
2654 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2655 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2656 continue;
2657 }
2658 if (providerList.contains(provider)) {
2659 return true;
2660 }
2661 }
2662 return false;
2663 }
2664 } finally {
2665 Binder.restoreCallingIdentity(identity);
2666 }
2667 }
2668
2669 /**
2670 * Enable or disable location for a user
2671 *
2672 * @param enabled true to enable location, false to disable location
2673 * @param userId the id of the user
2674 */
2675 @Override
2676 public void setLocationEnabledForUser(boolean enabled, int userId) {
2677 mContext.enforceCallingPermission(
2678 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2679 "Requires WRITE_SECURE_SETTINGS permission");
2680
2681 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2682 checkInteractAcrossUsersPermission(userId);
2683
2684 long identity = Binder.clearCallingIdentity();
2685 try {
2686 synchronized (mLock) {
2687 final Set<String> allRealProviders = mRealProviders.keySet();
2688 // Update all providers on device plus gps and network provider when disabling
2689 // location
2690 Set<String> allProvidersSet = new ArraySet<>(allRealProviders.size() + 2);
2691 allProvidersSet.addAll(allRealProviders);
2692 // When disabling location, disable gps and network provider that could have been
2693 // enabled by location mode api.
2694 if (enabled == false) {
2695 allProvidersSet.add(LocationManager.GPS_PROVIDER);
2696 allProvidersSet.add(LocationManager.NETWORK_PROVIDER);
2697 }
2698 if (allProvidersSet.isEmpty()) {
2699 return;
2700 }
2701 // to ensure thread safety, we write the provider name with a '+' or '-'
2702 // and let the SettingsProvider handle it rather than reading and modifying
2703 // the list of enabled providers.
2704 final String prefix = enabled ? "+" : "-";
2705 StringBuilder locationProvidersAllowed = new StringBuilder();
2706 for (String provider : allProvidersSet) {
2707 if (provider.equals(LocationManager.PASSIVE_PROVIDER)
2708 || provider.equals(LocationManager.FUSED_PROVIDER)) {
2709 continue;
2710 }
2711 locationProvidersAllowed.append(prefix);
2712 locationProvidersAllowed.append(provider);
2713 locationProvidersAllowed.append(",");
2714 }
2715 // Remove the trailing comma
2716 locationProvidersAllowed.setLength(locationProvidersAllowed.length() - 1);
2717 Settings.Secure.putStringForUser(
2718 mContext.getContentResolver(),
2719 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2720 locationProvidersAllowed.toString(),
2721 userId);
2722 }
2723 } finally {
2724 Binder.restoreCallingIdentity(identity);
2725 }
2726 }
2727
2728 /**
2729 * Returns the current enabled/disabled status of a location provider and user
2730 *
2731 * @param provider name of the provider
2732 * @param userId the id of the user
2733 * @return true if the provider exists and is enabled
2734 */
2735 @Override
2736 public boolean isProviderEnabledForUser(String provider, int userId) {
2737 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2738 checkInteractAcrossUsersPermission(userId);
2739
2740 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2741 // so we discourage its use
2742 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2743
2744 int uid = Binder.getCallingUid();
2745 synchronized (mLock) {
2746 LocationProviderInterface p = mProvidersByName.get(provider);
2747 return p != null
2748 && isAllowedByUserSettingsLocked(provider, uid, userId);
2749 }
2750 }
2751
2752 /**
2753 * Enable or disable a single location provider.
2754 *
2755 * @param provider name of the provider
2756 * @param enabled true to enable the provider. False to disable the provider
2757 * @param userId the id of the user to set
2758 * @return true if the value was set, false on errors
2759 */
2760 @Override
2761 public boolean setProviderEnabledForUser(String provider, boolean enabled, int userId) {
2762 mContext.enforceCallingPermission(
2763 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2764 "Requires WRITE_SECURE_SETTINGS permission");
2765
2766 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2767 checkInteractAcrossUsersPermission(userId);
2768
2769 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2770 // so we discourage its use
2771 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2772
2773 long identity = Binder.clearCallingIdentity();
2774 try {
2775 synchronized (mLock) {
2776 // No such provider exists
2777 if (!mProvidersByName.containsKey(provider)) return false;
2778
2779 // If it is a test provider, do not write to Settings.Secure
2780 if (mMockProviders.containsKey(provider)) {
2781 setTestProviderEnabled(provider, enabled);
2782 return true;
2783 }
2784
2785 // to ensure thread safety, we write the provider name with a '+' or '-'
2786 // and let the SettingsProvider handle it rather than reading and modifying
2787 // the list of enabled providers.
2788 String providerChange = (enabled ? "+" : "-") + provider;
2789 return Settings.Secure.putStringForUser(
2790 mContext.getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2791 providerChange, userId);
2792 }
2793 } finally {
2794 Binder.restoreCallingIdentity(identity);
2795 }
2796 }
2797
2798 /**
Maggieaa080f92018-01-04 15:35:11 -08002799 * Read location provider status from Settings.Secure
2800 *
2801 * @param provider the location provider to query
2802 * @param userId the user id to query
2803 * @return true if the provider is enabled
2804 */
2805 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2806 long identity = Binder.clearCallingIdentity();
2807 try {
2808 // Use system settings
2809 ContentResolver cr = mContext.getContentResolver();
2810 String allowedProviders = Settings.Secure.getStringForUser(
2811 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2812 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2813 } finally {
2814 Binder.restoreCallingIdentity(identity);
2815 }
2816 }
2817
2818 /**
Maggie2a9409e2018-03-21 11:47:28 -07002819 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2820 * current user id
2821 *
2822 * @param userId the user id to get or set value
2823 */
2824 private void checkInteractAcrossUsersPermission(int userId) {
2825 int uid = Binder.getCallingUid();
2826 if (UserHandle.getUserId(uid) != userId) {
2827 if (ActivityManager.checkComponentPermission(
2828 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2829 != PERMISSION_GRANTED) {
2830 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2831 }
2832 }
2833 }
2834
2835 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002836 * Returns "true" if the UID belongs to a bound location provider.
2837 *
2838 * @param uid the uid
2839 * @return true if uid belongs to a bound location provider
2840 */
2841 private boolean isUidALocationProvider(int uid) {
2842 if (uid == Process.SYSTEM_UID) {
2843 return true;
2844 }
2845 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002846 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002847 }
2848 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002849 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002850 }
2851 return false;
2852 }
2853
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002854 private void checkCallerIsProvider() {
2855 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002856 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002857 return;
2858 }
2859
2860 // Previously we only used the INSTALL_LOCATION_PROVIDER
2861 // check. But that is system or signature
2862 // protection level which is not flexible enough for
2863 // providers installed oustide the system image. So
2864 // also allow providers with a UID matching the
2865 // currently bound package name
2866
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002867 if (isUidALocationProvider(Binder.getCallingUid())) {
2868 return;
2869 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002870
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002871 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2872 "or UID of a currently bound location provider");
2873 }
2874
David Christie1f141c12014-05-14 15:11:15 -07002875 /**
2876 * Returns true if the given package belongs to the given uid.
2877 */
2878 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002879 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 return false;
2881 }
David Christie1f141c12014-05-14 15:11:15 -07002882 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2883 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002884 return false;
2885 }
David Christie1f141c12014-05-14 15:11:15 -07002886 for (String name : packageNames) {
2887 if (packageName.equals(name)) {
2888 return true;
2889 }
2890 }
2891 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
2893
Nick Pellye0fd6932012-07-11 10:26:13 -07002894 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002895 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002896 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002897
Nick Pelly2eeeec22012-07-18 13:13:37 -07002898 if (!location.isComplete()) {
2899 Log.w(TAG, "Dropping incomplete location: " + location);
2900 return;
2901 }
2902
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002903 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2904 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002905 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002906 mLocationHandler.sendMessageAtFrontOfQueue(m);
2907 }
2908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909
Laurent Tu75defb62012-11-01 16:21:52 -07002910 private static boolean shouldBroadcastSafe(
2911 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002912 // Always broadcast the first update
2913 if (lastLoc == null) {
2914 return true;
2915 }
2916
Nick Pellyf1be6862012-05-15 10:53:42 -07002917 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002918 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002919 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2920 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002921 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 return false;
2923 }
2924
2925 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002926 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002927 if (minDistance > 0.0) {
2928 if (loc.distanceTo(lastLoc) <= minDistance) {
2929 return false;
2930 }
2931 }
2932
Laurent Tu75defb62012-11-01 16:21:52 -07002933 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002934 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002935 return false;
2936 }
2937
2938 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002939 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002940 }
2941
Mike Lockwooda4903f22010-02-17 06:42:23 -05002942 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002943 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002944 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002945 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002946 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002947 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002948 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002949 updateLastLocationLocked(location, provider);
2950 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002951 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002952 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002953 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2954 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002955 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956
David Christie1b9b7b12013-04-15 15:31:11 -07002957 // Update last known coarse interval location if enough time has passed.
2958 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2959 if (lastLocationCoarseInterval == null) {
2960 lastLocationCoarseInterval = new Location(location);
2961 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2962 }
2963 long timeDiffNanos = location.getElapsedRealtimeNanos()
2964 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2965 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2966 lastLocationCoarseInterval.set(location);
2967 }
2968 // Don't ever return a coarse location that is more recent than the allowed update
2969 // interval (i.e. don't allow an app to keep registering and unregistering for
2970 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002971 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002972 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2973
Laurent Tu60ec50a2012-10-04 17:00:10 -07002974 // Skip if there are no UpdateRecords for this provider.
2975 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2976 if (records == null || records.size() == 0) return;
2977
Victoria Lease09016ab2012-09-16 12:33:15 -07002978 // Fetch coarse location
2979 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002980 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002981 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2982 }
2983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 // Fetch latest status update time
2985 long newStatusUpdateTime = p.getStatusUpdateTime();
2986
David Christie2ff96af2014-01-30 16:09:37 -08002987 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002988 Bundle extras = new Bundle();
2989 int status = p.getStatus(extras);
2990
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002991 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002992 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002993
Soonil Nagarkar94749f72018-11-08 11:46:43 -08002994 // Broadcast location to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002995 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002996 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002997 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002998
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002999 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
3000 if (!isCurrentProfile(receiverUserId)
3001 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07003002 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07003003 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07003004 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003005 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07003006 }
3007 continue;
3008 }
3009
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003010 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08003011 if (D) {
3012 Log.d(TAG, "skipping loc update for blacklisted app: " +
3013 receiver.mIdentity.mPackageName);
3014 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003015 continue;
3016 }
3017
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003018 if (!reportLocationAccessNoThrow(
3019 receiver.mIdentity.mPid,
3020 receiver.mIdentity.mUid,
3021 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003022 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08003023 if (D) {
3024 Log.d(TAG, "skipping loc update for no op app: " +
3025 receiver.mIdentity.mPackageName);
3026 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08003027 continue;
3028 }
3029
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003030 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07003031 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
3032 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003033 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07003034 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003035 }
Victoria Lease09016ab2012-09-16 12:33:15 -07003036 if (notifyLocation != null) {
3037 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07003038 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07003039 if (lastLoc == null) {
3040 lastLoc = new Location(notifyLocation);
3041 r.mLastFixBroadcast = lastLoc;
3042 } else {
3043 lastLoc.set(notifyLocation);
3044 }
3045 if (!receiver.callLocationChangedLocked(notifyLocation)) {
3046 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
3047 receiverDead = true;
3048 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07003049 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 }
3051 }
3052
Soonil Nagarkar94749f72018-11-08 11:46:43 -08003053 // TODO: location provider status callbacks have been disabled and deprecated, and are
3054 // guarded behind this setting now. should be removed completely post-Q
3055 if (Settings.Global.getInt(mContext.getContentResolver(),
3056 LOCATION_DISABLE_STATUS_CALLBACKS, 1) == 0) {
3057 long prevStatusUpdateTime = r.mLastStatusBroadcast;
3058 if ((newStatusUpdateTime > prevStatusUpdateTime)
3059 && (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060
Soonil Nagarkar94749f72018-11-08 11:46:43 -08003061 r.mLastStatusBroadcast = newStatusUpdateTime;
3062 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
3063 receiverDead = true;
3064 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
3065 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07003066 }
3067 }
3068
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003069 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07003070 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003071 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003072 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003073 }
3074 deadUpdateRecords.add(r);
3075 }
3076 // track dead receivers
3077 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07003078 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003079 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07003080 }
3081 if (!deadReceivers.contains(receiver)) {
3082 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
3084 }
3085 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003086
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003087 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003089 for (Receiver receiver : deadReceivers) {
3090 removeUpdatesLocked(receiver);
3091 }
3092 }
3093 if (deadUpdateRecords != null) {
3094 for (UpdateRecord r : deadUpdateRecords) {
3095 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 }
Victoria Lease8b38b292012-12-04 15:04:43 -08003097 applyRequirementsLocked(provider);
3098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 }
3100
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08003101 /**
3102 * Updates last location with the given location
3103 *
3104 * @param location new location to update
3105 * @param provider Location provider to update for
3106 */
3107 private void updateLastLocationLocked(Location location, String provider) {
3108 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3109 Location lastNoGPSLocation;
3110 Location lastLocation = mLastLocation.get(provider);
3111 if (lastLocation == null) {
3112 lastLocation = new Location(provider);
3113 mLastLocation.put(provider, lastLocation);
3114 } else {
3115 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3116 if (noGPSLocation == null && lastNoGPSLocation != null) {
3117 // New location has no no-GPS location: adopt last no-GPS location. This is set
3118 // directly into location because we do not want to notify COARSE clients.
3119 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
3120 }
3121 }
3122 lastLocation.set(location);
3123 }
3124
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003126 public LocationWorkerHandler(Looper looper) {
3127 super(looper, null, true);
3128 }
3129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 @Override
3131 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003132 switch (msg.what) {
3133 case MSG_LOCATION_CHANGED:
3134 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3135 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
3137 }
3138 }
3139
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003140 private boolean isMockProvider(String provider) {
3141 synchronized (mLock) {
3142 return mMockProviders.containsKey(provider);
3143 }
3144 }
3145
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003146 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003147 // create a working copy of the incoming Location so that the service can modify it without
3148 // disturbing the caller's copy
3149 Location myLocation = new Location(location);
3150 String provider = myLocation.getProvider();
3151
3152 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3153 // bit if location did not come from a mock provider because passive/fused providers can
3154 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3155 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3156 myLocation.setIsFromMockProvider(true);
3157 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003158
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003159 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003160 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3161 if (!passive) {
3162 // notify passive provider of the new location
3163 mPassiveProvider.updateLocation(myLocation);
3164 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003165 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003169
Mike Lockwoode97ae402010-09-29 15:23:46 -04003170 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3171 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003172 public void onPackageDisappeared(String packageName, int reason) {
3173 // remove all receivers associated with this package name
3174 synchronized (mLock) {
3175 ArrayList<Receiver> deadReceivers = null;
3176
3177 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003178 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003179 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003180 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003181 }
3182 deadReceivers.add(receiver);
3183 }
3184 }
3185
3186 // perform removal outside of mReceivers loop
3187 if (deadReceivers != null) {
3188 for (Receiver receiver : deadReceivers) {
3189 removeUpdatesLocked(receiver);
3190 }
3191 }
3192 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003193 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003194 };
3195
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 // Geocoder
3197
Nick Pellye0fd6932012-07-11 10:26:13 -07003198 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003199 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003200 return mGeocodeProvider != null;
3201 }
3202
Nick Pellye0fd6932012-07-11 10:26:13 -07003203 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003205 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003206 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003207 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3208 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003209 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003210 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003211 }
3212
Mike Lockwooda55c3212009-04-15 11:10:11 -04003213
Nick Pellye0fd6932012-07-11 10:26:13 -07003214 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003216 double lowerLeftLatitude, double lowerLeftLongitude,
3217 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003218 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003219
3220 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003221 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3222 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3223 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003225 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 }
3227
3228 // Mock Providers
3229
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003230 private boolean canCallerAccessMockLocation(String opPackageName) {
3231 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3232 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 }
3234
Nick Pellye0fd6932012-07-11 10:26:13 -07003235 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003236 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3237 if (!canCallerAccessMockLocation(opPackageName)) {
3238 return;
3239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240
Mike Lockwooda4903f22010-02-17 06:42:23 -05003241 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3242 throw new IllegalArgumentException("Cannot mock the passive location provider");
3243 }
3244
Mike Lockwood86328a92009-10-23 08:38:25 -04003245 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003246 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003247 // remove the real provider if we are replacing GPS or network provider
3248 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003249 || LocationManager.NETWORK_PROVIDER.equals(name)
3250 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003251 LocationProviderInterface p = mProvidersByName.get(name);
3252 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003253 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003254 }
3255 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003256 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 updateProvidersLocked();
3258 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003259 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
3261
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003262 private void addTestProviderLocked(String name, ProviderProperties properties) {
3263 if (mProvidersByName.get(name) != null) {
3264 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3265 }
3266 MockProvider provider = new MockProvider(name, this, properties);
3267 addProviderLocked(provider);
3268 mMockProviders.put(name, provider);
3269 mLastLocation.put(name, null);
3270 mLastLocationCoarseInterval.put(name, null);
3271 }
3272
Nick Pellye0fd6932012-07-11 10:26:13 -07003273 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003274 public void removeTestProvider(String provider, String opPackageName) {
3275 if (!canCallerAccessMockLocation(opPackageName)) {
3276 return;
3277 }
3278
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003279 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003280
3281 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003282 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003283 clearTestProviderEnabled(provider, opPackageName);
3284 clearTestProviderLocation(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003285
You Kima6d0b6f2012-10-28 03:58:44 +09003286 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003287 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3289 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003290 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003291 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003292
3293 // reinstate real provider if available
3294 LocationProviderInterface realProvider = mRealProviders.get(provider);
3295 if (realProvider != null) {
3296 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003297 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003298 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003299 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003301 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 }
3303 }
3304
Nick Pellye0fd6932012-07-11 10:26:13 -07003305 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003306 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3307 if (!canCallerAccessMockLocation(opPackageName)) {
3308 return;
3309 }
3310
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003311 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003312 MockProvider mockProvider = mMockProviders.get(provider);
3313 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3315 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003316
3317 // Ensure that the location is marked as being mock. There's some logic to do this in
3318 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3319 Location mock = new Location(loc);
3320 mock.setIsFromMockProvider(true);
3321
3322 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3323 // The location has an explicit provider that is different from the mock provider
3324 // name. The caller may be trying to fool us via bug 33091107.
3325 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3326 provider + "!=" + loc.getProvider());
3327 }
3328
Mike Lockwood95427cd2009-05-07 13:27:54 -04003329 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3330 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003331 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003332 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003333 }
3334 }
3335
Nick Pellye0fd6932012-07-11 10:26:13 -07003336 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003337 public void clearTestProviderLocation(String provider, String opPackageName) {
3338 if (!canCallerAccessMockLocation(opPackageName)) {
3339 return;
3340 }
3341
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003342 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003343 MockProvider mockProvider = mMockProviders.get(provider);
3344 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003345 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3346 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003347 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003348 }
3349 }
3350
Nick Pellye0fd6932012-07-11 10:26:13 -07003351 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003352 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3353 if (!canCallerAccessMockLocation(opPackageName)) {
3354 return;
3355 }
Maggie2a9409e2018-03-21 11:47:28 -07003356 setTestProviderEnabled(provider, enabled);
3357 }
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003358
Maggie2a9409e2018-03-21 11:47:28 -07003359 /** Enable or disable a test location provider. */
3360 private void setTestProviderEnabled(String provider, boolean enabled) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003361 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003362 MockProvider mockProvider = mMockProviders.get(provider);
3363 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3365 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003366 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003368 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 mEnabledProviders.add(provider);
3370 mDisabledProviders.remove(provider);
3371 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003372 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 mEnabledProviders.remove(provider);
3374 mDisabledProviders.add(provider);
3375 }
3376 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003377 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003378 }
3379 }
3380
Nick Pellye0fd6932012-07-11 10:26:13 -07003381 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003382 public void clearTestProviderEnabled(String provider, String opPackageName) {
3383 if (!canCallerAccessMockLocation(opPackageName)) {
3384 return;
3385 }
3386
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003387 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003388 MockProvider mockProvider = mMockProviders.get(provider);
3389 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3391 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003392 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 mEnabledProviders.remove(provider);
3394 mDisabledProviders.remove(provider);
3395 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003396 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 }
3398 }
3399
Nick Pellye0fd6932012-07-11 10:26:13 -07003400 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003401 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3402 String opPackageName) {
3403 if (!canCallerAccessMockLocation(opPackageName)) {
3404 return;
3405 }
3406
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003407 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003408 MockProvider mockProvider = mMockProviders.get(provider);
3409 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3411 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003412 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 }
3414 }
3415
Nick Pellye0fd6932012-07-11 10:26:13 -07003416 @Override
Philip P. Moltmanned988282018-11-07 16:19:42 -08003417 public PendingIntent createManageLocationPermissionIntent(String packageName,
3418 String permission) {
3419 Preconditions.checkNotNull(packageName);
3420 Preconditions.checkArgument(permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)
3421 || permission.equals(Manifest.permission.ACCESS_COARSE_LOCATION)
3422 || permission.equals(Manifest.permission.ACCESS_BACKGROUND_LOCATION));
3423
3424 int callingUid = Binder.getCallingUid();
3425 long token = Binder.clearCallingIdentity();
3426 try {
3427 String locProvider = getNetworkProviderPackage();
3428 if (locProvider == null) {
3429 return null;
3430 }
3431
3432 PackageInfo locProviderInfo;
3433 try {
3434 locProviderInfo = mContext.getPackageManager().getPackageInfo(
3435 locProvider, PackageManager.MATCH_DIRECT_BOOT_AUTO);
3436 } catch (NameNotFoundException e) {
3437 Log.e(TAG, "Could not resolve " + locProvider, e);
3438 return null;
3439 }
3440
3441 if (locProviderInfo.applicationInfo.uid != callingUid) {
3442 throw new SecurityException("Only " + locProvider + " can call this API");
3443 }
3444
3445 Intent intent = new Intent(Intent.ACTION_MANAGE_APP_PERMISSION);
3446 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, packageName);
3447 intent.putExtra(Intent.EXTRA_PERMISSION_NAME, permission);
3448 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3449
3450 return PendingIntent.getActivity(mContext,
3451 Objects.hash(packageName, permission), intent,
3452 PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_IMMUTABLE);
3453 } finally {
3454 Binder.restoreCallingIdentity(token);
3455 }
3456 }
3457
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003458 private void log(String log) {
3459 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003460 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003461 }
3462 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003463
3464 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003466 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003467
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003468 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003469 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3470 if (mGnssMetricsProvider != null) {
3471 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3472 }
3473 return;
3474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003477 for (Receiver receiver : mReceivers.values()) {
3478 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003479 }
David Christie2ff96af2014-01-30 16:09:37 -08003480 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003481 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3482 pw.println(" " + entry.getKey() + ":");
3483 for (UpdateRecord record : entry.getValue()) {
3484 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 }
3486 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003487 pw.println(" Active GnssMeasurement Listeners:");
3488 for (Identity identity : mGnssMeasurementsListeners.values()) {
3489 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3490 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3491 }
3492 pw.println(" Active GnssNavigationMessage Listeners:");
3493 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3494 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3495 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3496 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003497 pw.println(" Overlay Provider Packages:");
3498 for (LocationProviderInterface provider : mProviders) {
3499 if (provider instanceof LocationProviderProxy) {
3500 pw.println(" " + provider.getName() + ": "
3501 + ((LocationProviderProxy) provider).getConnectedPackageName());
3502 }
3503 }
David Christie2ff96af2014-01-30 16:09:37 -08003504 pw.println(" Historical Records by Provider:");
3505 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3506 : mRequestStatistics.statistics.entrySet()) {
3507 PackageProviderKey key = entry.getKey();
3508 PackageStatistics stats = entry.getValue();
3509 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3510 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003511 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003512 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3513 String provider = entry.getKey();
3514 Location location = entry.getValue();
3515 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003516 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003517
David Christie1b9b7b12013-04-15 15:31:11 -07003518 pw.println(" Last Known Locations Coarse Intervals:");
3519 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3520 String provider = entry.getKey();
3521 Location location = entry.getValue();
3522 pw.println(" " + provider + ": " + location);
3523 }
3524
Nick Pellye0fd6932012-07-11 10:26:13 -07003525 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 if (mEnabledProviders.size() > 0) {
3528 pw.println(" Enabled Providers:");
3529 for (String i : mEnabledProviders) {
3530 pw.println(" " + i);
3531 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003533 }
3534 if (mDisabledProviders.size() > 0) {
3535 pw.println(" Disabled Providers:");
3536 for (String i : mDisabledProviders) {
3537 pw.println(" " + i);
3538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003540 pw.append(" ");
3541 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003542 if (mMockProviders.size() > 0) {
3543 pw.println(" Mock Providers:");
3544 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003545 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 }
3547 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003548
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003549 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3550 pw.println(" Throttling Whitelisted Packages:");
3551 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3552 pw.println(" " + packageName);
3553 }
3554 }
3555
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003556 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003557 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003558
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003559 if (args.length > 0 && "short".equals(args[0])) {
3560 return;
3561 }
gomo48f1a642017-11-10 20:35:46 -08003562 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003563 pw.print(provider.getName() + " Internal State");
3564 if (provider instanceof LocationProviderProxy) {
3565 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3566 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003567 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003568 pw.println(":");
3569 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003570 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003571 if (mGnssBatchingInProgress) {
3572 pw.println(" GNSS batching in progress");
3573 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003574 }
3575 }
3576}