blob: 1dd92f3130a74e2b74b77c7704659ffbacbded0d [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;
20
Wyatt Rileycf879db2017-01-12 13:57:38 -080021import android.annotation.NonNull;
Maggieaa080f92018-01-04 15:35:11 -080022import android.app.ActivityManager;
23import android.app.AppOpsManager;
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.PackageManagerInternal;
35import android.content.pm.ResolveInfo;
36import android.content.pm.Signature;
37import android.content.res.Resources;
38import android.database.ContentObserver;
39import android.hardware.location.ActivityRecognitionHardware;
40import android.location.Address;
41import android.location.Criteria;
42import android.location.GeocoderParams;
43import android.location.Geofence;
44import android.location.IBatchedLocationCallback;
45import android.location.IGnssMeasurementsListener;
46import android.location.IGnssNavigationMessageListener;
47import android.location.IGnssStatusListener;
48import android.location.IGnssStatusProvider;
49import android.location.IGpsGeofenceHardware;
50import android.location.ILocationListener;
51import android.location.ILocationManager;
52import android.location.INetInitiatedListener;
53import android.location.Location;
54import android.location.LocationManager;
55import android.location.LocationProvider;
56import android.location.LocationRequest;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.Handler;
60import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
63import android.os.PowerManager;
64import android.os.Process;
65import android.os.RemoteException;
66import android.os.SystemClock;
67import android.os.UserHandle;
68import android.os.UserManager;
69import android.os.WorkSource;
Narayan Kamath32684dd2018-01-08 17:32:51 +000070import android.os.WorkSource.WorkChain;
Maggieaa080f92018-01-04 15:35:11 -080071import android.provider.Settings;
72import android.text.TextUtils;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080073import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080074import android.util.ArraySet;
Maggieaa080f92018-01-04 15:35:11 -080075import android.util.EventLog;
76import android.util.Log;
77import android.util.Slog;
destradaaea8a8a62014-06-23 18:19:03 -070078import com.android.internal.content.PackageMonitor;
79import com.android.internal.location.ProviderProperties;
80import com.android.internal.location.ProviderRequest;
81import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070082import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060083import com.android.internal.util.DumpUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070084import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070085import com.android.server.location.FlpHardwareProvider;
86import com.android.server.location.FusedProxy;
87import com.android.server.location.GeocoderProxy;
88import com.android.server.location.GeofenceManager;
89import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080090import com.android.server.location.GnssLocationProvider;
91import com.android.server.location.GnssMeasurementsProvider;
92import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070093import com.android.server.location.LocationBlacklist;
94import com.android.server.location.LocationFudger;
95import com.android.server.location.LocationProviderInterface;
96import com.android.server.location.LocationProviderProxy;
97import com.android.server.location.LocationRequestStatistics;
98import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
99import com.android.server.location.LocationRequestStatistics.PackageStatistics;
100import com.android.server.location.MockProvider;
101import com.android.server.location.PassiveProvider;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400102import java.io.FileDescriptor;
103import java.io.PrintWriter;
104import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700105import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400106import java.util.HashMap;
107import java.util.HashSet;
108import java.util.List;
109import java.util.Map;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800110import java.util.Map.Entry;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800111import java.util.NoSuchElementException;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400112import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
114/**
115 * The service class that manages LocationProviders and issues location
116 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800118public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800120 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700121
Olivier Gaillard7a222662017-11-20 16:07:24 +0000122 private static final String WAKELOCK_KEY = "*location*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123
Victoria Lease37425c32012-10-16 16:08:48 -0700124 // Location resolution level: no location data whatsoever
125 private static final int RESOLUTION_LEVEL_NONE = 0;
126 // Location resolution level: coarse location data only
127 private static final int RESOLUTION_LEVEL_COARSE = 1;
128 // Location resolution level: fine location data
129 private static final int RESOLUTION_LEVEL_FINE = 2;
130
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700132 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700134 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400135 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700136 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
137
138 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700139 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700140 private static final String FUSED_LOCATION_SERVICE_ACTION =
141 "com.android.location.service.FusedLocationProvider";
142
143 private static final int MSG_LOCATION_CHANGED = 1;
144
David Christie1b9b7b12013-04-15 15:31:11 -0700145 private static final long NANOS_PER_MILLI = 1000000L;
146
David Christie0b837452013-07-29 16:02:13 -0700147 // The maximum interval a location request can have and still be considered "high power".
148 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
149
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700150 private static final int FOREGROUND_IMPORTANCE_CUTOFF
gomo48f1a642017-11-10 20:35:46 -0800151 = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700152
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800153 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800154 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800155
Nick Pellyf1be6862012-05-15 10:53:42 -0700156 // Location Providers may sometimes deliver location updates
157 // slightly faster that requested - provide grace period so
158 // we don't unnecessarily filter events that are otherwise on
159 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700160 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700161
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700162 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
163
164 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800165 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700166
167 // used internally for synchronization
168 private final Object mLock = new Object();
169
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700170 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700171 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700173 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700174 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800175 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700176 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700177 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800178 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700179 private INetInitiatedListener mNetInitiatedListener;
180 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700181 private PassiveProvider mPassiveProvider; // track passive provider for special cases
182 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800183 private GnssMeasurementsProvider mGnssMeasurementsProvider;
184 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700185 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700187 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700189 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800190 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
192 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800193 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700195 // Mock (test) providers
196 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800197 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700199 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800200 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700202 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500203 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800204 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400205
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700206 // real providers, saved here when mocked out
207 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800208 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700210 // mapping from provider name to provider
211 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800212 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800213
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700214 // mapping from provider name to all its UpdateRecords
215 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800216 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700217
David Christie2ff96af2014-01-30 16:09:37 -0800218 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
219
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700220 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800221 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
David Christie1b9b7b12013-04-15 15:31:11 -0700223 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
224 // locations stored here are not fudged for coarse permissions.
225 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800226 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700227
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800228 // all providers that operate over proxy, for authorizing incoming location and whitelisting
229 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700230 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800231 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800233 private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800234
Wyatt Riley11cc7492018-01-17 08:48:27 -0800235 private final ArrayMap<IBinder, Identity> mGnssMeasurementsListeners = new ArrayMap<>();
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800236
Wyatt Riley11cc7492018-01-17 08:48:27 -0800237 private final ArrayMap<IBinder, Identity>
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800238 mGnssNavigationMessageListeners = new ArrayMap<>();
239
Victoria Lease38389b62012-09-30 11:44:22 -0700240 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700241 private int mCurrentUserId = UserHandle.USER_SYSTEM;
gomo48f1a642017-11-10 20:35:46 -0800242 private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
Victoria Lease38389b62012-09-30 11:44:22 -0700243
Lifu Tang9363b942016-02-16 18:07:00 -0800244 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800245
Siddharth Raybb608c82017-03-16 11:33:34 -0700246 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700247
248 private GnssLocationProvider.GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800249 private IBatchedLocationCallback mGnssBatchingCallback;
250 private LinkedCallback mGnssBatchingDeathCallback;
251 private boolean mGnssBatchingInProgress = false;
252
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700253 public LocationManagerService(Context context) {
254 super();
255 mContext = context;
gomo48f1a642017-11-10 20:35:46 -0800256 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800257
Svet Ganovadc1cf42015-06-15 16:36:24 -0700258 // Let the package manager query which are the default location
259 // providers as they get certain permissions granted by default.
260 PackageManagerInternal packageManagerInternal = LocalServices.getService(
261 PackageManagerInternal.class);
262 packageManagerInternal.setLocationPackagesProvider(
263 new PackageManagerInternal.PackagesProvider() {
264 @Override
265 public String[] getPackages(int userId) {
266 return mContext.getResources().getStringArray(
267 com.android.internal.R.array.config_locationProviderPackageNames);
268 }
269 });
270
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700271 if (D) Log.d(TAG, "Constructed");
272
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700273 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700274 }
275
Svetoslav Ganova0027152013-06-25 14:59:53 -0700276 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700277 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700278 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700279
Victoria Lease5cd731a2012-12-19 15:04:21 -0800280 // fetch package manager
281 mPackageManager = mContext.getPackageManager();
282
Victoria Lease0aa28602013-05-29 15:28:26 -0700283 // fetch power manager
284 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800285
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800286 // fetch activity manager
287 mActivityManager
288 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
289
Victoria Lease5cd731a2012-12-19 15:04:21 -0800290 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700291 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800292
293 // prepare mLocationHandler's dependents
294 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
295 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
296 mBlacklist.init();
297 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
298
Dianne Hackbornc2293022013-02-06 23:14:49 -0800299 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700300 AppOpsManager.OnOpChangedListener callback
301 = new AppOpsManager.OnOpChangedInternalListener() {
302 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800303 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700304 for (Receiver receiver : mReceivers.values()) {
305 receiver.updateMonitoring(true);
306 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800307 applyAllProviderRequirementsLocked();
308 }
309 }
310 };
311 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
312
David Christieb870dbf2015-06-22 12:42:53 -0700313 PackageManager.OnPermissionsChangedListener permissionListener
314 = new PackageManager.OnPermissionsChangedListener() {
315 @Override
316 public void onPermissionsChanged(final int uid) {
317 synchronized (mLock) {
318 applyAllProviderRequirementsLocked();
319 }
320 }
321 };
322 mPackageManager.addOnPermissionsChangeListener(permissionListener);
323
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800324 // listen for background/foreground changes
325 ActivityManager.OnUidImportanceListener uidImportanceListener
326 = new ActivityManager.OnUidImportanceListener() {
327 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700328 public void onUidImportance(final int uid, final int importance) {
329 mLocationHandler.post(new Runnable() {
330 @Override
331 public void run() {
332 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800333 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700334 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800335 }
336 };
337 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700338 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800339
Amith Yamasanib27528d2014-06-05 15:02:10 -0700340 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
341 updateUserProfiles(mCurrentUserId);
342
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800343 updateBackgroundThrottlingWhitelistLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800344
Victoria Lease5cd731a2012-12-19 15:04:21 -0800345 // prepare providers
346 loadProvidersLocked();
347 updateProvidersLocked();
348 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700349
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700350 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700351 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700352 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700353 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800354 @Override
355 public void onChange(boolean selfChange) {
356 synchronized (mLock) {
357 updateProvidersLocked();
358 }
359 }
360 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800361 mContext.getContentResolver().registerContentObserver(
362 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
363 true,
364 new ContentObserver(mLocationHandler) {
365 @Override
366 public void onChange(boolean selfChange) {
367 synchronized (mLock) {
368 updateProvidersLocked();
369 }
370 }
371 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800372 mContext.getContentResolver().registerContentObserver(
gomo48f1a642017-11-10 20:35:46 -0800373 Settings.Global.getUriFor(
374 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
375 true,
376 new ContentObserver(mLocationHandler) {
377 @Override
378 public void onChange(boolean selfChange) {
379 synchronized (mLock) {
380 updateBackgroundThrottlingWhitelistLocked();
381 updateProvidersLocked();
382 }
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800383 }
gomo48f1a642017-11-10 20:35:46 -0800384 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800385 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700386
Victoria Lease38389b62012-09-30 11:44:22 -0700387 // listen for user change
388 IntentFilter intentFilter = new IntentFilter();
389 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700390 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
391 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700392 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700393
394 mContext.registerReceiverAsUser(new BroadcastReceiver() {
395 @Override
396 public void onReceive(Context context, Intent intent) {
397 String action = intent.getAction();
398 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
399 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700400 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
401 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
402 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700403 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700404 // shutdown only if UserId indicates whole system, not just one user
gomo48f1a642017-11-10 20:35:46 -0800405 if (D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700406 if (getSendingUserId() == UserHandle.USER_ALL) {
407 shutdownComponents();
408 }
Victoria Lease38389b62012-09-30 11:44:22 -0700409 }
410 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800411 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700412 }
413
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700414 private void onUidImportanceChanged(int uid, int importance) {
415 boolean foreground = isImportanceForeground(importance);
416 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
417 synchronized (mLock) {
418 for (Entry<String, ArrayList<UpdateRecord>> entry
gomo48f1a642017-11-10 20:35:46 -0800419 : mRecordsByProvider.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700420 String provider = entry.getKey();
421 for (UpdateRecord record : entry.getValue()) {
422 if (record.mReceiver.mIdentity.mUid == uid
gomo48f1a642017-11-10 20:35:46 -0800423 && record.mIsForegroundUid != foreground) {
424 if (D) {
425 Log.d(TAG, "request from uid " + uid + " is now "
426 + (foreground ? "foreground" : "background)"));
427 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700428 record.mIsForegroundUid = foreground;
429
430 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
431 affectedProviders.add(provider);
432 }
433 }
434 }
435 }
436 for (String provider : affectedProviders) {
437 applyRequirementsLocked(provider);
438 }
439
Wyatt Riley11cc7492018-01-17 08:48:27 -0800440 for (Entry<IBinder, Identity> entry : mGnssMeasurementsListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700441 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800442 if (D) {
443 Log.d(TAG, "gnss measurements listener from uid " + uid
444 + " is now " + (foreground ? "foreground" : "background)"));
445 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700446 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800447 mGnssMeasurementsProvider.addListener(
448 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700449 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800450 mGnssMeasurementsProvider.removeListener(
451 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700452 }
453 }
454 }
455
Wyatt Riley11cc7492018-01-17 08:48:27 -0800456 for (Entry<IBinder, Identity> entry : mGnssNavigationMessageListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700457 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800458 if (D) {
459 Log.d(TAG, "gnss navigation message listener from uid "
460 + uid + " is now "
461 + (foreground ? "foreground" : "background)"));
462 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700463 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800464 mGnssNavigationMessageProvider.addListener(
465 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700466 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800467 mGnssNavigationMessageProvider.removeListener(
468 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700469 }
470 }
471 }
472 }
473 }
474
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800475 private static boolean isImportanceForeground(int importance) {
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700476 return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800477 }
478
Amith Yamasanib27528d2014-06-05 15:02:10 -0700479 /**
destradaab9026982015-08-27 17:34:54 -0700480 * Provides a way for components held by the {@link LocationManagerService} to clean-up
481 * gracefully on system's shutdown.
482 *
483 * NOTES:
484 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
485 * support for components that do not wish to handle such event.
486 */
487 private void shutdownComponents() {
gomo48f1a642017-11-10 20:35:46 -0800488 if (D) Log.d(TAG, "Shutting down components...");
destradaab9026982015-08-27 17:34:54 -0700489
490 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
491 if (gpsProvider != null && gpsProvider.isEnabled()) {
492 gpsProvider.disable();
493 }
494
destradaa2e385072015-10-14 16:45:58 -0700495 // it is needed to check if FLP HW provider is supported before accessing the instance, this
496 // avoids an exception to be thrown by the singleton factory method
497 if (FlpHardwareProvider.isSupported()) {
498 FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaab9026982015-08-27 17:34:54 -0700499 flpHardwareProvider.cleanup();
500 }
501 }
502
503 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700504 * Makes a list of userids that are related to the current user. This is
505 * relevant when using managed profiles. Otherwise the list only contains
506 * the current user.
507 *
508 * @param currentUserId the current user, who might have an alter-ego.
509 */
510 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700511 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700512 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700513 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700514 }
515 }
516
517 /**
518 * Checks if the specified userId matches any of the current foreground
519 * users stored in mCurrentUserProfiles.
520 */
521 private boolean isCurrentProfile(int userId) {
522 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700523 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700524 }
525 }
526
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500527 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
528 PackageManager pm = mContext.getPackageManager();
529 String systemPackageName = mContext.getPackageName();
530 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
531
532 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
533 new Intent(FUSED_LOCATION_SERVICE_ACTION),
534 PackageManager.GET_META_DATA, mCurrentUserId);
535 for (ResolveInfo rInfo : rInfos) {
536 String packageName = rInfo.serviceInfo.packageName;
537
538 // Check that the signature is in the list of supported sigs. If it's not in
539 // this list the standard provider binding logic won't bind to it.
540 try {
541 PackageInfo pInfo;
542 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
543 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
544 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
545 ", but has wrong signature, ignoring");
546 continue;
547 }
548 } catch (NameNotFoundException e) {
549 Log.e(TAG, "missing package: " + packageName);
550 continue;
551 }
552
553 // Get the version info
554 if (rInfo.serviceInfo.metaData == null) {
555 Log.w(TAG, "Found fused provider without metadata: " + packageName);
556 continue;
557 }
558
559 int version = rInfo.serviceInfo.metaData.getInt(
560 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
561 if (version == 0) {
562 // This should be the fallback fused location provider.
563
564 // Make sure it's in the system partition.
565 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
566 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
567 continue;
568 }
569
570 // Check that the fallback is signed the same as the OS
571 // as a proxy for coreApp="true"
572 if (pm.checkSignatures(systemPackageName, packageName)
573 != PackageManager.SIGNATURE_MATCH) {
gomo48f1a642017-11-10 20:35:46 -0800574 if (D) {
575 Log.d(TAG, "Fallback candidate not signed the same as system: "
576 + packageName);
577 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500578 continue;
579 }
580
581 // Found a valid fallback.
582 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
583 return;
584 } else {
585 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
586 }
587 }
588
589 throw new IllegalStateException("Unable to find a fused location provider that is in the "
590 + "system partition with version 0 and signed with the platform certificate. "
591 + "Such a package is needed to provide a default fused location provider in the "
592 + "event that no other fused location provider has been installed or is currently "
593 + "available. For example, coreOnly boot mode when decrypting the data "
594 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
595 }
596
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700597 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700598 // create a passive location provider, which is always enabled
599 PassiveProvider passiveProvider = new PassiveProvider(this);
600 addProviderLocked(passiveProvider);
601 mEnabledProviders.add(passiveProvider.getName());
602 mPassiveProvider = passiveProvider;
603
Lifu Tang30f95a72016-01-07 23:20:38 -0800604 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700605 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800606 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700607 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800608 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Wyatt Rileycf879db2017-01-12 13:57:38 -0800609 mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
Siddharth Raybb608c82017-03-16 11:33:34 -0700610 mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800611 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
612 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
613 addProviderLocked(gnssProvider);
614 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800615 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
616 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800617 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700618 }
619
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700620 /*
621 Load package name(s) containing location provider support.
622 These packages can contain services implementing location providers:
623 Geocoder Provider, Network Location Provider, and
624 Fused Location Provider. They will each be searched for
625 service components implementing these providers.
626 The location framework also has support for installation
627 of new location providers at run-time. The new package does not
628 have to be explicitly listed here, however it must have a signature
629 that matches the signature of at least one package on this list.
630 */
631 Resources resources = mContext.getResources();
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800632 ArrayList<String> providerPackageNames = new ArrayList<>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500633 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700634 com.android.internal.R.array.config_locationProviderPackageNames);
gomo48f1a642017-11-10 20:35:46 -0800635 if (D) {
636 Log.d(TAG, "certificates for location providers pulled from: " +
637 Arrays.toString(pkgs));
638 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500639 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
640
641 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700642
643 // bind to network provider
644 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
645 mContext,
646 LocationManager.NETWORK_PROVIDER,
647 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700648 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
649 com.android.internal.R.string.config_networkLocationProviderPackageName,
650 com.android.internal.R.array.config_locationProviderPackageNames,
651 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700652 if (networkProvider != null) {
653 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
654 mProxyProviders.add(networkProvider);
655 addProviderLocked(networkProvider);
656 } else {
gomo48f1a642017-11-10 20:35:46 -0800657 Slog.w(TAG, "no network location provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700658 }
659
660 // bind to fused provider
661 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
662 mContext,
663 LocationManager.FUSED_PROVIDER,
664 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700665 com.android.internal.R.bool.config_enableFusedLocationOverlay,
666 com.android.internal.R.string.config_fusedLocationProviderPackageName,
667 com.android.internal.R.array.config_locationProviderPackageNames,
668 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700669 if (fusedLocationProvider != null) {
670 addProviderLocked(fusedLocationProvider);
671 mProxyProviders.add(fusedLocationProvider);
672 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700673 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700674 } else {
675 Slog.e(TAG, "no fused location provider found",
676 new IllegalStateException("Location service needs a fused location provider"));
677 }
678
679 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700680 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
681 com.android.internal.R.bool.config_enableGeocoderOverlay,
682 com.android.internal.R.string.config_geocoderProviderPackageName,
683 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800684 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700685 if (mGeocodeProvider == null) {
gomo48f1a642017-11-10 20:35:46 -0800686 Slog.e(TAG, "no geocoder provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700687 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700688
destradaaa4fa3b52014-07-09 10:46:39 -0700689 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700690 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
691 // exception, so make sure we only do that when supported
692 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700693 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700694 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700695 FusedProxy fusedProxy = FusedProxy.createAndBind(
696 mContext,
697 mLocationHandler,
698 flpHardwareProvider.getLocationHardware(),
699 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
700 com.android.internal.R.string.config_hardwareFlpPackageName,
701 com.android.internal.R.array.config_locationProviderPackageNames);
702 if (fusedProxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700703 Slog.d(TAG, "Unable to bind FusedProxy.");
destradaaf9a274c2014-07-25 15:11:56 -0700704 }
destradaacfbdcd22014-04-30 11:29:11 -0700705 } else {
destradaabeea4422014-07-30 18:17:21 -0700706 flpHardwareProvider = null;
destradaa6b4893a2016-05-03 15:33:43 -0700707 Slog.d(TAG, "FLP HAL not supported");
destradaaf9a274c2014-07-25 15:11:56 -0700708 }
709
710 // bind to geofence provider
711 GeofenceProxy provider = GeofenceProxy.createAndBind(
gomo48f1a642017-11-10 20:35:46 -0800712 mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
destradaaf9a274c2014-07-25 15:11:56 -0700713 com.android.internal.R.string.config_geofenceProviderPackageName,
714 com.android.internal.R.array.config_locationProviderPackageNames,
715 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700716 mGpsGeofenceProxy,
destradaabeea4422014-07-30 18:17:21 -0700717 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700718 if (provider == null) {
gomo48f1a642017-11-10 20:35:46 -0800719 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700720 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900721
destradaa6e2fe752015-06-23 17:25:53 -0700722 // bind to hardware activity recognition
723 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
724 ActivityRecognitionHardware activityRecognitionHardware = null;
725 if (activityRecognitionHardwareIsSupported) {
726 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700727 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700728 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700729 }
destradaa6e2fe752015-06-23 17:25:53 -0700730 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
731 mContext,
732 mLocationHandler,
733 activityRecognitionHardwareIsSupported,
734 activityRecognitionHardware,
735 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
736 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
737 com.android.internal.R.array.config_locationProviderPackageNames);
738 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700739 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700740 }
destradaaa4fa3b52014-07-09 10:46:39 -0700741
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900742 String[] testProviderStrings = resources.getStringArray(
743 com.android.internal.R.array.config_testLocationProviders);
744 for (String testProviderString : testProviderStrings) {
745 String fragments[] = testProviderString.split(",");
746 String name = fragments[0].trim();
747 if (mProvidersByName.get(name) != null) {
748 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
749 }
750 ProviderProperties properties = new ProviderProperties(
751 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
752 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
753 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
754 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
755 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
756 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
757 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
758 Integer.parseInt(fragments[8]) /* powerRequirement */,
759 Integer.parseInt(fragments[9]) /* accuracy */);
760 addTestProviderLocked(name, properties);
761 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700762 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700763
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800764 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700765 * Called when the device's active user changes.
gomo48f1a642017-11-10 20:35:46 -0800766 *
Victoria Lease38389b62012-09-30 11:44:22 -0700767 * @param userId the new active user's UserId
768 */
769 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800770 if (mCurrentUserId == userId) {
771 return;
772 }
Victoria Lease83762d22012-10-03 13:51:17 -0700773 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800774 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700775 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700776 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700777 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700778 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700779 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700780 }
Victoria Lease38389b62012-09-30 11:44:22 -0700781 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700782 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700783 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700784 }
785 }
786
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800787 private static final class Identity {
788 final int mUid;
789 final int mPid;
790 final String mPackageName;
791
792 Identity(int uid, int pid, String packageName) {
793 mUid = uid;
794 mPid = pid;
795 mPackageName = packageName;
796 }
797 }
798
Victoria Lease38389b62012-09-30 11:44:22 -0700799 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800800 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
801 * location updates.
802 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700803 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800804 final Identity mIdentity;
Victoria Lease37425c32012-10-16 16:08:48 -0700805 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700806
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800807 final ILocationListener mListener;
808 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700809 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700810 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700812
gomo48f1a642017-11-10 20:35:46 -0800813 final HashMap<String, UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700814
David Christie0b837452013-07-29 16:02:13 -0700815 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700816 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700817 // True if app ops has started monitoring this receiver for high power (gps) locations.
818 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700819 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700820 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700822 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700823 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700826 if (listener != null) {
827 mKey = listener.asBinder();
828 } else {
829 mKey = intent;
830 }
Victoria Lease37425c32012-10-16 16:08:48 -0700831 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800832 mIdentity = new Identity(uid, pid, packageName);
Narayan Kamath32684dd2018-01-08 17:32:51 +0000833 if (workSource != null && workSource.isEmpty()) {
David Christie82edc9b2013-07-19 11:31:42 -0700834 workSource = null;
835 }
836 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700837 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700838
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700839 updateMonitoring(true);
840
Victoria Lease0aa28602013-05-29 15:28:26 -0700841 // construct/configure wakelock
842 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700843 if (workSource == null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800844 workSource = new WorkSource(mIdentity.mUid, mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -0700845 }
846 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800847 }
848
849 @Override
850 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800851 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800852 }
853
854 @Override
855 public int hashCode() {
856 return mKey.hashCode();
857 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400858
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800859 @Override
860 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700861 StringBuilder s = new StringBuilder();
862 s.append("Reciever[");
863 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700865 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700867 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700869 for (String p : mUpdateRecords.keySet()) {
870 s.append(" ").append(mUpdateRecords.get(p).toString());
871 }
872 s.append("]");
873 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 }
875
David Christie15b31912013-08-13 15:54:32 -0700876 /**
877 * Update AppOp monitoring for this receiver.
878 *
879 * @param allow If true receiver is currently active, if false it's been removed.
880 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700881 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700882 if (mHideFromAppOps) {
883 return;
884 }
885
David Christie15b31912013-08-13 15:54:32 -0700886 boolean requestingLocation = false;
887 boolean requestingHighPowerLocation = false;
888 if (allow) {
889 // See if receiver has any enabled update records. Also note if any update records
890 // are high power (has a high power provider with an interval under a threshold).
891 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
892 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
893 requestingLocation = true;
894 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800895 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700896 ProviderProperties properties = locationProvider != null
897 ? locationProvider.getProperties() : null;
898 if (properties != null
899 && properties.mPowerRequirement == Criteria.POWER_HIGH
900 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
901 requestingHighPowerLocation = true;
902 break;
903 }
904 }
905 }
906 }
907
David Christie0b837452013-07-29 16:02:13 -0700908 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700909 mOpMonitoring = updateMonitoring(
910 requestingLocation,
911 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700912 AppOpsManager.OP_MONITOR_LOCATION);
913
914 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700915 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700916 mOpHighPowerMonitoring = updateMonitoring(
917 requestingHighPowerLocation,
918 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700919 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700920 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700921 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700922 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
923 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
924 }
David Christie0b837452013-07-29 16:02:13 -0700925 }
926
927 /**
928 * Update AppOps monitoring for a single location request and op type.
929 *
gomo48f1a642017-11-10 20:35:46 -0800930 * @param allowMonitoring True if monitoring is allowed for this request/op.
David Christie0b837452013-07-29 16:02:13 -0700931 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
gomo48f1a642017-11-10 20:35:46 -0800932 * @param op AppOps code for the op to update.
David Christie0b837452013-07-29 16:02:13 -0700933 * @return True if monitoring is on for this request/op after updating.
934 */
935 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
936 int op) {
937 if (!currentlyMonitoring) {
938 if (allowMonitoring) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800939 return mAppOps.startOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700940 == AppOpsManager.MODE_ALLOWED;
941 }
942 } else {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800943 if (!allowMonitoring
944 || mAppOps.checkOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700945 != AppOpsManager.MODE_ALLOWED) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800946 mAppOps.finishOp(op, mIdentity.mUid, mIdentity.mPackageName);
David Christie0b837452013-07-29 16:02:13 -0700947 return false;
948 }
949 }
950
951 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700952 }
953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 public boolean isListener() {
955 return mListener != null;
956 }
957
958 public boolean isPendingIntent() {
959 return mPendingIntent != null;
960 }
961
962 public ILocationListener getListener() {
963 if (mListener != null) {
964 return mListener;
965 }
966 throw new IllegalStateException("Request for non-existent listener");
967 }
968
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
970 if (mListener != null) {
971 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700972 synchronized (this) {
973 // synchronize to ensure incrementPendingBroadcastsLocked()
974 // is called before decrementPendingBroadcasts()
975 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700976 // call this after broadcasting so we do not increment
977 // if we throw an exeption.
978 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 } catch (RemoteException e) {
981 return false;
982 }
983 } else {
984 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800985 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
987 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700988 synchronized (this) {
989 // synchronize to ensure incrementPendingBroadcastsLocked()
990 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700991 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700992 getResolutionPermission(mAllowedResolutionLevel));
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,
Victoria Lease37425c32012-10-16 16:08:48 -07001027 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001028 // call this after broadcasting so we do not increment
1029 // if we throw an exeption.
1030 incrementPendingBroadcastsLocked();
1031 }
1032 } catch (PendingIntent.CanceledException e) {
1033 return false;
1034 }
1035 }
1036 return true;
1037 }
1038
1039 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001040 // First update AppOp monitoring.
1041 // An app may get/lose location access as providers are enabled/disabled.
1042 updateMonitoring(true);
1043
Mike Lockwood48f17512009-04-23 09:12:08 -07001044 if (mListener != null) {
1045 try {
1046 synchronized (this) {
1047 // synchronize to ensure incrementPendingBroadcastsLocked()
1048 // is called before decrementPendingBroadcasts()
1049 if (enabled) {
1050 mListener.onProviderEnabled(provider);
1051 } else {
1052 mListener.onProviderDisabled(provider);
1053 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001054 // call this after broadcasting so we do not increment
1055 // if we throw an exeption.
1056 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001057 }
1058 } catch (RemoteException e) {
1059 return false;
1060 }
1061 } else {
1062 Intent providerIntent = new Intent();
1063 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1064 try {
1065 synchronized (this) {
1066 // synchronize to ensure incrementPendingBroadcastsLocked()
1067 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001068 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001069 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001070 // call this after broadcasting so we do not increment
1071 // if we throw an exeption.
1072 incrementPendingBroadcastsLocked();
1073 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 } catch (PendingIntent.CanceledException e) {
1075 return false;
1076 }
1077 }
1078 return true;
1079 }
1080
Nick Pellyf1be6862012-05-15 10:53:42 -07001081 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001083 if (D) Log.d(TAG, "Location listener died");
1084
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001085 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086 removeUpdatesLocked(this);
1087 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001088 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001089 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001090 }
1091 }
1092
Nick Pellye0fd6932012-07-11 10:26:13 -07001093 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001094 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1095 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001096 synchronized (this) {
1097 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001098 }
1099 }
1100
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001101 // this must be called while synchronized by caller in a synchronized block
1102 // containing the sending of the broadcaset
1103 private void incrementPendingBroadcastsLocked() {
1104 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001105 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001106 }
1107 }
1108
1109 private void decrementPendingBroadcastsLocked() {
1110 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001111 if (mWakeLock.isHeld()) {
1112 mWakeLock.release();
1113 }
1114 }
1115 }
1116
1117 public void clearPendingBroadcastsLocked() {
1118 if (mPendingBroadcasts > 0) {
1119 mPendingBroadcasts = 0;
1120 if (mWakeLock.isHeld()) {
1121 mWakeLock.release();
1122 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001123 }
1124 }
1125 }
1126
Nick Pellye0fd6932012-07-11 10:26:13 -07001127 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001128 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001129 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001130 //the receiver list if it is not found. If it is not found then the
1131 //LocationListener was removed when it had a pending broadcast and should
1132 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001133 synchronized (mLock) {
1134 IBinder binder = listener.asBinder();
1135 Receiver receiver = mReceivers.get(binder);
1136 if (receiver != null) {
1137 synchronized (receiver) {
1138 // so wakelock calls will succeed
1139 long identity = Binder.clearCallingIdentity();
1140 receiver.decrementPendingBroadcastsLocked();
1141 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001142 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001143 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145 }
1146
Lifu Tang82f893d2016-01-21 18:15:33 -08001147 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001148 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001149 */
1150 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001151 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001152 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001153 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001154 } else {
1155 return 0;
1156 }
1157 }
1158
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001159
1160 /**
1161 * Returns the model name of the GNSS hardware.
1162 */
1163 @Override
1164 public String getGnssHardwareModelName() {
1165 if (mGnssSystemInfoProvider != null) {
1166 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1167 } else {
1168 return LocationManager.GNSS_HARDWARE_MODEL_NAME_UNKNOWN;
1169 }
1170 }
1171
Wyatt Rileycf879db2017-01-12 13:57:38 -08001172 /**
1173 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1174 * (try to) access GNSS information at this layer.
1175 */
1176 private boolean hasGnssPermissions(String packageName) {
1177 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1178 checkResolutionLevelIsSufficientForProviderUse(
1179 allowedResolutionLevel,
1180 LocationManager.GPS_PROVIDER);
1181
1182 int pid = Binder.getCallingPid();
1183 int uid = Binder.getCallingUid();
1184 long identity = Binder.clearCallingIdentity();
1185 boolean hasLocationAccess;
1186 try {
1187 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1188 } finally {
1189 Binder.restoreCallingIdentity(identity);
1190 }
1191
1192 return hasLocationAccess;
1193 }
1194
1195 /**
1196 * Returns the GNSS batching size, if available.
1197 */
1198 @Override
1199 public int getGnssBatchSize(String packageName) {
1200 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1201 "Location Hardware permission not granted to access hardware batching");
1202
1203 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
1204 return mGnssBatchingProvider.getSize();
1205 } else {
1206 return 0;
1207 }
1208 }
1209
1210 /**
1211 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1212 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1213 */
1214 @Override
1215 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1216 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1217 "Location Hardware permission not granted to access hardware batching");
1218
1219 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1220 return false;
1221 }
1222
1223 mGnssBatchingCallback = callback;
1224 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1225 try {
1226 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1227 } catch (RemoteException e) {
1228 // if the remote process registering the listener is already dead, just swallow the
1229 // exception and return
1230 Log.e(TAG, "Remote listener already died.", e);
1231 return false;
1232 }
1233
1234 return true;
1235 }
1236
1237 private class LinkedCallback implements IBinder.DeathRecipient {
1238 private final IBatchedLocationCallback mCallback;
1239
1240 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1241 mCallback = callback;
1242 }
1243
1244 @NonNull
1245 public IBatchedLocationCallback getUnderlyingListener() {
1246 return mCallback;
1247 }
1248
1249 @Override
1250 public void binderDied() {
1251 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1252 stopGnssBatch();
1253 removeGnssBatchingCallback();
1254 }
1255 }
1256
1257 /**
1258 * Removes callback for GNSS batching
1259 */
1260 @Override
1261 public void removeGnssBatchingCallback() {
1262 try {
1263 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1264 0 /* flags */);
1265 } catch (NoSuchElementException e) {
1266 // if the death callback isn't connected (it should be...), log error, swallow the
1267 // exception and return
1268 Log.e(TAG, "Couldn't unlink death callback.", e);
1269 }
1270 mGnssBatchingCallback = null;
1271 mGnssBatchingDeathCallback = null;
1272 }
1273
1274
1275 /**
1276 * Starts GNSS batching, if available.
1277 */
1278 @Override
1279 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1280 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1281 "Location Hardware permission not granted to access hardware batching");
1282
1283 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1284 return false;
1285 }
1286
1287 if (mGnssBatchingInProgress) {
1288 // Current design does not expect multiple starts to be called repeatedly
1289 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1290 // Try to clean up anyway, and continue
1291 stopGnssBatch();
1292 }
1293
1294 mGnssBatchingInProgress = true;
1295 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1296 }
1297
1298 /**
1299 * Flushes a GNSS batch in progress
1300 */
1301 @Override
1302 public void flushGnssBatch(String packageName) {
1303 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1304 "Location Hardware permission not granted to access hardware batching");
1305
1306 if (!hasGnssPermissions(packageName)) {
1307 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1308 return;
1309 }
1310
1311 if (!mGnssBatchingInProgress) {
1312 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1313 }
1314
1315 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001316 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001317 }
1318 }
1319
1320 /**
1321 * Stops GNSS batching
1322 */
1323 @Override
1324 public boolean stopGnssBatch() {
1325 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1326 "Location Hardware permission not granted to access hardware batching");
1327
1328 if (mGnssBatchingProvider != null) {
1329 mGnssBatchingInProgress = false;
1330 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001331 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001332 return false;
1333 }
1334 }
1335
1336 @Override
1337 public void reportLocationBatch(List<Location> locations) {
1338 checkCallerIsProvider();
1339
1340 // Currently used only for GNSS locations - update permissions check if changed
1341 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1342 if (mGnssBatchingCallback == null) {
1343 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1344 return;
1345 }
1346 try {
1347 mGnssBatchingCallback.onLocationBatch(locations);
1348 } catch (RemoteException e) {
1349 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1350 }
1351 } else {
1352 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1353 }
1354 }
1355
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001356 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001357 mProviders.add(provider);
1358 mProvidersByName.put(provider.getName(), provider);
1359 }
1360
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001361 private void removeProviderLocked(LocationProviderInterface provider) {
1362 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001363 mProviders.remove(provider);
1364 mProvidersByName.remove(provider.getName());
1365 }
1366
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001367 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001368 * Returns "true" if access to the specified location provider is allowed by the current
1369 * user's settings. Access to all location providers is forbidden to non-location-provider
1370 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001371 *
1372 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001373 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001374 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 if (mEnabledProviders.contains(provider)) {
1376 return true;
1377 }
1378 if (mDisabledProviders.contains(provider)) {
1379 return false;
1380 }
Maggieaa080f92018-01-04 15:35:11 -08001381 return isLocationProviderEnabledForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 }
1383
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001384 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001385 * Returns "true" if access to the specified location provider is allowed by the specified
1386 * user's settings. Access to all location providers is forbidden to non-location-provider
1387 * processes belonging to background users.
1388 *
1389 * @param provider the name of the location provider
gomo48f1a642017-11-10 20:35:46 -08001390 * @param uid the requestor's UID
Victoria Lease09eeaec2013-02-05 11:34:13 -08001391 */
1392 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001393 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001394 return false;
1395 }
1396 return isAllowedByCurrentUserSettingsLocked(provider);
1397 }
1398
1399 /**
Maggieaa080f92018-01-04 15:35:11 -08001400 * 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 isAllowedByUserSettingsLockedForUser(
1409 String provider, int uid, int userId) {
1410 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
1411 return false;
1412 }
1413 return isLocationProviderEnabledForUser(provider, userId);
1414 }
1415
1416 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001417 * Returns the permission string associated with the specified resolution level.
1418 *
1419 * @param resolutionLevel the resolution level
1420 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001421 */
Victoria Lease37425c32012-10-16 16:08:48 -07001422 private String getResolutionPermission(int resolutionLevel) {
1423 switch (resolutionLevel) {
1424 case RESOLUTION_LEVEL_FINE:
1425 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1426 case RESOLUTION_LEVEL_COARSE:
1427 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1428 default:
1429 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001431 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001432
Victoria Leaseda479c52012-10-15 15:24:16 -07001433 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001434 * Returns the resolution level allowed to the given PID/UID pair.
1435 *
1436 * @param pid the PID
1437 * @param uid the UID
1438 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001439 */
Victoria Lease37425c32012-10-16 16:08:48 -07001440 private int getAllowedResolutionLevel(int pid, int uid) {
1441 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001442 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001443 return RESOLUTION_LEVEL_FINE;
1444 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001445 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001446 return RESOLUTION_LEVEL_COARSE;
1447 } else {
1448 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001449 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001450 }
1451
1452 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001453 * Returns the resolution level allowed to the caller
1454 *
1455 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001456 */
Victoria Lease37425c32012-10-16 16:08:48 -07001457 private int getCallerAllowedResolutionLevel() {
1458 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1459 }
1460
1461 /**
1462 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1463 *
1464 * @param allowedResolutionLevel resolution level allowed to caller
1465 */
1466 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1467 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001468 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1469 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001470 }
1471
Victoria Lease37425c32012-10-16 16:08:48 -07001472 /**
1473 * Return the minimum resolution level required to use the specified location provider.
1474 *
1475 * @param provider the name of the location provider
1476 * @return minimum resolution level required for provider
1477 */
1478 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001479 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1480 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1481 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001482 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001483 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1484 LocationManager.FUSED_PROVIDER.equals(provider)) {
1485 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001486 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001487 } else {
1488 // mock providers
1489 LocationProviderInterface lp = mMockProviders.get(provider);
1490 if (lp != null) {
1491 ProviderProperties properties = lp.getProperties();
1492 if (properties != null) {
1493 if (properties.mRequiresSatellite) {
1494 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001495 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001496 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1497 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001498 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001499 }
1500 }
1501 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001502 }
Victoria Lease37425c32012-10-16 16:08:48 -07001503 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001504 }
1505
Victoria Lease37425c32012-10-16 16:08:48 -07001506 /**
1507 * Throw SecurityException if specified resolution level is insufficient to use the named
1508 * location provider.
1509 *
1510 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001511 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001512 */
1513 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1514 String providerName) {
1515 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1516 if (allowedResolutionLevel < requiredResolutionLevel) {
1517 switch (requiredResolutionLevel) {
1518 case RESOLUTION_LEVEL_FINE:
1519 throw new SecurityException("\"" + providerName + "\" location provider " +
1520 "requires ACCESS_FINE_LOCATION permission.");
1521 case RESOLUTION_LEVEL_COARSE:
1522 throw new SecurityException("\"" + providerName + "\" location provider " +
1523 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1524 default:
1525 throw new SecurityException("Insufficient permission for \"" + providerName +
1526 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001527 }
1528 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001529 }
1530
David Christie82edc9b2013-07-19 11:31:42 -07001531 /**
1532 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1533 * for battery).
1534 */
David Christie40e57822013-07-30 11:36:48 -07001535 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001536 mContext.enforceCallingOrSelfPermission(
1537 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1538 }
1539
David Christie40e57822013-07-30 11:36:48 -07001540 private void checkUpdateAppOpsAllowed() {
1541 mContext.enforceCallingOrSelfPermission(
1542 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1543 }
1544
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001545 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001546 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1547 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001548 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001549 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001550 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001551 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001552 }
1553 return -1;
1554 }
1555
David Christieb870dbf2015-06-22 12:42:53 -07001556 boolean reportLocationAccessNoThrow(
1557 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001558 int op = resolutionLevelToOp(allowedResolutionLevel);
1559 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001560 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1561 return false;
1562 }
1563 }
David Christieb870dbf2015-06-22 12:42:53 -07001564
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001565 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001566 }
1567
David Christieb870dbf2015-06-22 12:42:53 -07001568 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001569 int op = resolutionLevelToOp(allowedResolutionLevel);
1570 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001571 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1572 return false;
1573 }
1574 }
David Christieb870dbf2015-06-22 12:42:53 -07001575
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001576 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001577 }
1578
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001579 /**
Maggie91e630c2018-01-24 17:31:46 -08001580 * Returns all providers by name, including passive and the ones that are not permitted to
1581 * be accessed by the calling activity or are currently disabled, but excluding fused.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001582 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001583 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 public List<String> getAllProviders() {
Maggie91e630c2018-01-24 17:31:46 -08001585 ArrayList<String> out;
1586 synchronized (mLock) {
1587 out = new ArrayList<>(mProviders.size());
1588 for (LocationProviderInterface provider : mProviders) {
1589 String name = provider.getName();
1590 if (LocationManager.FUSED_PROVIDER.equals(name)) {
1591 continue;
1592 }
1593 out.add(name);
1594 }
1595 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001596 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 return out;
1598 }
1599
Mike Lockwood03ca2162010-04-01 08:10:09 -07001600 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001601 * Return all providers by name, that match criteria and are optionally
1602 * enabled.
1603 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001604 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001605 @Override
1606 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001607 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001608 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001609 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001610 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001611 try {
1612 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001613 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001614 for (LocationProviderInterface provider : mProviders) {
1615 String name = provider.getName();
1616 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001617 continue;
1618 }
Victoria Lease37425c32012-10-16 16:08:48 -07001619 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001620 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001621 continue;
1622 }
1623 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1624 name, provider.getProperties(), criteria)) {
1625 continue;
1626 }
1627 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001628 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001629 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001630 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001631 } finally {
1632 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001633 }
1634
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001635 if (D) Log.d(TAG, "getProviders()=" + out);
1636 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001637 }
1638
1639 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001640 * Return the name of the best provider given a Criteria object.
1641 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001642 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001643 * has been deprecated as well. So this method now uses
1644 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001645 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001646 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001647 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001648 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001649
1650 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001651 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001652 result = pickBest(providers);
1653 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1654 return result;
1655 }
1656 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001657 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001658 result = pickBest(providers);
1659 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1660 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001661 }
1662
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001663 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001664 return null;
1665 }
1666
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001667 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001668 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001669 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001670 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1671 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001672 } else {
1673 return providers.get(0);
1674 }
1675 }
1676
Nick Pellye0fd6932012-07-11 10:26:13 -07001677 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001678 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1679 LocationProviderInterface p = mProvidersByName.get(provider);
1680 if (p == null) {
1681 throw new IllegalArgumentException("provider=" + provider);
1682 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001683
1684 boolean result = LocationProvider.propertiesMeetCriteria(
1685 p.getName(), p.getProperties(), criteria);
1686 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1687 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001688 }
1689
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001691 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001692 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001693 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 boolean isEnabled = p.isEnabled();
1695 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001696 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001697 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001698 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001699 // If any provider has been disabled, clear all last locations for all providers.
1700 // This is to be on the safe side in case a provider has location derived from
1701 // this disabled provider.
1702 mLastLocation.clear();
1703 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001704 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001706 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001707 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001709 }
1710 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001711 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1712 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001713 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1714 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716 }
1717
Amith Yamasanib27528d2014-06-05 15:02:10 -07001718 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001719 int listeners = 0;
1720
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001721 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001722 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723
1724 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1727 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001728 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001729 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001730 // Sends a notification message to the receiver
1731 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1732 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001733 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001734 }
1735 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001737 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740 }
1741
1742 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001743 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 removeUpdatesLocked(deadReceivers.get(i));
1745 }
1746 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001747
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 if (enabled) {
1749 p.enable();
1750 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001751 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
1753 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001756 }
1757
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001758 private void applyRequirementsLocked(String provider) {
1759 LocationProviderInterface p = mProvidersByName.get(provider);
1760 if (p == null) return;
1761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001763 WorkSource worksource = new WorkSource();
1764 ProviderRequest providerRequest = new ProviderRequest();
1765
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001766 ContentResolver resolver = mContext.getContentResolver();
1767 long backgroundThrottleInterval = Settings.Global.getLong(
1768 resolver,
1769 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1770 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001771 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001772
gomo48f1a642017-11-10 20:35:46 -08001773 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001775 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001776 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001777 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001778 record.mReceiver.mIdentity.mPid,
1779 record.mReceiver.mIdentity.mUid,
1780 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001781 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001782 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001783 long interval = locationRequest.getInterval();
1784
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001785 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001786 if (!record.mIsForegroundUid) {
1787 interval = Math.max(interval, backgroundThrottleInterval);
1788 }
1789 if (interval != locationRequest.getInterval()) {
1790 locationRequest = new LocationRequest(locationRequest);
1791 locationRequest.setInterval(interval);
1792 }
1793 }
1794
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001795 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001796 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001797 if (!locationRequest.isLowPowerMode()) {
1798 providerRequest.lowPowerMode = false;
1799 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001800 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001801 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001802 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001803 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001804 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001805 }
1806 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001807
1808 if (providerRequest.reportLocation) {
1809 // calculate who to blame for power
1810 // This is somewhat arbitrary. We pick a threshold interval
1811 // that is slightly higher that the minimum interval, and
1812 // spread the blame across all applications with a request
1813 // under that threshold.
1814 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1815 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001816 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001817 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001818
1819 // Don't assign battery blame for update records whose
1820 // client has no permission to receive location data.
1821 if (!providerRequest.locationRequests.contains(locationRequest)) {
1822 continue;
1823 }
1824
Victoria Leaseb711d572012-10-02 13:14:11 -07001825 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001826 if (record.mReceiver.mWorkSource != null
Narayan Kamath32684dd2018-01-08 17:32:51 +00001827 && isValidWorkSource(record.mReceiver.mWorkSource)) {
David Christie82edc9b2013-07-19 11:31:42 -07001828 worksource.add(record.mReceiver.mWorkSource);
1829 } else {
Narayan Kamath32684dd2018-01-08 17:32:51 +00001830 // Assign blame to caller if there's no WorkSource associated with
1831 // the request or if it's invalid.
David Christie82edc9b2013-07-19 11:31:42 -07001832 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001833 record.mReceiver.mIdentity.mUid,
1834 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001835 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001836 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001837 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
1840 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001841
1842 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1843 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
1845
Narayan Kamath32684dd2018-01-08 17:32:51 +00001846 /**
1847 * Whether a given {@code WorkSource} associated with a Location request is valid.
1848 */
1849 private static boolean isValidWorkSource(WorkSource workSource) {
1850 if (workSource.size() > 0) {
1851 // If the WorkSource has one or more non-chained UIDs, make sure they're accompanied
1852 // by tags.
1853 return workSource.getName(0) != null;
1854 } else {
1855 // For now, make sure callers have supplied an attribution tag for use with
1856 // AppOpsManager. This might be relaxed in the future.
1857 final ArrayList<WorkChain> workChains = workSource.getWorkChains();
1858 return workChains != null && !workChains.isEmpty() &&
1859 workChains.get(0).getAttributionTag() != null;
1860 }
1861 }
1862
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001863 @Override
1864 public String[] getBackgroundThrottlingWhitelist() {
1865 synchronized (mLock) {
1866 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001867 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001868 }
1869 }
1870
1871 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001872 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001873 mContext.getContentResolver(),
1874 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001875 if (setting == null) {
1876 setting = "";
1877 }
1878
1879 mBackgroundThrottlePackageWhitelist.clear();
1880 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001881 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001882 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001883 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001884 }
1885
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001886 private boolean isThrottlingExemptLocked(Identity identity) {
1887 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001888 return true;
1889 }
1890
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001891 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001892 return true;
1893 }
1894
1895 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001896 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001897 return true;
1898 }
1899 }
1900
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001901 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001902 }
1903
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 private class UpdateRecord {
1905 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001906 final LocationRequest mRealRequest; // original request from client
1907 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001909 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001910 Location mLastFixBroadcast;
1911 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912
1913 /**
1914 * Note: must be constructed with lock held.
1915 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001916 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001918 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001919 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001921 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001922 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923
1924 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1925 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001926 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 mRecordsByProvider.put(provider, records);
1928 }
1929 if (!records.contains(this)) {
1930 records.add(this);
1931 }
David Christie2ff96af2014-01-30 16:09:37 -08001932
1933 // Update statistics for historical location requests by package/provider
1934 mRequestStatistics.startRequesting(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001935 mReceiver.mIdentity.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
1937
1938 /**
David Christie2ff96af2014-01-30 16:09:37 -08001939 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001941 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001942 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001943
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001944 // remove from mRecordsByProvider
1945 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1946 if (globalRecords != null) {
1947 globalRecords.remove(this);
1948 }
1949
1950 if (!removeReceiver) return; // the caller will handle the rest
1951
1952 // remove from Receiver#mUpdateRecords
1953 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1954 if (receiverRecords != null) {
1955 receiverRecords.remove(this.mProvider);
1956
1957 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001958 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001959 removeUpdatesLocked(mReceiver);
1960 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001961 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 }
1963
1964 @Override
1965 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001966 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001967 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1968 : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001969 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001970 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001971 }
1972
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001973 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001974 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001975 IBinder binder = listener.asBinder();
1976 Receiver receiver = mReceivers.get(binder);
1977 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001978 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1979 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001980 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001981 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001982 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001983 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001984 return null;
1985 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001986 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001987 }
1988 return receiver;
1989 }
1990
David Christie82edc9b2013-07-19 11:31:42 -07001991 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001992 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001993 Receiver receiver = mReceivers.get(intent);
1994 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001995 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1996 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001997 mReceivers.put(intent, receiver);
1998 }
1999 return receiver;
2000 }
2001
Victoria Lease37425c32012-10-16 16:08:48 -07002002 /**
2003 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
2004 * and consistency requirements.
2005 *
2006 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07002007 * @return a version of request that meets the given resolution and consistency requirements
2008 * @hide
2009 */
gomo48f1a642017-11-10 20:35:46 -08002010 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
2011 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07002012 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08002013 if (!callerHasLocationHardwarePermission) {
2014 // allow setting low power mode only for callers with location hardware permission
2015 sanitizedRequest.setLowPowerMode(false);
2016 }
Victoria Lease37425c32012-10-16 16:08:48 -07002017 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
2018 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002019 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07002020 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07002021 break;
2022 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07002023 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07002024 break;
2025 }
2026 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07002027 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2028 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002029 }
Victoria Lease37425c32012-10-16 16:08:48 -07002030 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2031 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002032 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002033 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002034 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002035 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002036 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002037 }
Victoria Lease37425c32012-10-16 16:08:48 -07002038 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002039 }
2040
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002041 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002042 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002043 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002044 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002045 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002046 String[] packages = mPackageManager.getPackagesForUid(uid);
2047 if (packages == null) {
2048 throw new SecurityException("invalid UID " + uid);
2049 }
2050 for (String pkg : packages) {
2051 if (packageName.equals(pkg)) return;
2052 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002053 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002054 }
2055
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002056 private void checkPendingIntent(PendingIntent intent) {
2057 if (intent == null) {
2058 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002059 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002060 }
2061
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002062 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002063 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002064 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002065 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002066 } else if (intent != null && listener != null) {
2067 throw new IllegalArgumentException("cannot register both listener and intent");
2068 } else if (intent != null) {
2069 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002070 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002071 } else {
David Christie40e57822013-07-30 11:36:48 -07002072 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002073 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002074 }
2075
Nick Pellye0fd6932012-07-11 10:26:13 -07002076 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002077 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2078 PendingIntent intent, String packageName) {
2079 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2080 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002081 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2082 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2083 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002084 WorkSource workSource = request.getWorkSource();
Narayan Kamath32684dd2018-01-08 17:32:51 +00002085 if (workSource != null && !workSource.isEmpty()) {
David Christie40e57822013-07-30 11:36:48 -07002086 checkDeviceStatsAllowed();
2087 }
2088 boolean hideFromAppOps = request.getHideFromAppOps();
2089 if (hideFromAppOps) {
2090 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002091 }
gomo48f1a642017-11-10 20:35:46 -08002092 boolean callerHasLocationHardwarePermission =
2093 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002094 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002095 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2096 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002098 final int pid = Binder.getCallingPid();
2099 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002100 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002101 long identity = Binder.clearCallingIdentity();
2102 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002103 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2104 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002105 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002106
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002107 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002108 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002109 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002110 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002111 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002112 } finally {
2113 Binder.restoreCallingIdentity(identity);
2114 }
2115 }
2116
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002117 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2118 int pid, int uid, String packageName) {
2119 // Figure out the provider. Either its explicitly request (legacy use cases), or
2120 // use the fused provider
2121 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2122 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002123 if (name == null) {
2124 throw new IllegalArgumentException("provider name must not be null");
2125 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002126
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002127 LocationProviderInterface provider = mProvidersByName.get(name);
2128 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002129 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002130 }
2131
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002132 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002133 if (D) {
2134 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2135 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2136 + (record.mIsForegroundUid ? "foreground" : "background")
2137 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002138 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002139 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002140
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002141 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2142 if (oldRecord != null) {
2143 oldRecord.disposeLocked(false);
2144 }
2145
Victoria Lease09eeaec2013-02-05 11:34:13 -08002146 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002147 if (isProviderEnabled) {
2148 applyRequirementsLocked(name);
2149 } else {
2150 // Notify the listener that updates are currently disabled
2151 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 }
David Christie0b837452013-07-29 16:02:13 -07002153 // Update the monitoring here just in case multiple location requests were added to the
2154 // same receiver (this request may be high power and the initial might not have been).
2155 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 }
2157
Nick Pellye0fd6932012-07-11 10:26:13 -07002158 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002159 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2160 String packageName) {
2161 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002162
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002163 final int pid = Binder.getCallingPid();
2164 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002165
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002166 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002167 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002168 boolean hideFromAppOps = false;
2169 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2170 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002171
2172 // providers may use public location API's, need to clear identity
2173 long identity = Binder.clearCallingIdentity();
2174 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002175 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002176 } finally {
2177 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002178 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002179 }
2180 }
2181
2182 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002183 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002184
2185 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2186 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2187 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002188 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
2191
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002192 receiver.updateMonitoring(false);
2193
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002194 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002195 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002196 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2197 if (oldRecords != null) {
2198 // Call dispose() on the obsolete update records.
2199 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002200 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002201 record.disposeLocked(false);
2202 }
2203 // Accumulate providers
2204 providers.addAll(oldRecords.keySet());
2205 }
2206
2207 // update provider
2208 for (String provider : providers) {
2209 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002210 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002211 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 }
2213
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002214 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002215 }
2216 }
2217
Dianne Hackbornc2293022013-02-06 23:14:49 -08002218 private void applyAllProviderRequirementsLocked() {
2219 for (LocationProviderInterface p : mProviders) {
2220 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002221 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002222 continue;
2223 }
2224
2225 applyRequirementsLocked(p.getName());
2226 }
2227 }
2228
Nick Pellye0fd6932012-07-11 10:26:13 -07002229 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002230 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002231 if (D) Log.d(TAG, "getLastLocation: " + request);
2232 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002233 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002234 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002235 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2236 request.getProvider());
2237 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002238
David Christieb870dbf2015-06-22 12:42:53 -07002239 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002240 final int uid = Binder.getCallingUid();
2241 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002242 try {
2243 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002244 if (D) {
2245 Log.d(TAG, "not returning last loc for blacklisted app: " +
2246 packageName);
2247 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002248 return null;
2249 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002250
David Christieb870dbf2015-06-22 12:42:53 -07002251 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002252 if (D) {
2253 Log.d(TAG, "not returning last loc for no op app: " +
2254 packageName);
2255 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002256 return null;
2257 }
2258
Victoria Leaseb711d572012-10-02 13:14:11 -07002259 synchronized (mLock) {
2260 // Figure out the provider. Either its explicitly request (deprecated API's),
2261 // or use the fused provider
2262 String name = request.getProvider();
2263 if (name == null) name = LocationManager.FUSED_PROVIDER;
2264 LocationProviderInterface provider = mProvidersByName.get(name);
2265 if (provider == null) return null;
2266
Victoria Lease09eeaec2013-02-05 11:34:13 -08002267 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002268
David Christie1b9b7b12013-04-15 15:31:11 -07002269 Location location;
2270 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2271 // Make sure that an app with coarse permissions can't get frequent location
2272 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2273 location = mLastLocationCoarseInterval.get(name);
2274 } else {
2275 location = mLastLocation.get(name);
2276 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002277 if (location == null) {
2278 return null;
2279 }
Victoria Lease37425c32012-10-16 16:08:48 -07002280 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002281 Location noGPSLocation = location.getExtraLocation(
2282 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002283 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002284 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002285 }
Victoria Lease37425c32012-10-16 16:08:48 -07002286 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002287 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002288 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002289 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002290 return null;
2291 } finally {
2292 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002293 }
2294 }
2295
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002296 /**
2297 * Provides an interface to inject and set the last location if location is not available
2298 * currently.
2299 *
2300 * This helps in cases where the product (Cars for example) has saved the last known location
2301 * before powering off. This interface lets the client inject the saved location while the GPS
2302 * chipset is getting its first fix, there by improving user experience.
2303 *
2304 * @param location - Location object to inject
2305 * @return true if update was successful, false if not
2306 */
2307 @Override
2308 public boolean injectLocation(Location location) {
2309 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2310 "Location Hardware permission not granted to inject location");
2311 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2312 "Access Fine Location permission not granted to inject Location");
2313
2314 if (location == null) {
2315 if (D) {
2316 Log.d(TAG, "injectLocation(): called with null location");
2317 }
2318 return false;
2319 }
2320 LocationProviderInterface p = null;
2321 String provider = location.getProvider();
2322 if (provider != null) {
2323 p = mProvidersByName.get(provider);
2324 }
2325 if (p == null) {
2326 if (D) {
2327 Log.d(TAG, "injectLocation(): unknown provider");
2328 }
2329 return false;
2330 }
2331 synchronized (mLock) {
2332 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2333 if (D) {
2334 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2335 }
2336 return false;
2337 } else {
2338 // NOTE: If last location is already available, location is not injected. If
2339 // provider's normal source (like a GPS chipset) have already provided an output,
2340 // there is no need to inject this location.
2341 if (mLastLocation.get(provider) == null) {
2342 updateLastLocationLocked(location, provider);
2343 } else {
2344 if (D) {
2345 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2346 }
2347 return false;
2348 }
2349 }
2350 }
2351 return true;
2352 }
2353
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002354 @Override
2355 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2356 String packageName) {
2357 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002358 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2359 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002360 checkPendingIntent(intent);
2361 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002362 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2363 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002364 // Require that caller can manage given document
2365 boolean callerHasLocationHardwarePermission =
2366 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002367 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002368 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2369 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002370
Victoria Lease37425c32012-10-16 16:08:48 -07002371 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002372
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002373 // geo-fence manager uses the public location API, need to clear identity
2374 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002375 // TODO: http://b/23822629
2376 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002377 // temporary measure until geofences work for secondary users
2378 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2379 return;
2380 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002381 long identity = Binder.clearCallingIdentity();
2382 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002383 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2384 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002385 } finally {
2386 Binder.restoreCallingIdentity(identity);
2387 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002388 }
2389
2390 @Override
2391 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002392 checkPendingIntent(intent);
2393 checkPackageName(packageName);
2394
2395 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2396
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002397 // geo-fence manager uses the public location API, need to clear identity
2398 long identity = Binder.clearCallingIdentity();
2399 try {
2400 mGeofenceManager.removeFence(geofence, intent);
2401 } finally {
2402 Binder.restoreCallingIdentity(identity);
2403 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002404 }
2405
2406
2407 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002408 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002409 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002410 return false;
2411 }
2412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002414 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002416 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002417 return false;
2418 }
2419 return true;
2420 }
2421
Nick Pellye0fd6932012-07-11 10:26:13 -07002422 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002423 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002424 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002425 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002426 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002427 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002428 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002430 }
2431 }
2432
Nick Pellye0fd6932012-07-11 10:26:13 -07002433 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002434 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002435 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002436 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002437 return false;
2438 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002439
2440 synchronized (mLock) {
2441 Identity callerIdentity
2442 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002443 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002444 long identity = Binder.clearCallingIdentity();
2445 try {
2446 if (isThrottlingExemptLocked(callerIdentity)
2447 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002448 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002449 return mGnssMeasurementsProvider.addListener(listener);
2450 }
2451 } finally {
2452 Binder.restoreCallingIdentity(identity);
2453 }
2454
2455 return true;
2456 }
destradaaea8a8a62014-06-23 18:19:03 -07002457 }
2458
2459 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002460 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2461 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002462 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002463 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002464 mGnssMeasurementsProvider.removeListener(listener);
2465 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002466 }
destradaaea8a8a62014-06-23 18:19:03 -07002467 }
2468
2469 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002470 public boolean addGnssNavigationMessageListener(
2471 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002472 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002473 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002474 return false;
2475 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002476
2477 synchronized (mLock) {
2478 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002479 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002480 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002481 long identity = Binder.clearCallingIdentity();
2482 try {
2483 if (isThrottlingExemptLocked(callerIdentity)
2484 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002485 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002486 return mGnssNavigationMessageProvider.addListener(listener);
2487 }
2488 } finally {
2489 Binder.restoreCallingIdentity(identity);
2490 }
2491
2492 return true;
2493 }
destradaa4b3e3932014-07-21 18:01:47 -07002494 }
2495
2496 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002497 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2498 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002499 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002500 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002501 mGnssNavigationMessageProvider.removeListener(listener);
2502 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002503 }
destradaa4b3e3932014-07-21 18:01:47 -07002504 }
2505
2506 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002508 if (provider == null) {
2509 // throw NullPointerException to remain compatible with previous implementation
2510 throw new NullPointerException();
2511 }
Victoria Lease37425c32012-10-16 16:08:48 -07002512 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2513 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002514
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002515 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002516 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002517 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2519 }
2520
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002521 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002522 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002523 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002524
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002525 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002526 }
2527 }
2528
Nick Pellye0fd6932012-07-11 10:26:13 -07002529 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002530 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002531 if (Binder.getCallingUid() != Process.myUid()) {
2532 throw new SecurityException(
2533 "calling sendNiResponse from outside of the system is not allowed");
2534 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002535 try {
2536 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002537 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002538 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002539 return false;
2540 }
2541 }
2542
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002544 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002545 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002546 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002548 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002549 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002550 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002551 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002552 }
2553
Victoria Lease37425c32012-10-16 16:08:48 -07002554 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2555 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002557 LocationProviderInterface p;
2558 synchronized (mLock) {
2559 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002560 }
2561
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002562 if (p == null) return null;
2563 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
2565
Jason Monkb71218a2015-06-17 14:44:39 -04002566 /**
2567 * @return null if the provider does not exist
2568 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002569 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002570 */
2571 @Override
2572 public String getNetworkProviderPackage() {
2573 LocationProviderInterface p;
2574 synchronized (mLock) {
2575 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2576 return null;
2577 }
2578 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2579 }
2580
2581 if (p instanceof LocationProviderProxy) {
2582 return ((LocationProviderProxy) p).getConnectedPackageName();
2583 }
2584 return null;
2585 }
2586
Maggieaa080f92018-01-04 15:35:11 -08002587 /**
2588 * Method for enabling or disabling location.
2589 *
2590 * @param enabled true to enable location. false to disable location
2591 * @param userId the user id to set
2592 */
2593 @Override
2594 public void setLocationEnabledForUser(boolean enabled, int userId) {
2595 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2596 checkInteractAcrossUsersPermission(userId);
2597
Maggie91e630c2018-01-24 17:31:46 -08002598 // Enable or disable all location providers. Fused provider and passive provider are
2599 // excluded.
Maggieaa080f92018-01-04 15:35:11 -08002600 synchronized (mLock) {
Maggie91e630c2018-01-24 17:31:46 -08002601 for(String provider : getAllProvidersForLocationSettings()) {
Maggieaa080f92018-01-04 15:35:11 -08002602 setProviderEnabledForUser(provider, enabled, userId);
2603 }
2604 }
2605 }
2606
2607 /**
2608 * Returns the current enabled/disabled status of location
2609 *
2610 * @param userId the user id to query
2611 * @return true if location is enabled. false if location is disabled.
2612 */
2613 @Override
2614 public boolean isLocationEnabledForUser(int userId) {
Maggieaa080f92018-01-04 15:35:11 -08002615 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2616 checkInteractAcrossUsersPermission(userId);
2617
Maggie91e630c2018-01-24 17:31:46 -08002618 // If at least one location provider is enabled, return true. Fused provider and passive
2619 // provider are excluded.
Maggieaa080f92018-01-04 15:35:11 -08002620 synchronized (mLock) {
Maggie91e630c2018-01-24 17:31:46 -08002621 for (String provider : getAllProvidersForLocationSettings()) {
Maggieaa080f92018-01-04 15:35:11 -08002622 if (isProviderEnabledForUser(provider, userId)) {
2623 return true;
2624 }
2625 }
2626 return false;
2627 }
2628 }
2629
Nick Pellye0fd6932012-07-11 10:26:13 -07002630 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002631 public boolean isProviderEnabled(String provider) {
Maggie9ebcf052018-01-24 11:01:20 -08002632 return isProviderEnabledForUser(provider, UserHandle.getCallingUserId());
Maggieaa080f92018-01-04 15:35:11 -08002633 }
2634
2635 /**
2636 * Method for determining if a location provider is enabled.
2637 *
2638 * @param provider the location provider to query
2639 * @param userId the user id to query
2640 * @return true if the provider is enabled
2641 */
2642 @Override
2643 public boolean isProviderEnabledForUser(String provider, int userId) {
2644 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2645 checkInteractAcrossUsersPermission(userId);
2646
Tom O'Neilld5759432013-09-11 11:03:03 -07002647 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2648 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002649 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2650
Victoria Lease09eeaec2013-02-05 11:34:13 -08002651 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002652 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002653 try {
2654 synchronized (mLock) {
2655 LocationProviderInterface p = mProvidersByName.get(provider);
Maggieaa080f92018-01-04 15:35:11 -08002656 return p != null
2657 && isAllowedByUserSettingsLockedForUser(provider, uid, userId);
Victoria Leaseb711d572012-10-02 13:14:11 -07002658 }
2659 } finally {
2660 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002661 }
2662 }
2663
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002664 /**
Maggieaa080f92018-01-04 15:35:11 -08002665 * Method for enabling or disabling a single location provider.
2666 *
2667 * @param provider the name of the provider
2668 * @param enabled true to enable the provider. false to disable the provider
2669 * @param userId the user id to set
2670 * @return true if the value was set successfully. false on failure.
2671 */
2672 @Override
2673 public boolean setProviderEnabledForUser(
2674 String provider, boolean enabled, int userId) {
2675 mContext.enforceCallingPermission(
2676 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2677 "Requires WRITE_SECURE_SETTINGS permission");
2678
2679 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2680 checkInteractAcrossUsersPermission(userId);
2681
2682 final long identity = Binder.clearCallingIdentity();
2683 try {
2684 synchronized (mLock) {
2685 // to ensure thread safety, we write the provider name with a '+' or '-'
2686 // and let the SettingsProvider handle it rather than reading and modifying
2687 // the list of enabled providers.
2688 if (enabled) {
2689 provider = "+" + provider;
2690 } else {
2691 provider = "-" + provider;
2692 }
2693 return Settings.Secure.putStringForUser(
2694 mContext.getContentResolver(),
2695 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2696 provider,
2697 userId);
2698 }
2699 } finally {
2700 Binder.restoreCallingIdentity(identity);
2701 }
2702 }
2703
2704 /**
Maggie91e630c2018-01-24 17:31:46 -08002705 * Return all location providers except fused provider and passive provider. These two
2706 * providers are not generating location by themselves, but only echo locations from other
2707 * providers.
2708 *
2709 * @return All location providers except fused provider and passive provider, including
2710 * providers that are not permitted to be accessed by the calling activity or are
2711 * currently disabled.
2712 */
2713 private List<String> getAllProvidersForLocationSettings() {
2714 List<String> providersForSettings = new ArrayList<>(mProviders.size());
2715 for (String provider : getAllProviders()) {
2716 if (provider.equals(LocationManager.PASSIVE_PROVIDER)) {
2717 continue;
2718 }
2719 providersForSettings.add(provider);
2720 }
2721 return providersForSettings;
2722 }
2723
2724 /**
Maggieaa080f92018-01-04 15:35:11 -08002725 * Read location provider status from Settings.Secure
2726 *
2727 * @param provider the location provider to query
2728 * @param userId the user id to query
2729 * @return true if the provider is enabled
2730 */
2731 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2732 long identity = Binder.clearCallingIdentity();
2733 try {
2734 // Use system settings
2735 ContentResolver cr = mContext.getContentResolver();
2736 String allowedProviders = Settings.Secure.getStringForUser(
2737 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2738 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2739 } finally {
2740 Binder.restoreCallingIdentity(identity);
2741 }
2742 }
2743
2744 /**
2745 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2746 * current user id
2747 *
2748 * @param userId the user id to get or set value
2749 */
2750 private void checkInteractAcrossUsersPermission(int userId) {
2751 int uid = Binder.getCallingUid();
2752 if (UserHandle.getUserId(uid) != userId) {
2753 if (ActivityManager.checkComponentPermission(
2754 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2755 != PERMISSION_GRANTED) {
2756 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2757 }
2758 }
2759 }
2760
2761 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002762 * Returns "true" if the UID belongs to a bound location provider.
2763 *
2764 * @param uid the uid
2765 * @return true if uid belongs to a bound location provider
2766 */
2767 private boolean isUidALocationProvider(int uid) {
2768 if (uid == Process.SYSTEM_UID) {
2769 return true;
2770 }
2771 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002772 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002773 }
2774 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002775 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002776 }
2777 return false;
2778 }
2779
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002780 private void checkCallerIsProvider() {
2781 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002782 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002783 return;
2784 }
2785
2786 // Previously we only used the INSTALL_LOCATION_PROVIDER
2787 // check. But that is system or signature
2788 // protection level which is not flexible enough for
2789 // providers installed oustide the system image. So
2790 // also allow providers with a UID matching the
2791 // currently bound package name
2792
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002793 if (isUidALocationProvider(Binder.getCallingUid())) {
2794 return;
2795 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002796
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002797 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2798 "or UID of a currently bound location provider");
2799 }
2800
David Christie1f141c12014-05-14 15:11:15 -07002801 /**
2802 * Returns true if the given package belongs to the given uid.
2803 */
2804 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002805 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 return false;
2807 }
David Christie1f141c12014-05-14 15:11:15 -07002808 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2809 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002810 return false;
2811 }
David Christie1f141c12014-05-14 15:11:15 -07002812 for (String name : packageNames) {
2813 if (packageName.equals(name)) {
2814 return true;
2815 }
2816 }
2817 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
2819
Nick Pellye0fd6932012-07-11 10:26:13 -07002820 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002821 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002822 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002823
Nick Pelly2eeeec22012-07-18 13:13:37 -07002824 if (!location.isComplete()) {
2825 Log.w(TAG, "Dropping incomplete location: " + location);
2826 return;
2827 }
2828
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002829 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2830 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002831 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002832 mLocationHandler.sendMessageAtFrontOfQueue(m);
2833 }
2834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835
Laurent Tu75defb62012-11-01 16:21:52 -07002836 private static boolean shouldBroadcastSafe(
2837 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002838 // Always broadcast the first update
2839 if (lastLoc == null) {
2840 return true;
2841 }
2842
Nick Pellyf1be6862012-05-15 10:53:42 -07002843 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002844 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002845 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2846 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002847 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002848 return false;
2849 }
2850
2851 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002852 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 if (minDistance > 0.0) {
2854 if (loc.distanceTo(lastLoc) <= minDistance) {
2855 return false;
2856 }
2857 }
2858
Laurent Tu75defb62012-11-01 16:21:52 -07002859 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002860 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002861 return false;
2862 }
2863
2864 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002865 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002866 }
2867
Mike Lockwooda4903f22010-02-17 06:42:23 -05002868 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002869 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002870 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002871 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002872 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002873 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002874 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002875 updateLastLocationLocked(location, provider);
2876 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002877 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002878 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002879 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2880 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002881 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882
David Christie1b9b7b12013-04-15 15:31:11 -07002883 // Update last known coarse interval location if enough time has passed.
2884 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2885 if (lastLocationCoarseInterval == null) {
2886 lastLocationCoarseInterval = new Location(location);
2887 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2888 }
2889 long timeDiffNanos = location.getElapsedRealtimeNanos()
2890 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2891 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2892 lastLocationCoarseInterval.set(location);
2893 }
2894 // Don't ever return a coarse location that is more recent than the allowed update
2895 // interval (i.e. don't allow an app to keep registering and unregistering for
2896 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002897 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002898 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2899
Laurent Tu60ec50a2012-10-04 17:00:10 -07002900 // Skip if there are no UpdateRecords for this provider.
2901 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2902 if (records == null || records.size() == 0) return;
2903
Victoria Lease09016ab2012-09-16 12:33:15 -07002904 // Fetch coarse location
2905 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002906 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002907 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2908 }
2909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002910 // Fetch latest status update time
2911 long newStatusUpdateTime = p.getStatusUpdateTime();
2912
David Christie2ff96af2014-01-30 16:09:37 -08002913 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002914 Bundle extras = new Bundle();
2915 int status = p.getStatus(extras);
2916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002917 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002918 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002919
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002920 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002921 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002923 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002924
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002925 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2926 if (!isCurrentProfile(receiverUserId)
2927 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002928 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002929 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002930 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002931 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002932 }
2933 continue;
2934 }
2935
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002936 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002937 if (D) {
2938 Log.d(TAG, "skipping loc update for blacklisted app: " +
2939 receiver.mIdentity.mPackageName);
2940 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002941 continue;
2942 }
2943
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002944 if (!reportLocationAccessNoThrow(
2945 receiver.mIdentity.mPid,
2946 receiver.mIdentity.mUid,
2947 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002948 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002949 if (D) {
2950 Log.d(TAG, "skipping loc update for no op app: " +
2951 receiver.mIdentity.mPackageName);
2952 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002953 continue;
2954 }
2955
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002956 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002957 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2958 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002959 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002960 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002961 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002962 if (notifyLocation != null) {
2963 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002964 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002965 if (lastLoc == null) {
2966 lastLoc = new Location(notifyLocation);
2967 r.mLastFixBroadcast = lastLoc;
2968 } else {
2969 lastLoc.set(notifyLocation);
2970 }
2971 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2972 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2973 receiverDead = true;
2974 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002975 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977 }
2978
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002979 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002980 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002981 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002982
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002983 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002985 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002986 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002987 }
2988 }
2989
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002990 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002991 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002992 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002993 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002994 }
2995 deadUpdateRecords.add(r);
2996 }
2997 // track dead receivers
2998 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002999 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003000 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07003001 }
3002 if (!deadReceivers.contains(receiver)) {
3003 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 }
3005 }
3006 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003007
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003008 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003010 for (Receiver receiver : deadReceivers) {
3011 removeUpdatesLocked(receiver);
3012 }
3013 }
3014 if (deadUpdateRecords != null) {
3015 for (UpdateRecord r : deadUpdateRecords) {
3016 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 }
Victoria Lease8b38b292012-12-04 15:04:43 -08003018 applyRequirementsLocked(provider);
3019 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 }
3021
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08003022 /**
3023 * Updates last location with the given location
3024 *
3025 * @param location new location to update
3026 * @param provider Location provider to update for
3027 */
3028 private void updateLastLocationLocked(Location location, String provider) {
3029 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3030 Location lastNoGPSLocation;
3031 Location lastLocation = mLastLocation.get(provider);
3032 if (lastLocation == null) {
3033 lastLocation = new Location(provider);
3034 mLastLocation.put(provider, lastLocation);
3035 } else {
3036 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
3037 if (noGPSLocation == null && lastNoGPSLocation != null) {
3038 // New location has no no-GPS location: adopt last no-GPS location. This is set
3039 // directly into location because we do not want to notify COARSE clients.
3040 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
3041 }
3042 }
3043 lastLocation.set(location);
3044 }
3045
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003047 public LocationWorkerHandler(Looper looper) {
3048 super(looper, null, true);
3049 }
3050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003051 @Override
3052 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003053 switch (msg.what) {
3054 case MSG_LOCATION_CHANGED:
3055 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3056 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 }
3058 }
3059 }
3060
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003061 private boolean isMockProvider(String provider) {
3062 synchronized (mLock) {
3063 return mMockProviders.containsKey(provider);
3064 }
3065 }
3066
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003067 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003068 // create a working copy of the incoming Location so that the service can modify it without
3069 // disturbing the caller's copy
3070 Location myLocation = new Location(location);
3071 String provider = myLocation.getProvider();
3072
3073 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3074 // bit if location did not come from a mock provider because passive/fused providers can
3075 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3076 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3077 myLocation.setIsFromMockProvider(true);
3078 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003079
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003080 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003081 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3082 if (!passive) {
3083 // notify passive provider of the new location
3084 mPassiveProvider.updateLocation(myLocation);
3085 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003086 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090
Mike Lockwoode97ae402010-09-29 15:23:46 -04003091 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3092 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003093 public void onPackageDisappeared(String packageName, int reason) {
3094 // remove all receivers associated with this package name
3095 synchronized (mLock) {
3096 ArrayList<Receiver> deadReceivers = null;
3097
3098 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003099 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003100 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003101 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003102 }
3103 deadReceivers.add(receiver);
3104 }
3105 }
3106
3107 // perform removal outside of mReceivers loop
3108 if (deadReceivers != null) {
3109 for (Receiver receiver : deadReceivers) {
3110 removeUpdatesLocked(receiver);
3111 }
3112 }
3113 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003114 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003115 };
3116
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117 // Geocoder
3118
Nick Pellye0fd6932012-07-11 10:26:13 -07003119 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003120 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003121 return mGeocodeProvider != null;
3122 }
3123
Nick Pellye0fd6932012-07-11 10:26:13 -07003124 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003125 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003126 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003127 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003128 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3129 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003131 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 }
3133
Mike Lockwooda55c3212009-04-15 11:10:11 -04003134
Nick Pellye0fd6932012-07-11 10:26:13 -07003135 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003137 double lowerLeftLatitude, double lowerLeftLongitude,
3138 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003139 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003140
3141 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003142 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3143 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3144 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003146 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147 }
3148
3149 // Mock Providers
3150
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003151 private boolean canCallerAccessMockLocation(String opPackageName) {
3152 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3153 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 }
3155
Nick Pellye0fd6932012-07-11 10:26:13 -07003156 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003157 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3158 if (!canCallerAccessMockLocation(opPackageName)) {
3159 return;
3160 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161
Mike Lockwooda4903f22010-02-17 06:42:23 -05003162 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3163 throw new IllegalArgumentException("Cannot mock the passive location provider");
3164 }
3165
Mike Lockwood86328a92009-10-23 08:38:25 -04003166 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003167 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003168 // remove the real provider if we are replacing GPS or network provider
3169 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003170 || LocationManager.NETWORK_PROVIDER.equals(name)
3171 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003172 LocationProviderInterface p = mProvidersByName.get(name);
3173 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003174 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003175 }
3176 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003177 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003178 updateProvidersLocked();
3179 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003180 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 }
3182
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003183 private void addTestProviderLocked(String name, ProviderProperties properties) {
3184 if (mProvidersByName.get(name) != null) {
3185 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3186 }
3187 MockProvider provider = new MockProvider(name, this, properties);
3188 addProviderLocked(provider);
3189 mMockProviders.put(name, provider);
3190 mLastLocation.put(name, null);
3191 mLastLocationCoarseInterval.put(name, null);
3192 }
3193
Nick Pellye0fd6932012-07-11 10:26:13 -07003194 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003195 public void removeTestProvider(String provider, String opPackageName) {
3196 if (!canCallerAccessMockLocation(opPackageName)) {
3197 return;
3198 }
3199
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003200 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003201
3202 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003203 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003204 clearTestProviderEnabled(provider, opPackageName);
3205 clearTestProviderLocation(provider, opPackageName);
3206 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003207
You Kima6d0b6f2012-10-28 03:58:44 +09003208 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003209 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3211 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003212 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003213 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003214
3215 // reinstate real provider if available
3216 LocationProviderInterface realProvider = mRealProviders.get(provider);
3217 if (realProvider != null) {
3218 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003219 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003220 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003221 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003223 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 }
3225 }
3226
Nick Pellye0fd6932012-07-11 10:26:13 -07003227 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003228 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3229 if (!canCallerAccessMockLocation(opPackageName)) {
3230 return;
3231 }
3232
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003233 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003234 MockProvider mockProvider = mMockProviders.get(provider);
3235 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003236 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3237 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003238
3239 // Ensure that the location is marked as being mock. There's some logic to do this in
3240 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3241 Location mock = new Location(loc);
3242 mock.setIsFromMockProvider(true);
3243
3244 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3245 // The location has an explicit provider that is different from the mock provider
3246 // name. The caller may be trying to fool us via bug 33091107.
3247 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3248 provider + "!=" + loc.getProvider());
3249 }
3250
Mike Lockwood95427cd2009-05-07 13:27:54 -04003251 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3252 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003253 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003254 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
3256 }
3257
Nick Pellye0fd6932012-07-11 10:26:13 -07003258 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003259 public void clearTestProviderLocation(String provider, String opPackageName) {
3260 if (!canCallerAccessMockLocation(opPackageName)) {
3261 return;
3262 }
3263
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003264 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003265 MockProvider mockProvider = mMockProviders.get(provider);
3266 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3268 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003269 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003270 }
3271 }
3272
Nick Pellye0fd6932012-07-11 10:26:13 -07003273 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003274 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3275 if (!canCallerAccessMockLocation(opPackageName)) {
3276 return;
3277 }
3278
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003279 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003280 MockProvider mockProvider = mMockProviders.get(provider);
3281 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003282 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3283 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003284 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003286 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 mEnabledProviders.add(provider);
3288 mDisabledProviders.remove(provider);
3289 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003290 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 mEnabledProviders.remove(provider);
3292 mDisabledProviders.add(provider);
3293 }
3294 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003295 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297 }
3298
Nick Pellye0fd6932012-07-11 10:26:13 -07003299 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003300 public void clearTestProviderEnabled(String provider, String opPackageName) {
3301 if (!canCallerAccessMockLocation(opPackageName)) {
3302 return;
3303 }
3304
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003305 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003306 MockProvider mockProvider = mMockProviders.get(provider);
3307 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3309 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003310 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 mEnabledProviders.remove(provider);
3312 mDisabledProviders.remove(provider);
3313 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003314 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
3316 }
3317
Nick Pellye0fd6932012-07-11 10:26:13 -07003318 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003319 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3320 String opPackageName) {
3321 if (!canCallerAccessMockLocation(opPackageName)) {
3322 return;
3323 }
3324
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003325 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003326 MockProvider mockProvider = mMockProviders.get(provider);
3327 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3329 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003330 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003331 }
3332 }
3333
Nick Pellye0fd6932012-07-11 10:26:13 -07003334 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003335 public void clearTestProviderStatus(String provider, String opPackageName) {
3336 if (!canCallerAccessMockLocation(opPackageName)) {
3337 return;
3338 }
3339
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003340 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003341 MockProvider mockProvider = mMockProviders.get(provider);
3342 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3344 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003345 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
3347 }
3348
3349 private void log(String log) {
3350 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003351 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 }
3353 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003354
3355 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003357 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003358
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003359 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003360 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3361 if (mGnssMetricsProvider != null) {
3362 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3363 }
3364 return;
3365 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003368 for (Receiver receiver : mReceivers.values()) {
3369 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 }
David Christie2ff96af2014-01-30 16:09:37 -08003371 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003372 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3373 pw.println(" " + entry.getKey() + ":");
3374 for (UpdateRecord record : entry.getValue()) {
3375 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 }
3377 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003378 pw.println(" Active GnssMeasurement Listeners:");
3379 for (Identity identity : mGnssMeasurementsListeners.values()) {
3380 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3381 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3382 }
3383 pw.println(" Active GnssNavigationMessage Listeners:");
3384 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3385 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3386 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3387 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003388 pw.println(" Overlay Provider Packages:");
3389 for (LocationProviderInterface provider : mProviders) {
3390 if (provider instanceof LocationProviderProxy) {
3391 pw.println(" " + provider.getName() + ": "
3392 + ((LocationProviderProxy) provider).getConnectedPackageName());
3393 }
3394 }
David Christie2ff96af2014-01-30 16:09:37 -08003395 pw.println(" Historical Records by Provider:");
3396 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3397 : mRequestStatistics.statistics.entrySet()) {
3398 PackageProviderKey key = entry.getKey();
3399 PackageStatistics stats = entry.getValue();
3400 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3401 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003403 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3404 String provider = entry.getKey();
3405 Location location = entry.getValue();
3406 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003407 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003408
David Christie1b9b7b12013-04-15 15:31:11 -07003409 pw.println(" Last Known Locations Coarse Intervals:");
3410 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3411 String provider = entry.getKey();
3412 Location location = entry.getValue();
3413 pw.println(" " + provider + ": " + location);
3414 }
3415
Nick Pellye0fd6932012-07-11 10:26:13 -07003416 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 if (mEnabledProviders.size() > 0) {
3419 pw.println(" Enabled Providers:");
3420 for (String i : mEnabledProviders) {
3421 pw.println(" " + i);
3422 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003424 }
3425 if (mDisabledProviders.size() > 0) {
3426 pw.println(" Disabled Providers:");
3427 for (String i : mDisabledProviders) {
3428 pw.println(" " + i);
3429 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003430 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003431 pw.append(" ");
3432 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 if (mMockProviders.size() > 0) {
3434 pw.println(" Mock Providers:");
3435 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003436 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 }
3438 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003439
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003440 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3441 pw.println(" Throttling Whitelisted Packages:");
3442 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3443 pw.println(" " + packageName);
3444 }
3445 }
3446
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003447 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003448 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003449
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003450 if (args.length > 0 && "short".equals(args[0])) {
3451 return;
3452 }
gomo48f1a642017-11-10 20:35:46 -08003453 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003454 pw.print(provider.getName() + " Internal State");
3455 if (provider instanceof LocationProviderProxy) {
3456 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3457 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003458 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003459 pw.println(":");
3460 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003461 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003462 if (mGnssBatchingInProgress) {
3463 pw.println(" GNSS batching in progress");
3464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 }
3466 }
3467}