blob: 57c992fdcf4879042d82db5580b61c20c88837be [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Soonil Nagarkar7decfb62017-01-18 12:18:49 -080019import android.app.ActivityManager;
Wyatt Rileycf879db2017-01-12 13:57:38 -080020import android.annotation.NonNull;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080021import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080022import android.util.ArraySet;
gomo48f1a642017-11-10 20:35:46 -080023
destradaaea8a8a62014-06-23 18:19:03 -070024import com.android.internal.content.PackageMonitor;
25import com.android.internal.location.ProviderProperties;
26import com.android.internal.location.ProviderRequest;
27import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070028import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060029import com.android.internal.util.DumpUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070030import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070031import com.android.server.location.FlpHardwareProvider;
32import com.android.server.location.FusedProxy;
33import com.android.server.location.GeocoderProxy;
34import com.android.server.location.GeofenceManager;
35import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080036import com.android.server.location.GnssLocationProvider;
37import com.android.server.location.GnssMeasurementsProvider;
38import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070039import com.android.server.location.LocationBlacklist;
40import com.android.server.location.LocationFudger;
41import com.android.server.location.LocationProviderInterface;
42import com.android.server.location.LocationProviderProxy;
43import com.android.server.location.LocationRequestStatistics;
44import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
45import com.android.server.location.LocationRequestStatistics.PackageStatistics;
46import com.android.server.location.MockProvider;
47import com.android.server.location.PassiveProvider;
48
Dianne Hackborna06de0f2012-12-11 16:34:47 -080049import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070051import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.content.ContentResolver;
53import android.content.Context;
54import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070055import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070056import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050057import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.content.pm.PackageManager;
Todd Kennedy0eb97382017-10-03 16:57:22 -070059import android.content.pm.PackageManagerInternal;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070060import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050061import android.content.pm.ResolveInfo;
62import android.content.pm.Signature;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050063import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070064import android.database.ContentObserver;
destradaaa4fa3b52014-07-09 10:46:39 -070065import android.hardware.location.ActivityRecognitionHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070067import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050068import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070069import android.location.Geofence;
Wyatt Rileycf879db2017-01-12 13:57:38 -080070import android.location.IBatchedLocationCallback;
Lifu Tang818aa2c2016-02-01 01:52:00 -080071import android.location.IGnssMeasurementsListener;
Lifu Tang30f95a72016-01-07 23:20:38 -080072import android.location.IGnssStatusListener;
73import android.location.IGnssStatusProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -070074import android.location.IGpsGeofenceHardware;
Lifu Tang818aa2c2016-02-01 01:52:00 -080075import android.location.IGnssNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.location.ILocationListener;
77import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040078import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.location.Location;
80import android.location.LocationManager;
81import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070082import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Binder;
84import android.os.Bundle;
85import android.os.Handler;
86import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070087import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Message;
89import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070090import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070092import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070093import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070094import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070095import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import android.provider.Settings;
Tom O'Neilla206a0f2016-12-15 10:26:28 -080097import android.text.TextUtils;
98import android.util.EventLog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800100import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700101
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
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800235 private final ArrayMap<IGnssMeasurementsListener, Identity> mGnssMeasurementsListeners =
236 new ArrayMap<>();
237
238 private final ArrayMap<IGnssNavigationMessageListener, Identity>
239 mGnssNavigationMessageListeners = new ArrayMap<>();
240
Victoria Lease38389b62012-09-30 11:44:22 -0700241 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700242 private int mCurrentUserId = UserHandle.USER_SYSTEM;
gomo48f1a642017-11-10 20:35:46 -0800243 private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
Victoria Lease38389b62012-09-30 11:44:22 -0700244
Lifu Tang9363b942016-02-16 18:07:00 -0800245 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800246
Siddharth Raybb608c82017-03-16 11:33:34 -0700247 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700248
249 private GnssLocationProvider.GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800250 private IBatchedLocationCallback mGnssBatchingCallback;
251 private LinkedCallback mGnssBatchingDeathCallback;
252 private boolean mGnssBatchingInProgress = false;
253
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700254 public LocationManagerService(Context context) {
255 super();
256 mContext = context;
gomo48f1a642017-11-10 20:35:46 -0800257 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800258
Svet Ganovadc1cf42015-06-15 16:36:24 -0700259 // Let the package manager query which are the default location
260 // providers as they get certain permissions granted by default.
261 PackageManagerInternal packageManagerInternal = LocalServices.getService(
262 PackageManagerInternal.class);
263 packageManagerInternal.setLocationPackagesProvider(
264 new PackageManagerInternal.PackagesProvider() {
265 @Override
266 public String[] getPackages(int userId) {
267 return mContext.getResources().getStringArray(
268 com.android.internal.R.array.config_locationProviderPackageNames);
269 }
270 });
271
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700272 if (D) Log.d(TAG, "Constructed");
273
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700274 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700275 }
276
Svetoslav Ganova0027152013-06-25 14:59:53 -0700277 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700278 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700279 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700280
Victoria Lease5cd731a2012-12-19 15:04:21 -0800281 // fetch package manager
282 mPackageManager = mContext.getPackageManager();
283
Victoria Lease0aa28602013-05-29 15:28:26 -0700284 // fetch power manager
285 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800286
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800287 // fetch activity manager
288 mActivityManager
289 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
290
Victoria Lease5cd731a2012-12-19 15:04:21 -0800291 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700292 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800293
294 // prepare mLocationHandler's dependents
295 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
296 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
297 mBlacklist.init();
298 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
299
Dianne Hackbornc2293022013-02-06 23:14:49 -0800300 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700301 AppOpsManager.OnOpChangedListener callback
302 = new AppOpsManager.OnOpChangedInternalListener() {
303 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800304 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700305 for (Receiver receiver : mReceivers.values()) {
306 receiver.updateMonitoring(true);
307 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800308 applyAllProviderRequirementsLocked();
309 }
310 }
311 };
312 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
313
David Christieb870dbf2015-06-22 12:42:53 -0700314 PackageManager.OnPermissionsChangedListener permissionListener
315 = new PackageManager.OnPermissionsChangedListener() {
316 @Override
317 public void onPermissionsChanged(final int uid) {
318 synchronized (mLock) {
319 applyAllProviderRequirementsLocked();
320 }
321 }
322 };
323 mPackageManager.addOnPermissionsChangeListener(permissionListener);
324
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800325 // listen for background/foreground changes
326 ActivityManager.OnUidImportanceListener uidImportanceListener
327 = new ActivityManager.OnUidImportanceListener() {
328 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700329 public void onUidImportance(final int uid, final int importance) {
330 mLocationHandler.post(new Runnable() {
331 @Override
332 public void run() {
333 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800334 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700335 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800336 }
337 };
338 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700339 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800340
Amith Yamasanib27528d2014-06-05 15:02:10 -0700341 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
342 updateUserProfiles(mCurrentUserId);
343
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800344 updateBackgroundThrottlingWhitelistLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800345
Victoria Lease5cd731a2012-12-19 15:04:21 -0800346 // prepare providers
347 loadProvidersLocked();
348 updateProvidersLocked();
349 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700350
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700351 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700352 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700353 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700354 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800355 @Override
356 public void onChange(boolean selfChange) {
357 synchronized (mLock) {
358 updateProvidersLocked();
359 }
360 }
361 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800362 mContext.getContentResolver().registerContentObserver(
363 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
364 true,
365 new ContentObserver(mLocationHandler) {
366 @Override
367 public void onChange(boolean selfChange) {
368 synchronized (mLock) {
369 updateProvidersLocked();
370 }
371 }
372 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800373 mContext.getContentResolver().registerContentObserver(
gomo48f1a642017-11-10 20:35:46 -0800374 Settings.Global.getUriFor(
375 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
376 true,
377 new ContentObserver(mLocationHandler) {
378 @Override
379 public void onChange(boolean selfChange) {
380 synchronized (mLock) {
381 updateBackgroundThrottlingWhitelistLocked();
382 updateProvidersLocked();
383 }
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800384 }
gomo48f1a642017-11-10 20:35:46 -0800385 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800386 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700387
Victoria Lease38389b62012-09-30 11:44:22 -0700388 // listen for user change
389 IntentFilter intentFilter = new IntentFilter();
390 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700391 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
392 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700393 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700394
395 mContext.registerReceiverAsUser(new BroadcastReceiver() {
396 @Override
397 public void onReceive(Context context, Intent intent) {
398 String action = intent.getAction();
399 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
400 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700401 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
402 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
403 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700404 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700405 // shutdown only if UserId indicates whole system, not just one user
gomo48f1a642017-11-10 20:35:46 -0800406 if (D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700407 if (getSendingUserId() == UserHandle.USER_ALL) {
408 shutdownComponents();
409 }
Victoria Lease38389b62012-09-30 11:44:22 -0700410 }
411 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800412 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700413 }
414
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700415 private void onUidImportanceChanged(int uid, int importance) {
416 boolean foreground = isImportanceForeground(importance);
417 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
418 synchronized (mLock) {
419 for (Entry<String, ArrayList<UpdateRecord>> entry
gomo48f1a642017-11-10 20:35:46 -0800420 : mRecordsByProvider.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700421 String provider = entry.getKey();
422 for (UpdateRecord record : entry.getValue()) {
423 if (record.mReceiver.mIdentity.mUid == uid
gomo48f1a642017-11-10 20:35:46 -0800424 && record.mIsForegroundUid != foreground) {
425 if (D) {
426 Log.d(TAG, "request from uid " + uid + " is now "
427 + (foreground ? "foreground" : "background)"));
428 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700429 record.mIsForegroundUid = foreground;
430
431 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
432 affectedProviders.add(provider);
433 }
434 }
435 }
436 }
437 for (String provider : affectedProviders) {
438 applyRequirementsLocked(provider);
439 }
440
441 for (Entry<IGnssMeasurementsListener, Identity> entry
gomo48f1a642017-11-10 20:35:46 -0800442 : mGnssMeasurementsListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700443 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800444 if (D) {
445 Log.d(TAG, "gnss measurements listener from uid " + uid
446 + " is now " + (foreground ? "foreground" : "background)"));
447 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700448 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
449 mGnssMeasurementsProvider.addListener(entry.getKey());
450 } else {
451 mGnssMeasurementsProvider.removeListener(entry.getKey());
452 }
453 }
454 }
455
456 for (Entry<IGnssNavigationMessageListener, Identity> entry
gomo48f1a642017-11-10 20:35:46 -0800457 : mGnssNavigationMessageListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700458 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800459 if (D) {
460 Log.d(TAG, "gnss navigation message listener from uid "
461 + uid + " is now "
462 + (foreground ? "foreground" : "background)"));
463 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700464 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
465 mGnssNavigationMessageProvider.addListener(entry.getKey());
466 } else {
467 mGnssNavigationMessageProvider.removeListener(entry.getKey());
468 }
469 }
470 }
471 }
472 }
473
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800474 private static boolean isImportanceForeground(int importance) {
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700475 return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800476 }
477
Amith Yamasanib27528d2014-06-05 15:02:10 -0700478 /**
destradaab9026982015-08-27 17:34:54 -0700479 * Provides a way for components held by the {@link LocationManagerService} to clean-up
480 * gracefully on system's shutdown.
481 *
482 * NOTES:
483 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
484 * support for components that do not wish to handle such event.
485 */
486 private void shutdownComponents() {
gomo48f1a642017-11-10 20:35:46 -0800487 if (D) Log.d(TAG, "Shutting down components...");
destradaab9026982015-08-27 17:34:54 -0700488
489 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
490 if (gpsProvider != null && gpsProvider.isEnabled()) {
491 gpsProvider.disable();
492 }
493
destradaa2e385072015-10-14 16:45:58 -0700494 // it is needed to check if FLP HW provider is supported before accessing the instance, this
495 // avoids an exception to be thrown by the singleton factory method
496 if (FlpHardwareProvider.isSupported()) {
497 FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaab9026982015-08-27 17:34:54 -0700498 flpHardwareProvider.cleanup();
499 }
500 }
501
502 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700503 * Makes a list of userids that are related to the current user. This is
504 * relevant when using managed profiles. Otherwise the list only contains
505 * the current user.
506 *
507 * @param currentUserId the current user, who might have an alter-ego.
508 */
509 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700510 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700511 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700512 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700513 }
514 }
515
516 /**
517 * Checks if the specified userId matches any of the current foreground
518 * users stored in mCurrentUserProfiles.
519 */
520 private boolean isCurrentProfile(int userId) {
521 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700522 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700523 }
524 }
525
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500526 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
527 PackageManager pm = mContext.getPackageManager();
528 String systemPackageName = mContext.getPackageName();
529 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
530
531 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
532 new Intent(FUSED_LOCATION_SERVICE_ACTION),
533 PackageManager.GET_META_DATA, mCurrentUserId);
534 for (ResolveInfo rInfo : rInfos) {
535 String packageName = rInfo.serviceInfo.packageName;
536
537 // Check that the signature is in the list of supported sigs. If it's not in
538 // this list the standard provider binding logic won't bind to it.
539 try {
540 PackageInfo pInfo;
541 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
542 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
543 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
544 ", but has wrong signature, ignoring");
545 continue;
546 }
547 } catch (NameNotFoundException e) {
548 Log.e(TAG, "missing package: " + packageName);
549 continue;
550 }
551
552 // Get the version info
553 if (rInfo.serviceInfo.metaData == null) {
554 Log.w(TAG, "Found fused provider without metadata: " + packageName);
555 continue;
556 }
557
558 int version = rInfo.serviceInfo.metaData.getInt(
559 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
560 if (version == 0) {
561 // This should be the fallback fused location provider.
562
563 // Make sure it's in the system partition.
564 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
565 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
566 continue;
567 }
568
569 // Check that the fallback is signed the same as the OS
570 // as a proxy for coreApp="true"
571 if (pm.checkSignatures(systemPackageName, packageName)
572 != PackageManager.SIGNATURE_MATCH) {
gomo48f1a642017-11-10 20:35:46 -0800573 if (D) {
574 Log.d(TAG, "Fallback candidate not signed the same as system: "
575 + packageName);
576 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500577 continue;
578 }
579
580 // Found a valid fallback.
581 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
582 return;
583 } else {
584 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
585 }
586 }
587
588 throw new IllegalStateException("Unable to find a fused location provider that is in the "
589 + "system partition with version 0 and signed with the platform certificate. "
590 + "Such a package is needed to provide a default fused location provider in the "
591 + "event that no other fused location provider has been installed or is currently "
592 + "available. For example, coreOnly boot mode when decrypting the data "
593 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
594 }
595
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700596 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700597 // create a passive location provider, which is always enabled
598 PassiveProvider passiveProvider = new PassiveProvider(this);
599 addProviderLocked(passiveProvider);
600 mEnabledProviders.add(passiveProvider.getName());
601 mPassiveProvider = passiveProvider;
602
Lifu Tang30f95a72016-01-07 23:20:38 -0800603 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700604 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800605 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700606 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800607 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Wyatt Rileycf879db2017-01-12 13:57:38 -0800608 mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
Siddharth Raybb608c82017-03-16 11:33:34 -0700609 mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800610 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
611 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
612 addProviderLocked(gnssProvider);
613 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800614 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
615 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800616 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700617 }
618
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700619 /*
620 Load package name(s) containing location provider support.
621 These packages can contain services implementing location providers:
622 Geocoder Provider, Network Location Provider, and
623 Fused Location Provider. They will each be searched for
624 service components implementing these providers.
625 The location framework also has support for installation
626 of new location providers at run-time. The new package does not
627 have to be explicitly listed here, however it must have a signature
628 that matches the signature of at least one package on this list.
629 */
630 Resources resources = mContext.getResources();
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800631 ArrayList<String> providerPackageNames = new ArrayList<>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500632 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700633 com.android.internal.R.array.config_locationProviderPackageNames);
gomo48f1a642017-11-10 20:35:46 -0800634 if (D) {
635 Log.d(TAG, "certificates for location providers pulled from: " +
636 Arrays.toString(pkgs));
637 }
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500638 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
639
640 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700641
642 // bind to network provider
643 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
644 mContext,
645 LocationManager.NETWORK_PROVIDER,
646 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700647 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
648 com.android.internal.R.string.config_networkLocationProviderPackageName,
649 com.android.internal.R.array.config_locationProviderPackageNames,
650 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700651 if (networkProvider != null) {
652 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
653 mProxyProviders.add(networkProvider);
654 addProviderLocked(networkProvider);
655 } else {
gomo48f1a642017-11-10 20:35:46 -0800656 Slog.w(TAG, "no network location provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700657 }
658
659 // bind to fused provider
660 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
661 mContext,
662 LocationManager.FUSED_PROVIDER,
663 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700664 com.android.internal.R.bool.config_enableFusedLocationOverlay,
665 com.android.internal.R.string.config_fusedLocationProviderPackageName,
666 com.android.internal.R.array.config_locationProviderPackageNames,
667 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700668 if (fusedLocationProvider != null) {
669 addProviderLocked(fusedLocationProvider);
670 mProxyProviders.add(fusedLocationProvider);
671 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700672 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700673 } else {
674 Slog.e(TAG, "no fused location provider found",
675 new IllegalStateException("Location service needs a fused location provider"));
676 }
677
678 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700679 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
680 com.android.internal.R.bool.config_enableGeocoderOverlay,
681 com.android.internal.R.string.config_geocoderProviderPackageName,
682 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800683 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700684 if (mGeocodeProvider == null) {
gomo48f1a642017-11-10 20:35:46 -0800685 Slog.e(TAG, "no geocoder provider found");
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700686 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700687
destradaaa4fa3b52014-07-09 10:46:39 -0700688 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700689 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
690 // exception, so make sure we only do that when supported
691 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700692 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700693 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700694 FusedProxy fusedProxy = FusedProxy.createAndBind(
695 mContext,
696 mLocationHandler,
697 flpHardwareProvider.getLocationHardware(),
698 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
699 com.android.internal.R.string.config_hardwareFlpPackageName,
700 com.android.internal.R.array.config_locationProviderPackageNames);
701 if (fusedProxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700702 Slog.d(TAG, "Unable to bind FusedProxy.");
destradaaf9a274c2014-07-25 15:11:56 -0700703 }
destradaacfbdcd22014-04-30 11:29:11 -0700704 } else {
destradaabeea4422014-07-30 18:17:21 -0700705 flpHardwareProvider = null;
destradaa6b4893a2016-05-03 15:33:43 -0700706 Slog.d(TAG, "FLP HAL not supported");
destradaaf9a274c2014-07-25 15:11:56 -0700707 }
708
709 // bind to geofence provider
710 GeofenceProxy provider = GeofenceProxy.createAndBind(
gomo48f1a642017-11-10 20:35:46 -0800711 mContext, com.android.internal.R.bool.config_enableGeofenceOverlay,
destradaaf9a274c2014-07-25 15:11:56 -0700712 com.android.internal.R.string.config_geofenceProviderPackageName,
713 com.android.internal.R.array.config_locationProviderPackageNames,
714 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700715 mGpsGeofenceProxy,
destradaabeea4422014-07-30 18:17:21 -0700716 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700717 if (provider == null) {
gomo48f1a642017-11-10 20:35:46 -0800718 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700719 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900720
destradaa6e2fe752015-06-23 17:25:53 -0700721 // bind to hardware activity recognition
722 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
723 ActivityRecognitionHardware activityRecognitionHardware = null;
724 if (activityRecognitionHardwareIsSupported) {
725 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700726 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700727 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700728 }
destradaa6e2fe752015-06-23 17:25:53 -0700729 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
730 mContext,
731 mLocationHandler,
732 activityRecognitionHardwareIsSupported,
733 activityRecognitionHardware,
734 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
735 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
736 com.android.internal.R.array.config_locationProviderPackageNames);
737 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700738 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700739 }
destradaaa4fa3b52014-07-09 10:46:39 -0700740
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900741 String[] testProviderStrings = resources.getStringArray(
742 com.android.internal.R.array.config_testLocationProviders);
743 for (String testProviderString : testProviderStrings) {
744 String fragments[] = testProviderString.split(",");
745 String name = fragments[0].trim();
746 if (mProvidersByName.get(name) != null) {
747 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
748 }
749 ProviderProperties properties = new ProviderProperties(
750 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
751 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
752 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
753 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
754 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
755 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
756 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
757 Integer.parseInt(fragments[8]) /* powerRequirement */,
758 Integer.parseInt(fragments[9]) /* accuracy */);
759 addTestProviderLocked(name, properties);
760 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700761 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800763 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700764 * Called when the device's active user changes.
gomo48f1a642017-11-10 20:35:46 -0800765 *
Victoria Lease38389b62012-09-30 11:44:22 -0700766 * @param userId the new active user's UserId
767 */
768 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800769 if (mCurrentUserId == userId) {
770 return;
771 }
Victoria Lease83762d22012-10-03 13:51:17 -0700772 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800773 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700774 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700775 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700776 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700777 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700778 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700779 }
Victoria Lease38389b62012-09-30 11:44:22 -0700780 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700781 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700782 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700783 }
784 }
785
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800786 private static final class Identity {
787 final int mUid;
788 final int mPid;
789 final String mPackageName;
790
791 Identity(int uid, int pid, String packageName) {
792 mUid = uid;
793 mPid = pid;
794 mPackageName = packageName;
795 }
796 }
797
Victoria Lease38389b62012-09-30 11:44:22 -0700798 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800799 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
800 * location updates.
801 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700802 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800803 final Identity mIdentity;
Victoria Lease37425c32012-10-16 16:08:48 -0700804 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800806 final ILocationListener mListener;
807 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700808 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700809 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800810 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700811
gomo48f1a642017-11-10 20:35:46 -0800812 final HashMap<String, UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700813
David Christie0b837452013-07-29 16:02:13 -0700814 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700815 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700816 // True if app ops has started monitoring this receiver for high power (gps) locations.
817 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700818 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700819 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800820
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700821 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700822 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800823 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800824 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700825 if (listener != null) {
826 mKey = listener.asBinder();
827 } else {
828 mKey = intent;
829 }
Victoria Lease37425c32012-10-16 16:08:48 -0700830 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800831 mIdentity = new Identity(uid, pid, packageName);
David Christie82edc9b2013-07-19 11:31:42 -0700832 if (workSource != null && workSource.size() <= 0) {
833 workSource = null;
834 }
835 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700836 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700837
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700838 updateMonitoring(true);
839
Victoria Lease0aa28602013-05-29 15:28:26 -0700840 // construct/configure wakelock
841 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700842 if (workSource == null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800843 workSource = new WorkSource(mIdentity.mUid, mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -0700844 }
845 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 }
847
848 @Override
849 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800850 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 }
852
853 @Override
854 public int hashCode() {
855 return mKey.hashCode();
856 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400857
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 @Override
859 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700860 StringBuilder s = new StringBuilder();
861 s.append("Reciever[");
862 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800863 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700864 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700866 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700868 for (String p : mUpdateRecords.keySet()) {
869 s.append(" ").append(mUpdateRecords.get(p).toString());
870 }
871 s.append("]");
872 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 }
874
David Christie15b31912013-08-13 15:54:32 -0700875 /**
876 * Update AppOp monitoring for this receiver.
877 *
878 * @param allow If true receiver is currently active, if false it's been removed.
879 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700880 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700881 if (mHideFromAppOps) {
882 return;
883 }
884
David Christie15b31912013-08-13 15:54:32 -0700885 boolean requestingLocation = false;
886 boolean requestingHighPowerLocation = false;
887 if (allow) {
888 // See if receiver has any enabled update records. Also note if any update records
889 // are high power (has a high power provider with an interval under a threshold).
890 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
891 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
892 requestingLocation = true;
893 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800894 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700895 ProviderProperties properties = locationProvider != null
896 ? locationProvider.getProperties() : null;
897 if (properties != null
898 && properties.mPowerRequirement == Criteria.POWER_HIGH
899 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
900 requestingHighPowerLocation = true;
901 break;
902 }
903 }
904 }
905 }
906
David Christie0b837452013-07-29 16:02:13 -0700907 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700908 mOpMonitoring = updateMonitoring(
909 requestingLocation,
910 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700911 AppOpsManager.OP_MONITOR_LOCATION);
912
913 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700914 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700915 mOpHighPowerMonitoring = updateMonitoring(
916 requestingHighPowerLocation,
917 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700918 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700919 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700920 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700921 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
922 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
923 }
David Christie0b837452013-07-29 16:02:13 -0700924 }
925
926 /**
927 * Update AppOps monitoring for a single location request and op type.
928 *
gomo48f1a642017-11-10 20:35:46 -0800929 * @param allowMonitoring True if monitoring is allowed for this request/op.
David Christie0b837452013-07-29 16:02:13 -0700930 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
gomo48f1a642017-11-10 20:35:46 -0800931 * @param op AppOps code for the op to update.
David Christie0b837452013-07-29 16:02:13 -0700932 * @return True if monitoring is on for this request/op after updating.
933 */
934 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
935 int op) {
936 if (!currentlyMonitoring) {
937 if (allowMonitoring) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800938 return mAppOps.startOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700939 == AppOpsManager.MODE_ALLOWED;
940 }
941 } else {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800942 if (!allowMonitoring
943 || mAppOps.checkOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700944 != AppOpsManager.MODE_ALLOWED) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800945 mAppOps.finishOp(op, mIdentity.mUid, mIdentity.mPackageName);
David Christie0b837452013-07-29 16:02:13 -0700946 return false;
947 }
948 }
949
950 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700951 }
952
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 public boolean isListener() {
954 return mListener != null;
955 }
956
957 public boolean isPendingIntent() {
958 return mPendingIntent != null;
959 }
960
961 public ILocationListener getListener() {
962 if (mListener != null) {
963 return mListener;
964 }
965 throw new IllegalStateException("Request for non-existent listener");
966 }
967
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
969 if (mListener != null) {
970 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700971 synchronized (this) {
972 // synchronize to ensure incrementPendingBroadcastsLocked()
973 // is called before decrementPendingBroadcasts()
974 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700975 // call this after broadcasting so we do not increment
976 // if we throw an exeption.
977 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700978 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800979 } catch (RemoteException e) {
980 return false;
981 }
982 } else {
983 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800984 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
986 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700987 synchronized (this) {
988 // synchronize to ensure incrementPendingBroadcastsLocked()
989 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700990 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700991 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700992 // call this after broadcasting so we do not increment
993 // if we throw an exeption.
994 incrementPendingBroadcastsLocked();
995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 } catch (PendingIntent.CanceledException e) {
997 return false;
998 }
999 }
1000 return true;
1001 }
1002
1003 public boolean callLocationChangedLocked(Location location) {
1004 if (mListener != null) {
1005 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001006 synchronized (this) {
1007 // synchronize to ensure incrementPendingBroadcastsLocked()
1008 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001009 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -07001010 // call this after broadcasting so we do not increment
1011 // if we throw an exeption.
1012 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001013 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 } catch (RemoteException e) {
1015 return false;
1016 }
1017 } else {
1018 Intent locationChanged = new Intent();
gomo48f1a642017-11-10 20:35:46 -08001019 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED,
1020 new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001022 synchronized (this) {
1023 // synchronize to ensure incrementPendingBroadcastsLocked()
1024 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001025 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001026 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001027 // call this after broadcasting so we do not increment
1028 // if we throw an exeption.
1029 incrementPendingBroadcastsLocked();
1030 }
1031 } catch (PendingIntent.CanceledException e) {
1032 return false;
1033 }
1034 }
1035 return true;
1036 }
1037
1038 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001039 // First update AppOp monitoring.
1040 // An app may get/lose location access as providers are enabled/disabled.
1041 updateMonitoring(true);
1042
Mike Lockwood48f17512009-04-23 09:12:08 -07001043 if (mListener != null) {
1044 try {
1045 synchronized (this) {
1046 // synchronize to ensure incrementPendingBroadcastsLocked()
1047 // is called before decrementPendingBroadcasts()
1048 if (enabled) {
1049 mListener.onProviderEnabled(provider);
1050 } else {
1051 mListener.onProviderDisabled(provider);
1052 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001053 // call this after broadcasting so we do not increment
1054 // if we throw an exeption.
1055 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001056 }
1057 } catch (RemoteException e) {
1058 return false;
1059 }
1060 } else {
1061 Intent providerIntent = new Intent();
1062 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1063 try {
1064 synchronized (this) {
1065 // synchronize to ensure incrementPendingBroadcastsLocked()
1066 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001067 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001068 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001069 // call this after broadcasting so we do not increment
1070 // if we throw an exeption.
1071 incrementPendingBroadcastsLocked();
1072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 } catch (PendingIntent.CanceledException e) {
1074 return false;
1075 }
1076 }
1077 return true;
1078 }
1079
Nick Pellyf1be6862012-05-15 10:53:42 -07001080 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001082 if (D) Log.d(TAG, "Location listener died");
1083
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001084 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 removeUpdatesLocked(this);
1086 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001087 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001088 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001089 }
1090 }
1091
Nick Pellye0fd6932012-07-11 10:26:13 -07001092 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001093 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1094 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001095 synchronized (this) {
1096 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001097 }
1098 }
1099
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001100 // this must be called while synchronized by caller in a synchronized block
1101 // containing the sending of the broadcaset
1102 private void incrementPendingBroadcastsLocked() {
1103 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001104 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001105 }
1106 }
1107
1108 private void decrementPendingBroadcastsLocked() {
1109 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001110 if (mWakeLock.isHeld()) {
1111 mWakeLock.release();
1112 }
1113 }
1114 }
1115
1116 public void clearPendingBroadcastsLocked() {
1117 if (mPendingBroadcasts > 0) {
1118 mPendingBroadcasts = 0;
1119 if (mWakeLock.isHeld()) {
1120 mWakeLock.release();
1121 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001122 }
1123 }
1124 }
1125
Nick Pellye0fd6932012-07-11 10:26:13 -07001126 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001127 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001128 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001129 //the receiver list if it is not found. If it is not found then the
1130 //LocationListener was removed when it had a pending broadcast and should
1131 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001132 synchronized (mLock) {
1133 IBinder binder = listener.asBinder();
1134 Receiver receiver = mReceivers.get(binder);
1135 if (receiver != null) {
1136 synchronized (receiver) {
1137 // so wakelock calls will succeed
1138 long identity = Binder.clearCallingIdentity();
1139 receiver.decrementPendingBroadcastsLocked();
1140 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001141 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001142 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 }
1144 }
1145
Lifu Tang82f893d2016-01-21 18:15:33 -08001146 /**
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001147 * Returns the year of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001148 */
1149 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001150 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001151 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001152 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001153 } else {
1154 return 0;
1155 }
1156 }
1157
Wyatt Rileyd87cf912017-12-05 09:31:52 -08001158
1159 /**
1160 * Returns the model name of the GNSS hardware.
1161 */
1162 @Override
1163 public String getGnssHardwareModelName() {
1164 if (mGnssSystemInfoProvider != null) {
1165 return mGnssSystemInfoProvider.getGnssHardwareModelName();
1166 } else {
1167 return LocationManager.GNSS_HARDWARE_MODEL_NAME_UNKNOWN;
1168 }
1169 }
1170
Wyatt Rileycf879db2017-01-12 13:57:38 -08001171 /**
1172 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1173 * (try to) access GNSS information at this layer.
1174 */
1175 private boolean hasGnssPermissions(String packageName) {
1176 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1177 checkResolutionLevelIsSufficientForProviderUse(
1178 allowedResolutionLevel,
1179 LocationManager.GPS_PROVIDER);
1180
1181 int pid = Binder.getCallingPid();
1182 int uid = Binder.getCallingUid();
1183 long identity = Binder.clearCallingIdentity();
1184 boolean hasLocationAccess;
1185 try {
1186 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1187 } finally {
1188 Binder.restoreCallingIdentity(identity);
1189 }
1190
1191 return hasLocationAccess;
1192 }
1193
1194 /**
1195 * Returns the GNSS batching size, if available.
1196 */
1197 @Override
1198 public int getGnssBatchSize(String packageName) {
1199 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1200 "Location Hardware permission not granted to access hardware batching");
1201
1202 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
1203 return mGnssBatchingProvider.getSize();
1204 } else {
1205 return 0;
1206 }
1207 }
1208
1209 /**
1210 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1211 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1212 */
1213 @Override
1214 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1215 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1216 "Location Hardware permission not granted to access hardware batching");
1217
1218 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1219 return false;
1220 }
1221
1222 mGnssBatchingCallback = callback;
1223 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1224 try {
1225 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1226 } catch (RemoteException e) {
1227 // if the remote process registering the listener is already dead, just swallow the
1228 // exception and return
1229 Log.e(TAG, "Remote listener already died.", e);
1230 return false;
1231 }
1232
1233 return true;
1234 }
1235
1236 private class LinkedCallback implements IBinder.DeathRecipient {
1237 private final IBatchedLocationCallback mCallback;
1238
1239 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1240 mCallback = callback;
1241 }
1242
1243 @NonNull
1244 public IBatchedLocationCallback getUnderlyingListener() {
1245 return mCallback;
1246 }
1247
1248 @Override
1249 public void binderDied() {
1250 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1251 stopGnssBatch();
1252 removeGnssBatchingCallback();
1253 }
1254 }
1255
1256 /**
1257 * Removes callback for GNSS batching
1258 */
1259 @Override
1260 public void removeGnssBatchingCallback() {
1261 try {
1262 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1263 0 /* flags */);
1264 } catch (NoSuchElementException e) {
1265 // if the death callback isn't connected (it should be...), log error, swallow the
1266 // exception and return
1267 Log.e(TAG, "Couldn't unlink death callback.", e);
1268 }
1269 mGnssBatchingCallback = null;
1270 mGnssBatchingDeathCallback = null;
1271 }
1272
1273
1274 /**
1275 * Starts GNSS batching, if available.
1276 */
1277 @Override
1278 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1279 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1280 "Location Hardware permission not granted to access hardware batching");
1281
1282 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1283 return false;
1284 }
1285
1286 if (mGnssBatchingInProgress) {
1287 // Current design does not expect multiple starts to be called repeatedly
1288 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1289 // Try to clean up anyway, and continue
1290 stopGnssBatch();
1291 }
1292
1293 mGnssBatchingInProgress = true;
1294 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1295 }
1296
1297 /**
1298 * Flushes a GNSS batch in progress
1299 */
1300 @Override
1301 public void flushGnssBatch(String packageName) {
1302 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1303 "Location Hardware permission not granted to access hardware batching");
1304
1305 if (!hasGnssPermissions(packageName)) {
1306 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1307 return;
1308 }
1309
1310 if (!mGnssBatchingInProgress) {
1311 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1312 }
1313
1314 if (mGnssBatchingProvider != null) {
gomo48f1a642017-11-10 20:35:46 -08001315 mGnssBatchingProvider.flush();
Wyatt Rileycf879db2017-01-12 13:57:38 -08001316 }
1317 }
1318
1319 /**
1320 * Stops GNSS batching
1321 */
1322 @Override
1323 public boolean stopGnssBatch() {
1324 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1325 "Location Hardware permission not granted to access hardware batching");
1326
1327 if (mGnssBatchingProvider != null) {
1328 mGnssBatchingInProgress = false;
1329 return mGnssBatchingProvider.stop();
gomo48f1a642017-11-10 20:35:46 -08001330 } else {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001331 return false;
1332 }
1333 }
1334
1335 @Override
1336 public void reportLocationBatch(List<Location> locations) {
1337 checkCallerIsProvider();
1338
1339 // Currently used only for GNSS locations - update permissions check if changed
1340 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1341 if (mGnssBatchingCallback == null) {
1342 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1343 return;
1344 }
1345 try {
1346 mGnssBatchingCallback.onLocationBatch(locations);
1347 } catch (RemoteException e) {
1348 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1349 }
1350 } else {
1351 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1352 }
1353 }
1354
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001355 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001356 mProviders.add(provider);
1357 mProvidersByName.put(provider.getName(), provider);
1358 }
1359
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001360 private void removeProviderLocked(LocationProviderInterface provider) {
1361 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001362 mProviders.remove(provider);
1363 mProvidersByName.remove(provider.getName());
1364 }
1365
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001366 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001367 * Returns "true" if access to the specified location provider is allowed by the current
1368 * user's settings. Access to all location providers is forbidden to non-location-provider
1369 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001370 *
1371 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001372 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001373 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 if (mEnabledProviders.contains(provider)) {
1375 return true;
1376 }
1377 if (mDisabledProviders.contains(provider)) {
1378 return false;
1379 }
1380 // Use system settings
1381 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382
Victoria Leaseb711d572012-10-02 13:14:11 -07001383 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001386 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001387 * Returns "true" if access to the specified location provider is allowed by the specified
1388 * user's settings. Access to all location providers is forbidden to non-location-provider
1389 * processes belonging to background users.
1390 *
1391 * @param provider the name of the location provider
gomo48f1a642017-11-10 20:35:46 -08001392 * @param uid the requestor's UID
Victoria Lease09eeaec2013-02-05 11:34:13 -08001393 */
1394 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001395 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001396 return false;
1397 }
1398 return isAllowedByCurrentUserSettingsLocked(provider);
1399 }
1400
1401 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001402 * Returns the permission string associated with the specified resolution level.
1403 *
1404 * @param resolutionLevel the resolution level
1405 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001406 */
Victoria Lease37425c32012-10-16 16:08:48 -07001407 private String getResolutionPermission(int resolutionLevel) {
1408 switch (resolutionLevel) {
1409 case RESOLUTION_LEVEL_FINE:
1410 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1411 case RESOLUTION_LEVEL_COARSE:
1412 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1413 default:
1414 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001416 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001417
Victoria Leaseda479c52012-10-15 15:24:16 -07001418 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001419 * Returns the resolution level allowed to the given PID/UID pair.
1420 *
1421 * @param pid the PID
1422 * @param uid the UID
1423 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001424 */
Victoria Lease37425c32012-10-16 16:08:48 -07001425 private int getAllowedResolutionLevel(int pid, int uid) {
1426 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1427 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1428 return RESOLUTION_LEVEL_FINE;
1429 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1430 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1431 return RESOLUTION_LEVEL_COARSE;
1432 } else {
1433 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001434 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001435 }
1436
1437 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001438 * Returns the resolution level allowed to the caller
1439 *
1440 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001441 */
Victoria Lease37425c32012-10-16 16:08:48 -07001442 private int getCallerAllowedResolutionLevel() {
1443 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1444 }
1445
1446 /**
1447 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1448 *
1449 * @param allowedResolutionLevel resolution level allowed to caller
1450 */
1451 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1452 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001453 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456
Victoria Lease37425c32012-10-16 16:08:48 -07001457 /**
1458 * Return the minimum resolution level required to use the specified location provider.
1459 *
1460 * @param provider the name of the location provider
1461 * @return minimum resolution level required for provider
1462 */
1463 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001464 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1465 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1466 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001467 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001468 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1469 LocationManager.FUSED_PROVIDER.equals(provider)) {
1470 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001471 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001472 } else {
1473 // mock providers
1474 LocationProviderInterface lp = mMockProviders.get(provider);
1475 if (lp != null) {
1476 ProviderProperties properties = lp.getProperties();
1477 if (properties != null) {
1478 if (properties.mRequiresSatellite) {
1479 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001480 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001481 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1482 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001483 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001484 }
1485 }
1486 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001487 }
Victoria Lease37425c32012-10-16 16:08:48 -07001488 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001489 }
1490
Victoria Lease37425c32012-10-16 16:08:48 -07001491 /**
1492 * Throw SecurityException if specified resolution level is insufficient to use the named
1493 * location provider.
1494 *
1495 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001496 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001497 */
1498 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1499 String providerName) {
1500 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1501 if (allowedResolutionLevel < requiredResolutionLevel) {
1502 switch (requiredResolutionLevel) {
1503 case RESOLUTION_LEVEL_FINE:
1504 throw new SecurityException("\"" + providerName + "\" location provider " +
1505 "requires ACCESS_FINE_LOCATION permission.");
1506 case RESOLUTION_LEVEL_COARSE:
1507 throw new SecurityException("\"" + providerName + "\" location provider " +
1508 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1509 default:
1510 throw new SecurityException("Insufficient permission for \"" + providerName +
1511 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001512 }
1513 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001514 }
1515
David Christie82edc9b2013-07-19 11:31:42 -07001516 /**
1517 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1518 * for battery).
1519 */
David Christie40e57822013-07-30 11:36:48 -07001520 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1523 }
1524
David Christie40e57822013-07-30 11:36:48 -07001525 private void checkUpdateAppOpsAllowed() {
1526 mContext.enforceCallingOrSelfPermission(
1527 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1528 }
1529
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001530 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001531 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1532 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001533 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001534 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001535 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001536 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001537 }
1538 return -1;
1539 }
1540
David Christieb870dbf2015-06-22 12:42:53 -07001541 boolean reportLocationAccessNoThrow(
1542 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001543 int op = resolutionLevelToOp(allowedResolutionLevel);
1544 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001545 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1546 return false;
1547 }
1548 }
David Christieb870dbf2015-06-22 12:42:53 -07001549
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001550 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001551 }
1552
David Christieb870dbf2015-06-22 12:42:53 -07001553 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001554 int op = resolutionLevelToOp(allowedResolutionLevel);
1555 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001556 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1557 return false;
1558 }
1559 }
David Christieb870dbf2015-06-22 12:42:53 -07001560
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001561 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001562 }
1563
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001564 /**
1565 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001566 * fused, also including ones that are not permitted to
1567 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001568 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001569 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 public List<String> getAllProviders() {
destradaab376b3b2017-09-06 14:09:42 -07001571 List<String> out = getProviders(null /*criteria*/, false /*enabledOnly*/);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001572 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 return out;
1574 }
1575
Mike Lockwood03ca2162010-04-01 08:10:09 -07001576 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001577 * Return all providers by name, that match criteria and are optionally
1578 * enabled.
1579 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001580 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001581 @Override
1582 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001583 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001584 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001585 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001586 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001587 try {
1588 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001589 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001590 for (LocationProviderInterface provider : mProviders) {
1591 String name = provider.getName();
1592 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001593 continue;
1594 }
Victoria Lease37425c32012-10-16 16:08:48 -07001595 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001596 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001597 continue;
1598 }
1599 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1600 name, provider.getProperties(), criteria)) {
1601 continue;
1602 }
1603 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001604 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001605 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001606 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001607 } finally {
1608 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001609 }
1610
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001611 if (D) Log.d(TAG, "getProviders()=" + out);
1612 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001613 }
1614
1615 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001616 * Return the name of the best provider given a Criteria object.
1617 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001618 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001619 * has been deprecated as well. So this method now uses
1620 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001621 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001622 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001623 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001624 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001625
1626 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001627 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001628 result = pickBest(providers);
1629 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1630 return result;
1631 }
1632 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001633 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001634 result = pickBest(providers);
1635 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1636 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001637 }
1638
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001639 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001640 return null;
1641 }
1642
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001643 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001644 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001645 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001646 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1647 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001648 } else {
1649 return providers.get(0);
1650 }
1651 }
1652
Nick Pellye0fd6932012-07-11 10:26:13 -07001653 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001654 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1655 LocationProviderInterface p = mProvidersByName.get(provider);
1656 if (p == null) {
1657 throw new IllegalArgumentException("provider=" + provider);
1658 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001659
1660 boolean result = LocationProvider.propertiesMeetCriteria(
1661 p.getName(), p.getProperties(), criteria);
1662 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1663 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001664 }
1665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001667 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001668 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001669 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 boolean isEnabled = p.isEnabled();
1671 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001672 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001674 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001675 // If any provider has been disabled, clear all last locations for all providers.
1676 // This is to be on the safe side in case a provider has location derived from
1677 // this disabled provider.
1678 mLastLocation.clear();
1679 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001680 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001682 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001683 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001685 }
1686 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001687 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1688 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001689 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1690 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692 }
1693
Amith Yamasanib27528d2014-06-05 15:02:10 -07001694 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 int listeners = 0;
1696
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001697 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001698 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001699
1700 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1703 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001704 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001705 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001706 // Sends a notification message to the receiver
1707 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1708 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001709 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001710 }
1711 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001713 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001715 }
1716 }
1717
1718 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001719 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 removeUpdatesLocked(deadReceivers.get(i));
1721 }
1722 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724 if (enabled) {
1725 p.enable();
1726 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001727 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
1729 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001731 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001732 }
1733
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001734 private void applyRequirementsLocked(String provider) {
1735 LocationProviderInterface p = mProvidersByName.get(provider);
1736 if (p == null) return;
1737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001739 WorkSource worksource = new WorkSource();
1740 ProviderRequest providerRequest = new ProviderRequest();
1741
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001742 ContentResolver resolver = mContext.getContentResolver();
1743 long backgroundThrottleInterval = Settings.Global.getLong(
1744 resolver,
1745 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1746 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001747 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001748
gomo48f1a642017-11-10 20:35:46 -08001749 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001751 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001752 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001753 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001754 record.mReceiver.mIdentity.mPid,
1755 record.mReceiver.mIdentity.mUid,
1756 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001757 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001758 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001759 long interval = locationRequest.getInterval();
1760
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001761 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001762 if (!record.mIsForegroundUid) {
1763 interval = Math.max(interval, backgroundThrottleInterval);
1764 }
1765 if (interval != locationRequest.getInterval()) {
1766 locationRequest = new LocationRequest(locationRequest);
1767 locationRequest.setInterval(interval);
1768 }
1769 }
1770
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001771 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001772 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001773 if (!locationRequest.isLowPowerMode()) {
1774 providerRequest.lowPowerMode = false;
1775 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001776 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001777 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001778 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001779 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001780 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001781 }
1782 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001783
1784 if (providerRequest.reportLocation) {
1785 // calculate who to blame for power
1786 // This is somewhat arbitrary. We pick a threshold interval
1787 // that is slightly higher that the minimum interval, and
1788 // spread the blame across all applications with a request
1789 // under that threshold.
1790 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1791 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001792 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001793 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001794
1795 // Don't assign battery blame for update records whose
1796 // client has no permission to receive location data.
1797 if (!providerRequest.locationRequests.contains(locationRequest)) {
1798 continue;
1799 }
1800
Victoria Leaseb711d572012-10-02 13:14:11 -07001801 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001802 if (record.mReceiver.mWorkSource != null
1803 && record.mReceiver.mWorkSource.size() > 0
1804 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001805 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001806 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001807 worksource.add(record.mReceiver.mWorkSource);
1808 } else {
1809 // Assign blame to caller.
1810 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001811 record.mReceiver.mIdentity.mUid,
1812 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001813 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001814 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001815 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001817 }
1818 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001819
1820 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1821 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001824 @Override
1825 public String[] getBackgroundThrottlingWhitelist() {
1826 synchronized (mLock) {
1827 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001828 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001829 }
1830 }
1831
1832 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001833 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001834 mContext.getContentResolver(),
1835 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001836 if (setting == null) {
1837 setting = "";
1838 }
1839
1840 mBackgroundThrottlePackageWhitelist.clear();
1841 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001842 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001843 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001844 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001845 }
1846
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001847 private boolean isThrottlingExemptLocked(Identity identity) {
1848 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001849 return true;
1850 }
1851
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001852 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001853 return true;
1854 }
1855
1856 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001857 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001858 return true;
1859 }
1860 }
1861
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001862 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001863 }
1864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001865 private class UpdateRecord {
1866 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001867 final LocationRequest mRealRequest; // original request from client
1868 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001870 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001871 Location mLastFixBroadcast;
1872 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001873
1874 /**
1875 * Note: must be constructed with lock held.
1876 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001877 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001879 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001880 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001882 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001883 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001884
1885 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1886 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001887 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 mRecordsByProvider.put(provider, records);
1889 }
1890 if (!records.contains(this)) {
1891 records.add(this);
1892 }
David Christie2ff96af2014-01-30 16:09:37 -08001893
1894 // Update statistics for historical location requests by package/provider
1895 mRequestStatistics.startRequesting(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001896 mReceiver.mIdentity.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001897 }
1898
1899 /**
David Christie2ff96af2014-01-30 16:09:37 -08001900 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001902 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001903 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001904
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001905 // remove from mRecordsByProvider
1906 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1907 if (globalRecords != null) {
1908 globalRecords.remove(this);
1909 }
1910
1911 if (!removeReceiver) return; // the caller will handle the rest
1912
1913 // remove from Receiver#mUpdateRecords
1914 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1915 if (receiverRecords != null) {
1916 receiverRecords.remove(this.mProvider);
1917
1918 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001919 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001920 removeUpdatesLocked(mReceiver);
1921 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001923 }
1924
1925 @Override
1926 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001927 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001928 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1929 : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001930 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001931 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 }
1933
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001934 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001935 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001936 IBinder binder = listener.asBinder();
1937 Receiver receiver = mReceivers.get(binder);
1938 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001939 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1940 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001941 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001942 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001943 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001944 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001945 return null;
1946 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001947 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001948 }
1949 return receiver;
1950 }
1951
David Christie82edc9b2013-07-19 11:31:42 -07001952 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001953 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001954 Receiver receiver = mReceivers.get(intent);
1955 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001956 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1957 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001958 mReceivers.put(intent, receiver);
1959 }
1960 return receiver;
1961 }
1962
Victoria Lease37425c32012-10-16 16:08:48 -07001963 /**
1964 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1965 * and consistency requirements.
1966 *
1967 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001968 * @return a version of request that meets the given resolution and consistency requirements
1969 * @hide
1970 */
gomo48f1a642017-11-10 20:35:46 -08001971 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
1972 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07001973 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08001974 if (!callerHasLocationHardwarePermission) {
1975 // allow setting low power mode only for callers with location hardware permission
1976 sanitizedRequest.setLowPowerMode(false);
1977 }
Victoria Lease37425c32012-10-16 16:08:48 -07001978 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1979 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001980 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001981 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001982 break;
1983 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001984 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001985 break;
1986 }
1987 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001988 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1989 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001990 }
Victoria Lease37425c32012-10-16 16:08:48 -07001991 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1992 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001993 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001994 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001995 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001996 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001997 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001998 }
Victoria Lease37425c32012-10-16 16:08:48 -07001999 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002000 }
2001
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002002 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002003 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002004 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002005 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002006 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002007 String[] packages = mPackageManager.getPackagesForUid(uid);
2008 if (packages == null) {
2009 throw new SecurityException("invalid UID " + uid);
2010 }
2011 for (String pkg : packages) {
2012 if (packageName.equals(pkg)) return;
2013 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002014 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002015 }
2016
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002017 private void checkPendingIntent(PendingIntent intent) {
2018 if (intent == null) {
2019 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002020 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002021 }
2022
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002023 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002024 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002025 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002026 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002027 } else if (intent != null && listener != null) {
2028 throw new IllegalArgumentException("cannot register both listener and intent");
2029 } else if (intent != null) {
2030 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002031 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002032 } else {
David Christie40e57822013-07-30 11:36:48 -07002033 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002034 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002035 }
2036
Nick Pellye0fd6932012-07-11 10:26:13 -07002037 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002038 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2039 PendingIntent intent, String packageName) {
2040 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2041 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002042 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2043 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2044 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002045 WorkSource workSource = request.getWorkSource();
2046 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07002047 checkDeviceStatsAllowed();
2048 }
2049 boolean hideFromAppOps = request.getHideFromAppOps();
2050 if (hideFromAppOps) {
2051 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002052 }
gomo48f1a642017-11-10 20:35:46 -08002053 boolean callerHasLocationHardwarePermission =
2054 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
2055 == PackageManager.PERMISSION_GRANTED;
2056 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2057 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002059 final int pid = Binder.getCallingPid();
2060 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002061 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 long identity = Binder.clearCallingIdentity();
2063 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002064 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2065 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002066 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002067
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002068 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002069 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002070 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002071 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 } finally {
2074 Binder.restoreCallingIdentity(identity);
2075 }
2076 }
2077
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002078 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2079 int pid, int uid, String packageName) {
2080 // Figure out the provider. Either its explicitly request (legacy use cases), or
2081 // use the fused provider
2082 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2083 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002084 if (name == null) {
2085 throw new IllegalArgumentException("provider name must not be null");
2086 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002087
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002088 LocationProviderInterface provider = mProvidersByName.get(name);
2089 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002090 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002091 }
2092
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002093 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002094 if (D) {
2095 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2096 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2097 + (record.mIsForegroundUid ? "foreground" : "background")
2098 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002099 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002100 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002101
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002102 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2103 if (oldRecord != null) {
2104 oldRecord.disposeLocked(false);
2105 }
2106
Victoria Lease09eeaec2013-02-05 11:34:13 -08002107 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002108 if (isProviderEnabled) {
2109 applyRequirementsLocked(name);
2110 } else {
2111 // Notify the listener that updates are currently disabled
2112 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 }
David Christie0b837452013-07-29 16:02:13 -07002114 // Update the monitoring here just in case multiple location requests were added to the
2115 // same receiver (this request may be high power and the initial might not have been).
2116 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002117 }
2118
Nick Pellye0fd6932012-07-11 10:26:13 -07002119 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002120 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2121 String packageName) {
2122 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002123
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002124 final int pid = Binder.getCallingPid();
2125 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002126
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002127 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002128 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002129 boolean hideFromAppOps = false;
2130 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2131 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002132
2133 // providers may use public location API's, need to clear identity
2134 long identity = Binder.clearCallingIdentity();
2135 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002136 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002137 } finally {
2138 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002140 }
2141 }
2142
2143 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002144 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002145
2146 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2147 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2148 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002149 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002151 }
2152
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002153 receiver.updateMonitoring(false);
2154
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002155 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002156 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002157 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2158 if (oldRecords != null) {
2159 // Call dispose() on the obsolete update records.
2160 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002161 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002162 record.disposeLocked(false);
2163 }
2164 // Accumulate providers
2165 providers.addAll(oldRecords.keySet());
2166 }
2167
2168 // update provider
2169 for (String provider : providers) {
2170 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002171 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002172 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002173 }
2174
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002175 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002176 }
2177 }
2178
Dianne Hackbornc2293022013-02-06 23:14:49 -08002179 private void applyAllProviderRequirementsLocked() {
2180 for (LocationProviderInterface p : mProviders) {
2181 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002182 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002183 continue;
2184 }
2185
2186 applyRequirementsLocked(p.getName());
2187 }
2188 }
2189
Nick Pellye0fd6932012-07-11 10:26:13 -07002190 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002191 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002192 if (D) Log.d(TAG, "getLastLocation: " + request);
2193 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002194 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002195 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002196 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2197 request.getProvider());
2198 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002199
David Christieb870dbf2015-06-22 12:42:53 -07002200 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002201 final int uid = Binder.getCallingUid();
2202 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002203 try {
2204 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002205 if (D) {
2206 Log.d(TAG, "not returning last loc for blacklisted app: " +
2207 packageName);
2208 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002209 return null;
2210 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002211
David Christieb870dbf2015-06-22 12:42:53 -07002212 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002213 if (D) {
2214 Log.d(TAG, "not returning last loc for no op app: " +
2215 packageName);
2216 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002217 return null;
2218 }
2219
Victoria Leaseb711d572012-10-02 13:14:11 -07002220 synchronized (mLock) {
2221 // Figure out the provider. Either its explicitly request (deprecated API's),
2222 // or use the fused provider
2223 String name = request.getProvider();
2224 if (name == null) name = LocationManager.FUSED_PROVIDER;
2225 LocationProviderInterface provider = mProvidersByName.get(name);
2226 if (provider == null) return null;
2227
Victoria Lease09eeaec2013-02-05 11:34:13 -08002228 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002229
David Christie1b9b7b12013-04-15 15:31:11 -07002230 Location location;
2231 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2232 // Make sure that an app with coarse permissions can't get frequent location
2233 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2234 location = mLastLocationCoarseInterval.get(name);
2235 } else {
2236 location = mLastLocation.get(name);
2237 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002238 if (location == null) {
2239 return null;
2240 }
Victoria Lease37425c32012-10-16 16:08:48 -07002241 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002242 Location noGPSLocation = location.getExtraLocation(
2243 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002244 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002245 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002246 }
Victoria Lease37425c32012-10-16 16:08:48 -07002247 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002248 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002249 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002250 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002251 return null;
2252 } finally {
2253 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002254 }
2255 }
2256
2257 @Override
2258 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2259 String packageName) {
2260 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002261 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2262 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002263 checkPendingIntent(intent);
2264 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002265 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2266 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002267 // Require that caller can manage given document
2268 boolean callerHasLocationHardwarePermission =
2269 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
2270 == PackageManager.PERMISSION_GRANTED;
2271 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2272 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002273
Victoria Lease37425c32012-10-16 16:08:48 -07002274 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002275
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002276 // geo-fence manager uses the public location API, need to clear identity
2277 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002278 // TODO: http://b/23822629
2279 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002280 // temporary measure until geofences work for secondary users
2281 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2282 return;
2283 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002284 long identity = Binder.clearCallingIdentity();
2285 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002286 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2287 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002288 } finally {
2289 Binder.restoreCallingIdentity(identity);
2290 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002291 }
2292
2293 @Override
2294 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002295 checkPendingIntent(intent);
2296 checkPackageName(packageName);
2297
2298 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2299
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002300 // geo-fence manager uses the public location API, need to clear identity
2301 long identity = Binder.clearCallingIdentity();
2302 try {
2303 mGeofenceManager.removeFence(geofence, intent);
2304 } finally {
2305 Binder.restoreCallingIdentity(identity);
2306 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002307 }
2308
2309
2310 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002311 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002312 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002313 return false;
2314 }
2315
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002316 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002317 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002319 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002320 return false;
2321 }
2322 return true;
2323 }
2324
Nick Pellye0fd6932012-07-11 10:26:13 -07002325 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002326 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002327 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002328 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002329 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002330 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002331 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002332 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002333 }
2334 }
2335
Nick Pellye0fd6932012-07-11 10:26:13 -07002336 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002337 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002338 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002339 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002340 return false;
2341 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002342
2343 synchronized (mLock) {
2344 Identity callerIdentity
2345 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
2346 mGnssMeasurementsListeners.put(listener, callerIdentity);
2347 long identity = Binder.clearCallingIdentity();
2348 try {
2349 if (isThrottlingExemptLocked(callerIdentity)
2350 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002351 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002352 return mGnssMeasurementsProvider.addListener(listener);
2353 }
2354 } finally {
2355 Binder.restoreCallingIdentity(identity);
2356 }
2357
2358 return true;
2359 }
destradaaea8a8a62014-06-23 18:19:03 -07002360 }
2361
2362 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002363 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2364 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002365 synchronized (mLock) {
2366 mGnssMeasurementsListeners.remove(listener);
2367 mGnssMeasurementsProvider.removeListener(listener);
2368 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002369 }
destradaaea8a8a62014-06-23 18:19:03 -07002370 }
2371
2372 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002373 public boolean addGnssNavigationMessageListener(
2374 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002375 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002376 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002377 return false;
2378 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002379
2380 synchronized (mLock) {
2381 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002382 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002383 mGnssNavigationMessageListeners.put(listener, callerIdentity);
2384 long identity = Binder.clearCallingIdentity();
2385 try {
2386 if (isThrottlingExemptLocked(callerIdentity)
2387 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002388 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002389 return mGnssNavigationMessageProvider.addListener(listener);
2390 }
2391 } finally {
2392 Binder.restoreCallingIdentity(identity);
2393 }
2394
2395 return true;
2396 }
destradaa4b3e3932014-07-21 18:01:47 -07002397 }
2398
2399 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002400 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2401 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002402 synchronized (mLock) {
2403 mGnssNavigationMessageListeners.remove(listener);
2404 mGnssNavigationMessageProvider.removeListener(listener);
2405 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002406 }
destradaa4b3e3932014-07-21 18:01:47 -07002407 }
2408
2409 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002410 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002411 if (provider == null) {
2412 // throw NullPointerException to remain compatible with previous implementation
2413 throw new NullPointerException();
2414 }
Victoria Lease37425c32012-10-16 16:08:48 -07002415 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2416 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002419 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 != PackageManager.PERMISSION_GRANTED)) {
2421 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2422 }
2423
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002424 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002425 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002426 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002427
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002428 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 }
2430 }
2431
Nick Pellye0fd6932012-07-11 10:26:13 -07002432 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002433 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002434 if (Binder.getCallingUid() != Process.myUid()) {
2435 throw new SecurityException(
2436 "calling sendNiResponse from outside of the system is not allowed");
2437 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002438 try {
2439 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002440 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002441 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002442 return false;
2443 }
2444 }
2445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002447 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002448 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002449 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002450 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002451 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002452 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002453 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002454 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002455 }
2456
Victoria Lease37425c32012-10-16 16:08:48 -07002457 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2458 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002460 LocationProviderInterface p;
2461 synchronized (mLock) {
2462 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 }
2464
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002465 if (p == null) return null;
2466 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002467 }
2468
Jason Monkb71218a2015-06-17 14:44:39 -04002469 /**
2470 * @return null if the provider does not exist
2471 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002472 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002473 */
2474 @Override
2475 public String getNetworkProviderPackage() {
2476 LocationProviderInterface p;
2477 synchronized (mLock) {
2478 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2479 return null;
2480 }
2481 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2482 }
2483
2484 if (p instanceof LocationProviderProxy) {
2485 return ((LocationProviderProxy) p).getConnectedPackageName();
2486 }
2487 return null;
2488 }
2489
Nick Pellye0fd6932012-07-11 10:26:13 -07002490 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002491 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07002492 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2493 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002494 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2495
Victoria Lease09eeaec2013-02-05 11:34:13 -08002496 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002497 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002498 try {
2499 synchronized (mLock) {
2500 LocationProviderInterface p = mProvidersByName.get(provider);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002501 return p != null && isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07002502 }
2503 } finally {
2504 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002505 }
2506 }
2507
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002508 /**
2509 * Returns "true" if the UID belongs to a bound location provider.
2510 *
2511 * @param uid the uid
2512 * @return true if uid belongs to a bound location provider
2513 */
2514 private boolean isUidALocationProvider(int uid) {
2515 if (uid == Process.SYSTEM_UID) {
2516 return true;
2517 }
2518 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002519 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002520 }
2521 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002522 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002523 }
2524 return false;
2525 }
2526
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002527 private void checkCallerIsProvider() {
2528 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
2529 == PackageManager.PERMISSION_GRANTED) {
2530 return;
2531 }
2532
2533 // Previously we only used the INSTALL_LOCATION_PROVIDER
2534 // check. But that is system or signature
2535 // protection level which is not flexible enough for
2536 // providers installed oustide the system image. So
2537 // also allow providers with a UID matching the
2538 // currently bound package name
2539
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002540 if (isUidALocationProvider(Binder.getCallingUid())) {
2541 return;
2542 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002543
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002544 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2545 "or UID of a currently bound location provider");
2546 }
2547
David Christie1f141c12014-05-14 15:11:15 -07002548 /**
2549 * Returns true if the given package belongs to the given uid.
2550 */
2551 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002552 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553 return false;
2554 }
David Christie1f141c12014-05-14 15:11:15 -07002555 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2556 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002557 return false;
2558 }
David Christie1f141c12014-05-14 15:11:15 -07002559 for (String name : packageNames) {
2560 if (packageName.equals(name)) {
2561 return true;
2562 }
2563 }
2564 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566
Nick Pellye0fd6932012-07-11 10:26:13 -07002567 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002568 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002569 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002570
Nick Pelly2eeeec22012-07-18 13:13:37 -07002571 if (!location.isComplete()) {
2572 Log.w(TAG, "Dropping incomplete location: " + location);
2573 return;
2574 }
2575
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002576 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2577 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002578 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002579 mLocationHandler.sendMessageAtFrontOfQueue(m);
2580 }
2581
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002582
Laurent Tu75defb62012-11-01 16:21:52 -07002583 private static boolean shouldBroadcastSafe(
2584 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002585 // Always broadcast the first update
2586 if (lastLoc == null) {
2587 return true;
2588 }
2589
Nick Pellyf1be6862012-05-15 10:53:42 -07002590 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002591 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002592 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2593 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002594 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002595 return false;
2596 }
2597
2598 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002599 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002600 if (minDistance > 0.0) {
2601 if (loc.distanceTo(lastLoc) <= minDistance) {
2602 return false;
2603 }
2604 }
2605
Laurent Tu75defb62012-11-01 16:21:52 -07002606 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002607 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002608 return false;
2609 }
2610
2611 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002612 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002613 }
2614
Mike Lockwooda4903f22010-02-17 06:42:23 -05002615 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002616 if (D) Log.d(TAG, "incoming location: " + location);
2617
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002618 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002619 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002620
Laurent Tu60ec50a2012-10-04 17:00:10 -07002621 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002622 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002623 if (p == null) return;
2624
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002625 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002626 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002627 Location lastNoGPSLocation;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002628 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002629 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002630 lastLocation = new Location(provider);
2631 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002632 } else {
2633 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2634 if (noGPSLocation == null && lastNoGPSLocation != null) {
2635 // New location has no no-GPS location: adopt last no-GPS location. This is set
2636 // directly into location because we do not want to notify COARSE clients.
2637 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2638 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002639 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002640 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002641
David Christie1b9b7b12013-04-15 15:31:11 -07002642 // Update last known coarse interval location if enough time has passed.
2643 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2644 if (lastLocationCoarseInterval == null) {
2645 lastLocationCoarseInterval = new Location(location);
2646 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2647 }
2648 long timeDiffNanos = location.getElapsedRealtimeNanos()
2649 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2650 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2651 lastLocationCoarseInterval.set(location);
2652 }
2653 // Don't ever return a coarse location that is more recent than the allowed update
2654 // interval (i.e. don't allow an app to keep registering and unregistering for
2655 // location updates to overcome the minimum interval).
2656 noGPSLocation =
2657 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2658
Laurent Tu60ec50a2012-10-04 17:00:10 -07002659 // Skip if there are no UpdateRecords for this provider.
2660 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2661 if (records == null || records.size() == 0) return;
2662
Victoria Lease09016ab2012-09-16 12:33:15 -07002663 // Fetch coarse location
2664 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002665 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002666 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2667 }
2668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002669 // Fetch latest status update time
2670 long newStatusUpdateTime = p.getStatusUpdateTime();
2671
David Christie2ff96af2014-01-30 16:09:37 -08002672 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002673 Bundle extras = new Bundle();
2674 int status = p.getStatus(extras);
2675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002677 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002678
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002680 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002681 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002682 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002683
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002684 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2685 if (!isCurrentProfile(receiverUserId)
2686 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002687 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002688 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002689 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002690 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002691 }
2692 continue;
2693 }
2694
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002695 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002696 if (D) {
2697 Log.d(TAG, "skipping loc update for blacklisted app: " +
2698 receiver.mIdentity.mPackageName);
2699 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002700 continue;
2701 }
2702
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002703 if (!reportLocationAccessNoThrow(
2704 receiver.mIdentity.mPid,
2705 receiver.mIdentity.mUid,
2706 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002707 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002708 if (D) {
2709 Log.d(TAG, "skipping loc update for no op app: " +
2710 receiver.mIdentity.mPackageName);
2711 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002712 continue;
2713 }
2714
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002715 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002716 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2717 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002718 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002719 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002720 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002721 if (notifyLocation != null) {
2722 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002723 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002724 if (lastLoc == null) {
2725 lastLoc = new Location(notifyLocation);
2726 r.mLastFixBroadcast = lastLoc;
2727 } else {
2728 lastLoc.set(notifyLocation);
2729 }
2730 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2731 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2732 receiverDead = true;
2733 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002734 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 }
2736 }
2737
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002738 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002739 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002740 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002741
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002742 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002743 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002744 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002745 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002746 }
2747 }
2748
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002749 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002750 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002751 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002752 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002753 }
2754 deadUpdateRecords.add(r);
2755 }
2756 // track dead receivers
2757 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002758 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002759 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07002760 }
2761 if (!deadReceivers.contains(receiver)) {
2762 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002763 }
2764 }
2765 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002766
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002767 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002769 for (Receiver receiver : deadReceivers) {
2770 removeUpdatesLocked(receiver);
2771 }
2772 }
2773 if (deadUpdateRecords != null) {
2774 for (UpdateRecord r : deadUpdateRecords) {
2775 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002776 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002777 applyRequirementsLocked(provider);
2778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
2780
2781 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002782 public LocationWorkerHandler(Looper looper) {
2783 super(looper, null, true);
2784 }
2785
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002786 @Override
2787 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002788 switch (msg.what) {
2789 case MSG_LOCATION_CHANGED:
2790 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2791 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002792 }
2793 }
2794 }
2795
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002796 private boolean isMockProvider(String provider) {
2797 synchronized (mLock) {
2798 return mMockProviders.containsKey(provider);
2799 }
2800 }
2801
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002802 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002803 // create a working copy of the incoming Location so that the service can modify it without
2804 // disturbing the caller's copy
2805 Location myLocation = new Location(location);
2806 String provider = myLocation.getProvider();
2807
2808 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2809 // bit if location did not come from a mock provider because passive/fused providers can
2810 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2811 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2812 myLocation.setIsFromMockProvider(true);
2813 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002814
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002815 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002816 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2817 if (!passive) {
2818 // notify passive provider of the new location
2819 mPassiveProvider.updateLocation(myLocation);
2820 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002821 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002823 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825
Mike Lockwoode97ae402010-09-29 15:23:46 -04002826 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2827 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002828 public void onPackageDisappeared(String packageName, int reason) {
2829 // remove all receivers associated with this package name
2830 synchronized (mLock) {
2831 ArrayList<Receiver> deadReceivers = null;
2832
2833 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002834 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002835 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002836 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002837 }
2838 deadReceivers.add(receiver);
2839 }
2840 }
2841
2842 // perform removal outside of mReceivers loop
2843 if (deadReceivers != null) {
2844 for (Receiver receiver : deadReceivers) {
2845 removeUpdatesLocked(receiver);
2846 }
2847 }
2848 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002849 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002850 };
2851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002852 // Geocoder
2853
Nick Pellye0fd6932012-07-11 10:26:13 -07002854 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002855 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002856 return mGeocodeProvider != null;
2857 }
2858
Nick Pellye0fd6932012-07-11 10:26:13 -07002859 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002861 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002862 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002863 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2864 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002865 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002866 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 }
2868
Mike Lockwooda55c3212009-04-15 11:10:11 -04002869
Nick Pellye0fd6932012-07-11 10:26:13 -07002870 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002871 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002872 double lowerLeftLatitude, double lowerLeftLongitude,
2873 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002874 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002875
2876 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002877 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2878 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2879 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002880 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002881 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 }
2883
2884 // Mock Providers
2885
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002886 private boolean canCallerAccessMockLocation(String opPackageName) {
2887 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
2888 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 }
2890
Nick Pellye0fd6932012-07-11 10:26:13 -07002891 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002892 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
2893 if (!canCallerAccessMockLocation(opPackageName)) {
2894 return;
2895 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896
Mike Lockwooda4903f22010-02-17 06:42:23 -05002897 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2898 throw new IllegalArgumentException("Cannot mock the passive location provider");
2899 }
2900
Mike Lockwood86328a92009-10-23 08:38:25 -04002901 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002902 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002903 // remove the real provider if we are replacing GPS or network provider
2904 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002905 || LocationManager.NETWORK_PROVIDER.equals(name)
2906 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002907 LocationProviderInterface p = mProvidersByName.get(name);
2908 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002909 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002910 }
2911 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002912 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 updateProvidersLocked();
2914 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002915 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 }
2917
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002918 private void addTestProviderLocked(String name, ProviderProperties properties) {
2919 if (mProvidersByName.get(name) != null) {
2920 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2921 }
2922 MockProvider provider = new MockProvider(name, this, properties);
2923 addProviderLocked(provider);
2924 mMockProviders.put(name, provider);
2925 mLastLocation.put(name, null);
2926 mLastLocationCoarseInterval.put(name, null);
2927 }
2928
Nick Pellye0fd6932012-07-11 10:26:13 -07002929 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002930 public void removeTestProvider(String provider, String opPackageName) {
2931 if (!canCallerAccessMockLocation(opPackageName)) {
2932 return;
2933 }
2934
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002935 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002936
2937 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002938 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002939 clearTestProviderEnabled(provider, opPackageName);
2940 clearTestProviderLocation(provider, opPackageName);
2941 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002942
You Kima6d0b6f2012-10-28 03:58:44 +09002943 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002944 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002945 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2946 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002947 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002948 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002949
2950 // reinstate real provider if available
2951 LocationProviderInterface realProvider = mRealProviders.get(provider);
2952 if (realProvider != null) {
2953 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002954 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002955 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002956 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002958 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
2960 }
2961
Nick Pellye0fd6932012-07-11 10:26:13 -07002962 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002963 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
2964 if (!canCallerAccessMockLocation(opPackageName)) {
2965 return;
2966 }
2967
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002968 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002969 MockProvider mockProvider = mMockProviders.get(provider);
2970 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2972 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002973
2974 // Ensure that the location is marked as being mock. There's some logic to do this in
2975 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
2976 Location mock = new Location(loc);
2977 mock.setIsFromMockProvider(true);
2978
2979 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
2980 // The location has an explicit provider that is different from the mock provider
2981 // name. The caller may be trying to fool us via bug 33091107.
2982 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
2983 provider + "!=" + loc.getProvider());
2984 }
2985
Mike Lockwood95427cd2009-05-07 13:27:54 -04002986 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2987 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002988 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002989 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 }
2991 }
2992
Nick Pellye0fd6932012-07-11 10:26:13 -07002993 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002994 public void clearTestProviderLocation(String provider, String opPackageName) {
2995 if (!canCallerAccessMockLocation(opPackageName)) {
2996 return;
2997 }
2998
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002999 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003000 MockProvider mockProvider = mMockProviders.get(provider);
3001 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3003 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003004 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003005 }
3006 }
3007
Nick Pellye0fd6932012-07-11 10:26:13 -07003008 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003009 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3010 if (!canCallerAccessMockLocation(opPackageName)) {
3011 return;
3012 }
3013
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003014 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003015 MockProvider mockProvider = mMockProviders.get(provider);
3016 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3018 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003019 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003020 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003021 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 mEnabledProviders.add(provider);
3023 mDisabledProviders.remove(provider);
3024 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003025 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 mEnabledProviders.remove(provider);
3027 mDisabledProviders.add(provider);
3028 }
3029 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003030 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032 }
3033
Nick Pellye0fd6932012-07-11 10:26:13 -07003034 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003035 public void clearTestProviderEnabled(String provider, String opPackageName) {
3036 if (!canCallerAccessMockLocation(opPackageName)) {
3037 return;
3038 }
3039
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003040 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003041 MockProvider mockProvider = mMockProviders.get(provider);
3042 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3044 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003045 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 mEnabledProviders.remove(provider);
3047 mDisabledProviders.remove(provider);
3048 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003049 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003050 }
3051 }
3052
Nick Pellye0fd6932012-07-11 10:26:13 -07003053 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003054 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3055 String opPackageName) {
3056 if (!canCallerAccessMockLocation(opPackageName)) {
3057 return;
3058 }
3059
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003060 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003061 MockProvider mockProvider = mMockProviders.get(provider);
3062 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3064 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003065 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 }
3067 }
3068
Nick Pellye0fd6932012-07-11 10:26:13 -07003069 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003070 public void clearTestProviderStatus(String provider, String opPackageName) {
3071 if (!canCallerAccessMockLocation(opPackageName)) {
3072 return;
3073 }
3074
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003075 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003076 MockProvider mockProvider = mMockProviders.get(provider);
3077 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3079 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003080 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003081 }
3082 }
3083
3084 private void log(String log) {
3085 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003086 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
3088 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003089
3090 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003091 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003092 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003093
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003094 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003095 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3096 if (mGnssMetricsProvider != null) {
3097 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3098 }
3099 return;
3100 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003103 for (Receiver receiver : mReceivers.values()) {
3104 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 }
David Christie2ff96af2014-01-30 16:09:37 -08003106 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003107 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3108 pw.println(" " + entry.getKey() + ":");
3109 for (UpdateRecord record : entry.getValue()) {
3110 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
3112 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003113 pw.println(" Overlay Provider Packages:");
3114 for (LocationProviderInterface provider : mProviders) {
3115 if (provider instanceof LocationProviderProxy) {
3116 pw.println(" " + provider.getName() + ": "
3117 + ((LocationProviderProxy) provider).getConnectedPackageName());
3118 }
3119 }
David Christie2ff96af2014-01-30 16:09:37 -08003120 pw.println(" Historical Records by Provider:");
3121 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3122 : mRequestStatistics.statistics.entrySet()) {
3123 PackageProviderKey key = entry.getKey();
3124 PackageStatistics stats = entry.getValue();
3125 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3126 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003127 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003128 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3129 String provider = entry.getKey();
3130 Location location = entry.getValue();
3131 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003132 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003133
David Christie1b9b7b12013-04-15 15:31:11 -07003134 pw.println(" Last Known Locations Coarse Intervals:");
3135 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3136 String provider = entry.getKey();
3137 Location location = entry.getValue();
3138 pw.println(" " + provider + ": " + location);
3139 }
3140
Nick Pellye0fd6932012-07-11 10:26:13 -07003141 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 if (mEnabledProviders.size() > 0) {
3144 pw.println(" Enabled Providers:");
3145 for (String i : mEnabledProviders) {
3146 pw.println(" " + i);
3147 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003149 }
3150 if (mDisabledProviders.size() > 0) {
3151 pw.println(" Disabled Providers:");
3152 for (String i : mDisabledProviders) {
3153 pw.println(" " + i);
3154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003156 pw.append(" ");
3157 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158 if (mMockProviders.size() > 0) {
3159 pw.println(" Mock Providers:");
3160 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003161 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003162 }
3163 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003164
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003165 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3166 pw.println(" Throttling Whitelisted Packages:");
3167 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3168 pw.println(" " + packageName);
3169 }
3170 }
3171
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003172 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003173 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003174
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003175 if (args.length > 0 && "short".equals(args[0])) {
3176 return;
3177 }
gomo48f1a642017-11-10 20:35:46 -08003178 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003179 pw.print(provider.getName() + " Internal State");
3180 if (provider instanceof LocationProviderProxy) {
3181 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3182 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003183 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003184 pw.println(":");
3185 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003186 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003187 if (mGnssBatchingInProgress) {
3188 pw.println(" GNSS batching in progress");
3189 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 }
3191 }
3192}