blob: ea748db159e1f0bf1723e317ac0cc1f50e49a64e [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
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002257 /**
2258 * Provides an interface to inject and set the last location if location is not available
2259 * currently.
2260 *
2261 * This helps in cases where the product (Cars for example) has saved the last known location
2262 * before powering off. This interface lets the client inject the saved location while the GPS
2263 * chipset is getting its first fix, there by improving user experience.
2264 *
2265 * @param location - Location object to inject
2266 * @return true if update was successful, false if not
2267 */
2268 @Override
2269 public boolean injectLocation(Location location) {
2270 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2271 "Location Hardware permission not granted to inject location");
2272 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2273 "Access Fine Location permission not granted to inject Location");
2274
2275 if (location == null) {
2276 if (D) {
2277 Log.d(TAG, "injectLocation(): called with null location");
2278 }
2279 return false;
2280 }
2281 LocationProviderInterface p = null;
2282 String provider = location.getProvider();
2283 if (provider != null) {
2284 p = mProvidersByName.get(provider);
2285 }
2286 if (p == null) {
2287 if (D) {
2288 Log.d(TAG, "injectLocation(): unknown provider");
2289 }
2290 return false;
2291 }
2292 synchronized (mLock) {
2293 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2294 if (D) {
2295 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2296 }
2297 return false;
2298 } else {
2299 // NOTE: If last location is already available, location is not injected. If
2300 // provider's normal source (like a GPS chipset) have already provided an output,
2301 // there is no need to inject this location.
2302 if (mLastLocation.get(provider) == null) {
2303 updateLastLocationLocked(location, provider);
2304 } else {
2305 if (D) {
2306 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2307 }
2308 return false;
2309 }
2310 }
2311 }
2312 return true;
2313 }
2314
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002315 @Override
2316 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2317 String packageName) {
2318 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002319 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2320 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002321 checkPendingIntent(intent);
2322 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002323 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2324 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002325 // Require that caller can manage given document
2326 boolean callerHasLocationHardwarePermission =
2327 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
2328 == PackageManager.PERMISSION_GRANTED;
2329 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2330 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002331
Victoria Lease37425c32012-10-16 16:08:48 -07002332 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002333
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002334 // geo-fence manager uses the public location API, need to clear identity
2335 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002336 // TODO: http://b/23822629
2337 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002338 // temporary measure until geofences work for secondary users
2339 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2340 return;
2341 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002342 long identity = Binder.clearCallingIdentity();
2343 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002344 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2345 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002346 } finally {
2347 Binder.restoreCallingIdentity(identity);
2348 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002349 }
2350
2351 @Override
2352 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002353 checkPendingIntent(intent);
2354 checkPackageName(packageName);
2355
2356 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2357
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002358 // geo-fence manager uses the public location API, need to clear identity
2359 long identity = Binder.clearCallingIdentity();
2360 try {
2361 mGeofenceManager.removeFence(geofence, intent);
2362 } finally {
2363 Binder.restoreCallingIdentity(identity);
2364 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002365 }
2366
2367
2368 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002369 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002370 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002371 return false;
2372 }
2373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002374 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002375 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002376 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002377 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002378 return false;
2379 }
2380 return true;
2381 }
2382
Nick Pellye0fd6932012-07-11 10:26:13 -07002383 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002384 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002385 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002386 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002387 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002388 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002389 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002390 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002391 }
2392 }
2393
Nick Pellye0fd6932012-07-11 10:26:13 -07002394 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002395 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002396 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002397 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002398 return false;
2399 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002400
2401 synchronized (mLock) {
2402 Identity callerIdentity
2403 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
2404 mGnssMeasurementsListeners.put(listener, callerIdentity);
2405 long identity = Binder.clearCallingIdentity();
2406 try {
2407 if (isThrottlingExemptLocked(callerIdentity)
2408 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002409 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002410 return mGnssMeasurementsProvider.addListener(listener);
2411 }
2412 } finally {
2413 Binder.restoreCallingIdentity(identity);
2414 }
2415
2416 return true;
2417 }
destradaaea8a8a62014-06-23 18:19:03 -07002418 }
2419
2420 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002421 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2422 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002423 synchronized (mLock) {
2424 mGnssMeasurementsListeners.remove(listener);
2425 mGnssMeasurementsProvider.removeListener(listener);
2426 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002427 }
destradaaea8a8a62014-06-23 18:19:03 -07002428 }
2429
2430 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002431 public boolean addGnssNavigationMessageListener(
2432 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002433 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002434 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002435 return false;
2436 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002437
2438 synchronized (mLock) {
2439 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002440 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002441 mGnssNavigationMessageListeners.put(listener, callerIdentity);
2442 long identity = Binder.clearCallingIdentity();
2443 try {
2444 if (isThrottlingExemptLocked(callerIdentity)
2445 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002446 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002447 return mGnssNavigationMessageProvider.addListener(listener);
2448 }
2449 } finally {
2450 Binder.restoreCallingIdentity(identity);
2451 }
2452
2453 return true;
2454 }
destradaa4b3e3932014-07-21 18:01:47 -07002455 }
2456
2457 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002458 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2459 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002460 synchronized (mLock) {
2461 mGnssNavigationMessageListeners.remove(listener);
2462 mGnssNavigationMessageProvider.removeListener(listener);
2463 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002464 }
destradaa4b3e3932014-07-21 18:01:47 -07002465 }
2466
2467 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002469 if (provider == null) {
2470 // throw NullPointerException to remain compatible with previous implementation
2471 throw new NullPointerException();
2472 }
Victoria Lease37425c32012-10-16 16:08:48 -07002473 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2474 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002475
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002477 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 != PackageManager.PERMISSION_GRANTED)) {
2479 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2480 }
2481
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002482 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002483 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002484 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002485
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002486 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 }
2488 }
2489
Nick Pellye0fd6932012-07-11 10:26:13 -07002490 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002491 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002492 if (Binder.getCallingUid() != Process.myUid()) {
2493 throw new SecurityException(
2494 "calling sendNiResponse from outside of the system is not allowed");
2495 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002496 try {
2497 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002498 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002499 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002500 return false;
2501 }
2502 }
2503
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002504 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002505 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002506 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002507 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002508 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002509 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002510 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002511 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002512 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002513 }
2514
Victoria Lease37425c32012-10-16 16:08:48 -07002515 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2516 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002518 LocationProviderInterface p;
2519 synchronized (mLock) {
2520 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002521 }
2522
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002523 if (p == null) return null;
2524 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002525 }
2526
Jason Monkb71218a2015-06-17 14:44:39 -04002527 /**
2528 * @return null if the provider does not exist
2529 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002530 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002531 */
2532 @Override
2533 public String getNetworkProviderPackage() {
2534 LocationProviderInterface p;
2535 synchronized (mLock) {
2536 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2537 return null;
2538 }
2539 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2540 }
2541
2542 if (p instanceof LocationProviderProxy) {
2543 return ((LocationProviderProxy) p).getConnectedPackageName();
2544 }
2545 return null;
2546 }
2547
Nick Pellye0fd6932012-07-11 10:26:13 -07002548 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07002550 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2551 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002552 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2553
Victoria Lease09eeaec2013-02-05 11:34:13 -08002554 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002555 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002556 try {
2557 synchronized (mLock) {
2558 LocationProviderInterface p = mProvidersByName.get(provider);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002559 return p != null && isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07002560 }
2561 } finally {
2562 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002563 }
2564 }
2565
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002566 /**
2567 * Returns "true" if the UID belongs to a bound location provider.
2568 *
2569 * @param uid the uid
2570 * @return true if uid belongs to a bound location provider
2571 */
2572 private boolean isUidALocationProvider(int uid) {
2573 if (uid == Process.SYSTEM_UID) {
2574 return true;
2575 }
2576 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002577 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002578 }
2579 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002580 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002581 }
2582 return false;
2583 }
2584
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002585 private void checkCallerIsProvider() {
2586 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
2587 == PackageManager.PERMISSION_GRANTED) {
2588 return;
2589 }
2590
2591 // Previously we only used the INSTALL_LOCATION_PROVIDER
2592 // check. But that is system or signature
2593 // protection level which is not flexible enough for
2594 // providers installed oustide the system image. So
2595 // also allow providers with a UID matching the
2596 // currently bound package name
2597
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002598 if (isUidALocationProvider(Binder.getCallingUid())) {
2599 return;
2600 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002601
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002602 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2603 "or UID of a currently bound location provider");
2604 }
2605
David Christie1f141c12014-05-14 15:11:15 -07002606 /**
2607 * Returns true if the given package belongs to the given uid.
2608 */
2609 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002610 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 return false;
2612 }
David Christie1f141c12014-05-14 15:11:15 -07002613 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2614 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002615 return false;
2616 }
David Christie1f141c12014-05-14 15:11:15 -07002617 for (String name : packageNames) {
2618 if (packageName.equals(name)) {
2619 return true;
2620 }
2621 }
2622 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002623 }
2624
Nick Pellye0fd6932012-07-11 10:26:13 -07002625 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002626 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002627 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002628
Nick Pelly2eeeec22012-07-18 13:13:37 -07002629 if (!location.isComplete()) {
2630 Log.w(TAG, "Dropping incomplete location: " + location);
2631 return;
2632 }
2633
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002634 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2635 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002636 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002637 mLocationHandler.sendMessageAtFrontOfQueue(m);
2638 }
2639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002640
Laurent Tu75defb62012-11-01 16:21:52 -07002641 private static boolean shouldBroadcastSafe(
2642 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002643 // Always broadcast the first update
2644 if (lastLoc == null) {
2645 return true;
2646 }
2647
Nick Pellyf1be6862012-05-15 10:53:42 -07002648 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002649 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002650 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2651 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002652 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002653 return false;
2654 }
2655
2656 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002657 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002658 if (minDistance > 0.0) {
2659 if (loc.distanceTo(lastLoc) <= minDistance) {
2660 return false;
2661 }
2662 }
2663
Laurent Tu75defb62012-11-01 16:21:52 -07002664 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002665 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002666 return false;
2667 }
2668
2669 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002670 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672
Mike Lockwooda4903f22010-02-17 06:42:23 -05002673 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002674 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002675 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002676 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002677 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002678 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002679 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002680 updateLastLocationLocked(location, provider);
2681 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002682 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002683 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002684 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2685 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687
David Christie1b9b7b12013-04-15 15:31:11 -07002688 // Update last known coarse interval location if enough time has passed.
2689 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2690 if (lastLocationCoarseInterval == null) {
2691 lastLocationCoarseInterval = new Location(location);
2692 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2693 }
2694 long timeDiffNanos = location.getElapsedRealtimeNanos()
2695 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2696 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2697 lastLocationCoarseInterval.set(location);
2698 }
2699 // Don't ever return a coarse location that is more recent than the allowed update
2700 // interval (i.e. don't allow an app to keep registering and unregistering for
2701 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002702 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002703 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2704
Laurent Tu60ec50a2012-10-04 17:00:10 -07002705 // Skip if there are no UpdateRecords for this provider.
2706 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2707 if (records == null || records.size() == 0) return;
2708
Victoria Lease09016ab2012-09-16 12:33:15 -07002709 // Fetch coarse location
2710 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002711 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002712 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2713 }
2714
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002715 // Fetch latest status update time
2716 long newStatusUpdateTime = p.getStatusUpdateTime();
2717
David Christie2ff96af2014-01-30 16:09:37 -08002718 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002719 Bundle extras = new Bundle();
2720 int status = p.getStatus(extras);
2721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002722 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002723 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002724
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002726 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002727 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002728 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002729
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002730 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2731 if (!isCurrentProfile(receiverUserId)
2732 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002733 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002734 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002735 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002736 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002737 }
2738 continue;
2739 }
2740
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002741 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002742 if (D) {
2743 Log.d(TAG, "skipping loc update for blacklisted app: " +
2744 receiver.mIdentity.mPackageName);
2745 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002746 continue;
2747 }
2748
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002749 if (!reportLocationAccessNoThrow(
2750 receiver.mIdentity.mPid,
2751 receiver.mIdentity.mUid,
2752 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002753 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002754 if (D) {
2755 Log.d(TAG, "skipping loc update for no op app: " +
2756 receiver.mIdentity.mPackageName);
2757 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002758 continue;
2759 }
2760
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002761 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002762 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2763 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002764 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002765 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002766 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002767 if (notifyLocation != null) {
2768 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002769 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002770 if (lastLoc == null) {
2771 lastLoc = new Location(notifyLocation);
2772 r.mLastFixBroadcast = lastLoc;
2773 } else {
2774 lastLoc.set(notifyLocation);
2775 }
2776 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2777 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2778 receiverDead = true;
2779 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002780 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002781 }
2782 }
2783
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002784 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002785 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002786 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002788 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002790 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002791 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002792 }
2793 }
2794
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002795 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002796 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002797 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002798 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002799 }
2800 deadUpdateRecords.add(r);
2801 }
2802 // track dead receivers
2803 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002804 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002805 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07002806 }
2807 if (!deadReceivers.contains(receiver)) {
2808 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 }
2810 }
2811 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002812
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002813 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002814 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002815 for (Receiver receiver : deadReceivers) {
2816 removeUpdatesLocked(receiver);
2817 }
2818 }
2819 if (deadUpdateRecords != null) {
2820 for (UpdateRecord r : deadUpdateRecords) {
2821 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002822 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002823 applyRequirementsLocked(provider);
2824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002825 }
2826
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002827 /**
2828 * Updates last location with the given location
2829 *
2830 * @param location new location to update
2831 * @param provider Location provider to update for
2832 */
2833 private void updateLastLocationLocked(Location location, String provider) {
2834 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2835 Location lastNoGPSLocation;
2836 Location lastLocation = mLastLocation.get(provider);
2837 if (lastLocation == null) {
2838 lastLocation = new Location(provider);
2839 mLastLocation.put(provider, lastLocation);
2840 } else {
2841 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2842 if (noGPSLocation == null && lastNoGPSLocation != null) {
2843 // New location has no no-GPS location: adopt last no-GPS location. This is set
2844 // directly into location because we do not want to notify COARSE clients.
2845 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2846 }
2847 }
2848 lastLocation.set(location);
2849 }
2850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002851 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002852 public LocationWorkerHandler(Looper looper) {
2853 super(looper, null, true);
2854 }
2855
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 @Override
2857 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002858 switch (msg.what) {
2859 case MSG_LOCATION_CHANGED:
2860 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2861 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 }
2863 }
2864 }
2865
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002866 private boolean isMockProvider(String provider) {
2867 synchronized (mLock) {
2868 return mMockProviders.containsKey(provider);
2869 }
2870 }
2871
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002872 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002873 // create a working copy of the incoming Location so that the service can modify it without
2874 // disturbing the caller's copy
2875 Location myLocation = new Location(location);
2876 String provider = myLocation.getProvider();
2877
2878 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2879 // bit if location did not come from a mock provider because passive/fused providers can
2880 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2881 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2882 myLocation.setIsFromMockProvider(true);
2883 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002884
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002885 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002886 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2887 if (!passive) {
2888 // notify passive provider of the new location
2889 mPassiveProvider.updateLocation(myLocation);
2890 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002891 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002893 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002895
Mike Lockwoode97ae402010-09-29 15:23:46 -04002896 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2897 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002898 public void onPackageDisappeared(String packageName, int reason) {
2899 // remove all receivers associated with this package name
2900 synchronized (mLock) {
2901 ArrayList<Receiver> deadReceivers = null;
2902
2903 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002904 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002905 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002906 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002907 }
2908 deadReceivers.add(receiver);
2909 }
2910 }
2911
2912 // perform removal outside of mReceivers loop
2913 if (deadReceivers != null) {
2914 for (Receiver receiver : deadReceivers) {
2915 removeUpdatesLocked(receiver);
2916 }
2917 }
2918 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002919 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002920 };
2921
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002922 // Geocoder
2923
Nick Pellye0fd6932012-07-11 10:26:13 -07002924 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002925 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002926 return mGeocodeProvider != null;
2927 }
2928
Nick Pellye0fd6932012-07-11 10:26:13 -07002929 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002930 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002931 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002932 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002933 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2934 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002936 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 }
2938
Mike Lockwooda55c3212009-04-15 11:10:11 -04002939
Nick Pellye0fd6932012-07-11 10:26:13 -07002940 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002941 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002942 double lowerLeftLatitude, double lowerLeftLongitude,
2943 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002944 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002945
2946 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002947 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2948 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2949 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002950 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002951 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002952 }
2953
2954 // Mock Providers
2955
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002956 private boolean canCallerAccessMockLocation(String opPackageName) {
2957 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
2958 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002959 }
2960
Nick Pellye0fd6932012-07-11 10:26:13 -07002961 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002962 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
2963 if (!canCallerAccessMockLocation(opPackageName)) {
2964 return;
2965 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966
Mike Lockwooda4903f22010-02-17 06:42:23 -05002967 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2968 throw new IllegalArgumentException("Cannot mock the passive location provider");
2969 }
2970
Mike Lockwood86328a92009-10-23 08:38:25 -04002971 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002972 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002973 // remove the real provider if we are replacing GPS or network provider
2974 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002975 || LocationManager.NETWORK_PROVIDER.equals(name)
2976 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002977 LocationProviderInterface p = mProvidersByName.get(name);
2978 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002979 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002980 }
2981 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002982 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 updateProvidersLocked();
2984 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002985 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002986 }
2987
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002988 private void addTestProviderLocked(String name, ProviderProperties properties) {
2989 if (mProvidersByName.get(name) != null) {
2990 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2991 }
2992 MockProvider provider = new MockProvider(name, this, properties);
2993 addProviderLocked(provider);
2994 mMockProviders.put(name, provider);
2995 mLastLocation.put(name, null);
2996 mLastLocationCoarseInterval.put(name, null);
2997 }
2998
Nick Pellye0fd6932012-07-11 10:26:13 -07002999 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003000 public void removeTestProvider(String provider, String opPackageName) {
3001 if (!canCallerAccessMockLocation(opPackageName)) {
3002 return;
3003 }
3004
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003005 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003006
3007 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003008 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003009 clearTestProviderEnabled(provider, opPackageName);
3010 clearTestProviderLocation(provider, opPackageName);
3011 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003012
You Kima6d0b6f2012-10-28 03:58:44 +09003013 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003014 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3016 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003017 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003018 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003019
3020 // reinstate real provider if available
3021 LocationProviderInterface realProvider = mRealProviders.get(provider);
3022 if (realProvider != null) {
3023 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003024 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003025 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003026 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003027 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003028 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003029 }
3030 }
3031
Nick Pellye0fd6932012-07-11 10:26:13 -07003032 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003033 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3034 if (!canCallerAccessMockLocation(opPackageName)) {
3035 return;
3036 }
3037
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003038 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003039 MockProvider mockProvider = mMockProviders.get(provider);
3040 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3042 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003043
3044 // Ensure that the location is marked as being mock. There's some logic to do this in
3045 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3046 Location mock = new Location(loc);
3047 mock.setIsFromMockProvider(true);
3048
3049 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3050 // The location has an explicit provider that is different from the mock provider
3051 // name. The caller may be trying to fool us via bug 33091107.
3052 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3053 provider + "!=" + loc.getProvider());
3054 }
3055
Mike Lockwood95427cd2009-05-07 13:27:54 -04003056 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3057 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003058 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003059 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 }
3061 }
3062
Nick Pellye0fd6932012-07-11 10:26:13 -07003063 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003064 public void clearTestProviderLocation(String provider, String opPackageName) {
3065 if (!canCallerAccessMockLocation(opPackageName)) {
3066 return;
3067 }
3068
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003069 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003070 MockProvider mockProvider = mMockProviders.get(provider);
3071 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003072 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3073 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003074 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075 }
3076 }
3077
Nick Pellye0fd6932012-07-11 10:26:13 -07003078 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003079 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3080 if (!canCallerAccessMockLocation(opPackageName)) {
3081 return;
3082 }
3083
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003084 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003085 MockProvider mockProvider = mMockProviders.get(provider);
3086 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3088 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003089 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003091 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 mEnabledProviders.add(provider);
3093 mDisabledProviders.remove(provider);
3094 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003095 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 mEnabledProviders.remove(provider);
3097 mDisabledProviders.add(provider);
3098 }
3099 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003100 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 }
3102 }
3103
Nick Pellye0fd6932012-07-11 10:26:13 -07003104 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003105 public void clearTestProviderEnabled(String provider, String opPackageName) {
3106 if (!canCallerAccessMockLocation(opPackageName)) {
3107 return;
3108 }
3109
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003110 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003111 MockProvider mockProvider = mMockProviders.get(provider);
3112 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003113 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3114 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003115 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 mEnabledProviders.remove(provider);
3117 mDisabledProviders.remove(provider);
3118 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003119 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003120 }
3121 }
3122
Nick Pellye0fd6932012-07-11 10:26:13 -07003123 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003124 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3125 String opPackageName) {
3126 if (!canCallerAccessMockLocation(opPackageName)) {
3127 return;
3128 }
3129
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003130 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003131 MockProvider mockProvider = mMockProviders.get(provider);
3132 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003133 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3134 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003135 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136 }
3137 }
3138
Nick Pellye0fd6932012-07-11 10:26:13 -07003139 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003140 public void clearTestProviderStatus(String provider, String opPackageName) {
3141 if (!canCallerAccessMockLocation(opPackageName)) {
3142 return;
3143 }
3144
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003145 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003146 MockProvider mockProvider = mMockProviders.get(provider);
3147 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3149 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003150 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 }
3152 }
3153
3154 private void log(String log) {
3155 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003156 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
3158 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003159
3160 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003162 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003163
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003164 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003165 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3166 if (mGnssMetricsProvider != null) {
3167 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3168 }
3169 return;
3170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003173 for (Receiver receiver : mReceivers.values()) {
3174 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 }
David Christie2ff96af2014-01-30 16:09:37 -08003176 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003177 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3178 pw.println(" " + entry.getKey() + ":");
3179 for (UpdateRecord record : entry.getValue()) {
3180 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003181 }
3182 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003183 pw.println(" Overlay Provider Packages:");
3184 for (LocationProviderInterface provider : mProviders) {
3185 if (provider instanceof LocationProviderProxy) {
3186 pw.println(" " + provider.getName() + ": "
3187 + ((LocationProviderProxy) provider).getConnectedPackageName());
3188 }
3189 }
David Christie2ff96af2014-01-30 16:09:37 -08003190 pw.println(" Historical Records by Provider:");
3191 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3192 : mRequestStatistics.statistics.entrySet()) {
3193 PackageProviderKey key = entry.getKey();
3194 PackageStatistics stats = entry.getValue();
3195 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3196 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003198 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3199 String provider = entry.getKey();
3200 Location location = entry.getValue();
3201 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003202 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003203
David Christie1b9b7b12013-04-15 15:31:11 -07003204 pw.println(" Last Known Locations Coarse Intervals:");
3205 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3206 String provider = entry.getKey();
3207 Location location = entry.getValue();
3208 pw.println(" " + provider + ": " + location);
3209 }
3210
Nick Pellye0fd6932012-07-11 10:26:13 -07003211 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003212
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 if (mEnabledProviders.size() > 0) {
3214 pw.println(" Enabled Providers:");
3215 for (String i : mEnabledProviders) {
3216 pw.println(" " + i);
3217 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003218
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 }
3220 if (mDisabledProviders.size() > 0) {
3221 pw.println(" Disabled Providers:");
3222 for (String i : mDisabledProviders) {
3223 pw.println(" " + i);
3224 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003226 pw.append(" ");
3227 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003228 if (mMockProviders.size() > 0) {
3229 pw.println(" Mock Providers:");
3230 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003231 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 }
3233 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003234
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003235 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3236 pw.println(" Throttling Whitelisted Packages:");
3237 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3238 pw.println(" " + packageName);
3239 }
3240 }
3241
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003242 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003243 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003244
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003245 if (args.length > 0 && "short".equals(args[0])) {
3246 return;
3247 }
gomo48f1a642017-11-10 20:35:46 -08003248 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003249 pw.print(provider.getName() + " Internal State");
3250 if (provider instanceof LocationProviderProxy) {
3251 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3252 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003253 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003254 pw.println(":");
3255 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003256 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003257 if (mGnssBatchingInProgress) {
3258 pw.println(" GNSS batching in progress");
3259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003260 }
3261 }
3262}