blob: 5a4f7cab3ed6af4f02aedd981a80383dec99c41f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Maggieaa080f92018-01-04 15:35:11 -080019import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20
Wyatt Rileycf879db2017-01-12 13:57:38 -080021import android.annotation.NonNull;
Maggieaa080f92018-01-04 15:35:11 -080022import android.app.ActivityManager;
23import android.app.AppOpsManager;
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.PackageManagerInternal;
35import android.content.pm.ResolveInfo;
36import android.content.pm.Signature;
37import android.content.res.Resources;
38import android.database.ContentObserver;
39import android.hardware.location.ActivityRecognitionHardware;
40import android.location.Address;
41import android.location.Criteria;
42import android.location.GeocoderParams;
43import android.location.Geofence;
44import android.location.IBatchedLocationCallback;
45import android.location.IGnssMeasurementsListener;
46import android.location.IGnssNavigationMessageListener;
47import android.location.IGnssStatusListener;
48import android.location.IGnssStatusProvider;
49import android.location.IGpsGeofenceHardware;
50import android.location.ILocationListener;
51import android.location.ILocationManager;
52import android.location.INetInitiatedListener;
53import android.location.Location;
54import android.location.LocationManager;
55import android.location.LocationProvider;
56import android.location.LocationRequest;
57import android.os.Binder;
58import android.os.Bundle;
59import android.os.Handler;
60import android.os.IBinder;
61import android.os.Looper;
62import android.os.Message;
63import android.os.PowerManager;
64import android.os.Process;
65import android.os.RemoteException;
66import android.os.SystemClock;
67import android.os.UserHandle;
68import android.os.UserManager;
69import android.os.WorkSource;
70import android.provider.Settings;
71import android.text.TextUtils;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080072import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080073import android.util.ArraySet;
Maggieaa080f92018-01-04 15:35:11 -080074import android.util.EventLog;
75import android.util.Log;
76import android.util.Slog;
destradaaea8a8a62014-06-23 18:19:03 -070077import com.android.internal.content.PackageMonitor;
78import com.android.internal.location.ProviderProperties;
79import com.android.internal.location.ProviderRequest;
80import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070081import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060082import com.android.internal.util.DumpUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070083import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070084import com.android.server.location.FlpHardwareProvider;
85import com.android.server.location.FusedProxy;
86import com.android.server.location.GeocoderProxy;
87import com.android.server.location.GeofenceManager;
88import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080089import com.android.server.location.GnssLocationProvider;
90import com.android.server.location.GnssMeasurementsProvider;
91import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070092import com.android.server.location.LocationBlacklist;
93import com.android.server.location.LocationFudger;
94import com.android.server.location.LocationProviderInterface;
95import com.android.server.location.LocationProviderProxy;
96import com.android.server.location.LocationRequestStatistics;
97import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
98import com.android.server.location.LocationRequestStatistics.PackageStatistics;
99import com.android.server.location.MockProvider;
100import com.android.server.location.PassiveProvider;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400101import java.io.FileDescriptor;
102import java.io.PrintWriter;
103import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700104import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400105import java.util.HashMap;
106import java.util.HashSet;
107import java.util.List;
108import java.util.Map;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800109import java.util.Map.Entry;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800110import java.util.NoSuchElementException;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400111import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
113/**
114 * The service class that manages LocationProviders and issues location
115 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800117public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800119 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700120
Olivier Gaillard7a222662017-11-20 16:07:24 +0000121 private static final String WAKELOCK_KEY = "*location*";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Victoria Lease37425c32012-10-16 16:08:48 -0700123 // Location resolution level: no location data whatsoever
124 private static final int RESOLUTION_LEVEL_NONE = 0;
125 // Location resolution level: coarse location data only
126 private static final int RESOLUTION_LEVEL_COARSE = 1;
127 // Location resolution level: fine location data
128 private static final int RESOLUTION_LEVEL_FINE = 2;
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700131 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700133 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400134 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700135 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
136
137 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700138 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700139 private static final String FUSED_LOCATION_SERVICE_ACTION =
140 "com.android.location.service.FusedLocationProvider";
141
142 private static final int MSG_LOCATION_CHANGED = 1;
143
David Christie1b9b7b12013-04-15 15:31:11 -0700144 private static final long NANOS_PER_MILLI = 1000000L;
145
David Christie0b837452013-07-29 16:02:13 -0700146 // The maximum interval a location request can have and still be considered "high power".
147 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
148
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700149 private static final int FOREGROUND_IMPORTANCE_CUTOFF
gomo48f1a642017-11-10 20:35:46 -0800150 = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700151
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800152 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800153 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800154
Nick Pellyf1be6862012-05-15 10:53:42 -0700155 // Location Providers may sometimes deliver location updates
156 // slightly faster that requested - provide grace period so
157 // we don't unnecessarily filter events that are otherwise on
158 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700159 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700160
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700161 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
162
163 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800164 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700165
166 // used internally for synchronization
167 private final Object mLock = new Object();
168
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700169 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700170 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700171 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700173 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800174 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700175 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700176 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800177 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700178 private INetInitiatedListener mNetInitiatedListener;
179 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700180 private PassiveProvider mPassiveProvider; // track passive provider for special cases
181 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800182 private GnssMeasurementsProvider mGnssMeasurementsProvider;
183 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700184 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700185
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700188 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800189 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
191 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800192 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700194 // Mock (test) providers
195 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800196 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700198 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800199 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700201 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500202 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800203 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400204
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700205 // real providers, saved here when mocked out
206 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800207 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 // mapping from provider name to provider
210 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800211 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700213 // mapping from provider name to all its UpdateRecords
214 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800215 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700216
David Christie2ff96af2014-01-30 16:09:37 -0800217 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
218
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700219 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800220 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
David Christie1b9b7b12013-04-15 15:31:11 -0700222 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
223 // locations stored here are not fudged for coarse permissions.
224 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800225 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700226
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800227 // all providers that operate over proxy, for authorizing incoming location and whitelisting
228 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700229 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800230 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800232 private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800233
Wyatt Riley11cc7492018-01-17 08:48:27 -0800234 private final ArrayMap<IBinder, Identity> mGnssMeasurementsListeners = new ArrayMap<>();
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800235
Wyatt Riley11cc7492018-01-17 08:48:27 -0800236 private final ArrayMap<IBinder, Identity>
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800237 mGnssNavigationMessageListeners = new ArrayMap<>();
238
Victoria Lease38389b62012-09-30 11:44:22 -0700239 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700240 private int mCurrentUserId = UserHandle.USER_SYSTEM;
gomo48f1a642017-11-10 20:35:46 -0800241 private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM};
Victoria Lease38389b62012-09-30 11:44:22 -0700242
Lifu Tang9363b942016-02-16 18:07:00 -0800243 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800244
Siddharth Raybb608c82017-03-16 11:33:34 -0700245 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700246
247 private GnssLocationProvider.GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800248 private IBatchedLocationCallback mGnssBatchingCallback;
249 private LinkedCallback mGnssBatchingDeathCallback;
250 private boolean mGnssBatchingInProgress = false;
251
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700252 public LocationManagerService(Context context) {
253 super();
254 mContext = context;
gomo48f1a642017-11-10 20:35:46 -0800255 mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800256
Svet Ganovadc1cf42015-06-15 16:36:24 -0700257 // Let the package manager query which are the default location
258 // providers as they get certain permissions granted by default.
259 PackageManagerInternal packageManagerInternal = LocalServices.getService(
260 PackageManagerInternal.class);
261 packageManagerInternal.setLocationPackagesProvider(
262 new PackageManagerInternal.PackagesProvider() {
263 @Override
264 public String[] getPackages(int userId) {
265 return mContext.getResources().getStringArray(
266 com.android.internal.R.array.config_locationProviderPackageNames);
267 }
268 });
269
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700270 if (D) Log.d(TAG, "Constructed");
271
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700272 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700273 }
274
Svetoslav Ganova0027152013-06-25 14:59:53 -0700275 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700276 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700277 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700278
Victoria Lease5cd731a2012-12-19 15:04:21 -0800279 // fetch package manager
280 mPackageManager = mContext.getPackageManager();
281
Victoria Lease0aa28602013-05-29 15:28:26 -0700282 // fetch power manager
283 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800284
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800285 // fetch activity manager
286 mActivityManager
287 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
288
Victoria Lease5cd731a2012-12-19 15:04:21 -0800289 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700290 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800291
292 // prepare mLocationHandler's dependents
293 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
294 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
295 mBlacklist.init();
296 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
297
Dianne Hackbornc2293022013-02-06 23:14:49 -0800298 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700299 AppOpsManager.OnOpChangedListener callback
300 = new AppOpsManager.OnOpChangedInternalListener() {
301 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800302 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700303 for (Receiver receiver : mReceivers.values()) {
304 receiver.updateMonitoring(true);
305 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800306 applyAllProviderRequirementsLocked();
307 }
308 }
309 };
310 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
311
David Christieb870dbf2015-06-22 12:42:53 -0700312 PackageManager.OnPermissionsChangedListener permissionListener
313 = new PackageManager.OnPermissionsChangedListener() {
314 @Override
315 public void onPermissionsChanged(final int uid) {
316 synchronized (mLock) {
317 applyAllProviderRequirementsLocked();
318 }
319 }
320 };
321 mPackageManager.addOnPermissionsChangeListener(permissionListener);
322
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800323 // listen for background/foreground changes
324 ActivityManager.OnUidImportanceListener uidImportanceListener
325 = new ActivityManager.OnUidImportanceListener() {
326 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700327 public void onUidImportance(final int uid, final int importance) {
328 mLocationHandler.post(new Runnable() {
329 @Override
330 public void run() {
331 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800332 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700333 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800334 }
335 };
336 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700337 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800338
Amith Yamasanib27528d2014-06-05 15:02:10 -0700339 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
340 updateUserProfiles(mCurrentUserId);
341
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800342 updateBackgroundThrottlingWhitelistLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800343
Victoria Lease5cd731a2012-12-19 15:04:21 -0800344 // prepare providers
345 loadProvidersLocked();
346 updateProvidersLocked();
347 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700348
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700349 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700350 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700351 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700352 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800353 @Override
354 public void onChange(boolean selfChange) {
355 synchronized (mLock) {
356 updateProvidersLocked();
357 }
358 }
359 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800360 mContext.getContentResolver().registerContentObserver(
361 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
362 true,
363 new ContentObserver(mLocationHandler) {
364 @Override
365 public void onChange(boolean selfChange) {
366 synchronized (mLock) {
367 updateProvidersLocked();
368 }
369 }
370 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800371 mContext.getContentResolver().registerContentObserver(
gomo48f1a642017-11-10 20:35:46 -0800372 Settings.Global.getUriFor(
373 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
374 true,
375 new ContentObserver(mLocationHandler) {
376 @Override
377 public void onChange(boolean selfChange) {
378 synchronized (mLock) {
379 updateBackgroundThrottlingWhitelistLocked();
380 updateProvidersLocked();
381 }
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800382 }
gomo48f1a642017-11-10 20:35:46 -0800383 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800384 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700385
Victoria Lease38389b62012-09-30 11:44:22 -0700386 // listen for user change
387 IntentFilter intentFilter = new IntentFilter();
388 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700389 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
390 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700391 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700392
393 mContext.registerReceiverAsUser(new BroadcastReceiver() {
394 @Override
395 public void onReceive(Context context, Intent intent) {
396 String action = intent.getAction();
397 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
398 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700399 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
400 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
401 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700402 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700403 // shutdown only if UserId indicates whole system, not just one user
gomo48f1a642017-11-10 20:35:46 -0800404 if (D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700405 if (getSendingUserId() == UserHandle.USER_ALL) {
406 shutdownComponents();
407 }
Victoria Lease38389b62012-09-30 11:44:22 -0700408 }
409 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800410 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700411 }
412
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700413 private void onUidImportanceChanged(int uid, int importance) {
414 boolean foreground = isImportanceForeground(importance);
415 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
416 synchronized (mLock) {
417 for (Entry<String, ArrayList<UpdateRecord>> entry
gomo48f1a642017-11-10 20:35:46 -0800418 : mRecordsByProvider.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700419 String provider = entry.getKey();
420 for (UpdateRecord record : entry.getValue()) {
421 if (record.mReceiver.mIdentity.mUid == uid
gomo48f1a642017-11-10 20:35:46 -0800422 && record.mIsForegroundUid != foreground) {
423 if (D) {
424 Log.d(TAG, "request from uid " + uid + " is now "
425 + (foreground ? "foreground" : "background)"));
426 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700427 record.mIsForegroundUid = foreground;
428
429 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
430 affectedProviders.add(provider);
431 }
432 }
433 }
434 }
435 for (String provider : affectedProviders) {
436 applyRequirementsLocked(provider);
437 }
438
Wyatt Riley11cc7492018-01-17 08:48:27 -0800439 for (Entry<IBinder, Identity> entry : mGnssMeasurementsListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700440 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800441 if (D) {
442 Log.d(TAG, "gnss measurements listener from uid " + uid
443 + " is now " + (foreground ? "foreground" : "background)"));
444 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700445 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800446 mGnssMeasurementsProvider.addListener(
447 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700448 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800449 mGnssMeasurementsProvider.removeListener(
450 IGnssMeasurementsListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700451 }
452 }
453 }
454
Wyatt Riley11cc7492018-01-17 08:48:27 -0800455 for (Entry<IBinder, Identity> entry : mGnssNavigationMessageListeners.entrySet()) {
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700456 if (entry.getValue().mUid == uid) {
gomo48f1a642017-11-10 20:35:46 -0800457 if (D) {
458 Log.d(TAG, "gnss navigation message listener from uid "
459 + uid + " is now "
460 + (foreground ? "foreground" : "background)"));
461 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700462 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800463 mGnssNavigationMessageProvider.addListener(
464 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700465 } else {
Wyatt Riley11cc7492018-01-17 08:48:27 -0800466 mGnssNavigationMessageProvider.removeListener(
467 IGnssNavigationMessageListener.Stub.asInterface(entry.getKey()));
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700468 }
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 }
Maggieaa080f92018-01-04 15:35:11 -08001380 return isLocationProviderEnabledForUser(provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
1382
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001383 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001384 * Returns "true" if access to the specified location provider is allowed by the specified
1385 * user's settings. Access to all location providers is forbidden to non-location-provider
1386 * processes belonging to background users.
1387 *
1388 * @param provider the name of the location provider
gomo48f1a642017-11-10 20:35:46 -08001389 * @param uid the requestor's UID
Victoria Lease09eeaec2013-02-05 11:34:13 -08001390 */
1391 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001392 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001393 return false;
1394 }
1395 return isAllowedByCurrentUserSettingsLocked(provider);
1396 }
1397
1398 /**
Maggieaa080f92018-01-04 15:35:11 -08001399 * Returns "true" if access to the specified location provider is allowed by the specified
1400 * user's settings. Access to all location providers is forbidden to non-location-provider
1401 * processes belonging to background users.
1402 *
1403 * @param provider the name of the location provider
1404 * @param uid the requestor's UID
1405 * @param userId the user id to query
1406 */
1407 private boolean isAllowedByUserSettingsLockedForUser(
1408 String provider, int uid, int userId) {
1409 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
1410 return false;
1411 }
1412 return isLocationProviderEnabledForUser(provider, userId);
1413 }
1414
1415 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001416 * Returns the permission string associated with the specified resolution level.
1417 *
1418 * @param resolutionLevel the resolution level
1419 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001420 */
Victoria Lease37425c32012-10-16 16:08:48 -07001421 private String getResolutionPermission(int resolutionLevel) {
1422 switch (resolutionLevel) {
1423 case RESOLUTION_LEVEL_FINE:
1424 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1425 case RESOLUTION_LEVEL_COARSE:
1426 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1427 default:
1428 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001430 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001431
Victoria Leaseda479c52012-10-15 15:24:16 -07001432 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001433 * Returns the resolution level allowed to the given PID/UID pair.
1434 *
1435 * @param pid the PID
1436 * @param uid the UID
1437 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001438 */
Victoria Lease37425c32012-10-16 16:08:48 -07001439 private int getAllowedResolutionLevel(int pid, int uid) {
1440 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001441 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001442 return RESOLUTION_LEVEL_FINE;
1443 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
Maggieaa080f92018-01-04 15:35:11 -08001444 pid, uid) == PERMISSION_GRANTED) {
Victoria Lease37425c32012-10-16 16:08:48 -07001445 return RESOLUTION_LEVEL_COARSE;
1446 } else {
1447 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001448 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001449 }
1450
1451 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001452 * Returns the resolution level allowed to the caller
1453 *
1454 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001455 */
Victoria Lease37425c32012-10-16 16:08:48 -07001456 private int getCallerAllowedResolutionLevel() {
1457 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1458 }
1459
1460 /**
1461 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1462 *
1463 * @param allowedResolutionLevel resolution level allowed to caller
1464 */
1465 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1466 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001467 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
1470
Victoria Lease37425c32012-10-16 16:08:48 -07001471 /**
1472 * Return the minimum resolution level required to use the specified location provider.
1473 *
1474 * @param provider the name of the location provider
1475 * @return minimum resolution level required for provider
1476 */
1477 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001478 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1479 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1480 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001481 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001482 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1483 LocationManager.FUSED_PROVIDER.equals(provider)) {
1484 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001485 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001486 } else {
1487 // mock providers
1488 LocationProviderInterface lp = mMockProviders.get(provider);
1489 if (lp != null) {
1490 ProviderProperties properties = lp.getProperties();
1491 if (properties != null) {
1492 if (properties.mRequiresSatellite) {
1493 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001494 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001495 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1496 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001497 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001498 }
1499 }
1500 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001501 }
Victoria Lease37425c32012-10-16 16:08:48 -07001502 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001503 }
1504
Victoria Lease37425c32012-10-16 16:08:48 -07001505 /**
1506 * Throw SecurityException if specified resolution level is insufficient to use the named
1507 * location provider.
1508 *
1509 * @param allowedResolutionLevel resolution level allowed to caller
gomo48f1a642017-11-10 20:35:46 -08001510 * @param providerName the name of the location provider
Victoria Lease37425c32012-10-16 16:08:48 -07001511 */
1512 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1513 String providerName) {
1514 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1515 if (allowedResolutionLevel < requiredResolutionLevel) {
1516 switch (requiredResolutionLevel) {
1517 case RESOLUTION_LEVEL_FINE:
1518 throw new SecurityException("\"" + providerName + "\" location provider " +
1519 "requires ACCESS_FINE_LOCATION permission.");
1520 case RESOLUTION_LEVEL_COARSE:
1521 throw new SecurityException("\"" + providerName + "\" location provider " +
1522 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1523 default:
1524 throw new SecurityException("Insufficient permission for \"" + providerName +
1525 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001526 }
1527 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001528 }
1529
David Christie82edc9b2013-07-19 11:31:42 -07001530 /**
1531 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1532 * for battery).
1533 */
David Christie40e57822013-07-30 11:36:48 -07001534 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001535 mContext.enforceCallingOrSelfPermission(
1536 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1537 }
1538
David Christie40e57822013-07-30 11:36:48 -07001539 private void checkUpdateAppOpsAllowed() {
1540 mContext.enforceCallingOrSelfPermission(
1541 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1542 }
1543
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001544 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001545 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1546 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001547 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001548 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001549 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001550 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001551 }
1552 return -1;
1553 }
1554
David Christieb870dbf2015-06-22 12:42:53 -07001555 boolean reportLocationAccessNoThrow(
1556 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001557 int op = resolutionLevelToOp(allowedResolutionLevel);
1558 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001559 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1560 return false;
1561 }
1562 }
David Christieb870dbf2015-06-22 12:42:53 -07001563
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001564 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001565 }
1566
David Christieb870dbf2015-06-22 12:42:53 -07001567 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001568 int op = resolutionLevelToOp(allowedResolutionLevel);
1569 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001570 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1571 return false;
1572 }
1573 }
David Christieb870dbf2015-06-22 12:42:53 -07001574
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001575 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001576 }
1577
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001578 /**
1579 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001580 * fused, also including ones that are not permitted to
1581 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001582 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001583 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 public List<String> getAllProviders() {
destradaab376b3b2017-09-06 14:09:42 -07001585 List<String> out = getProviders(null /*criteria*/, false /*enabledOnly*/);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001586 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 return out;
1588 }
1589
Mike Lockwood03ca2162010-04-01 08:10:09 -07001590 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001591 * Return all providers by name, that match criteria and are optionally
1592 * enabled.
1593 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001594 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001595 @Override
1596 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001597 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001598 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001599 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001600 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001601 try {
1602 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001603 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001604 for (LocationProviderInterface provider : mProviders) {
1605 String name = provider.getName();
1606 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001607 continue;
1608 }
Victoria Lease37425c32012-10-16 16:08:48 -07001609 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001610 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001611 continue;
1612 }
1613 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1614 name, provider.getProperties(), criteria)) {
1615 continue;
1616 }
1617 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001618 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001619 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001620 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001621 } finally {
1622 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001623 }
1624
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001625 if (D) Log.d(TAG, "getProviders()=" + out);
1626 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001627 }
1628
1629 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001630 * Return the name of the best provider given a Criteria object.
1631 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001632 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001633 * has been deprecated as well. So this method now uses
1634 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001635 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001636 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001637 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001638 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001639
1640 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001641 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001642 result = pickBest(providers);
1643 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1644 return result;
1645 }
1646 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001647 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001648 result = pickBest(providers);
1649 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1650 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001651 }
1652
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001653 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001654 return null;
1655 }
1656
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001657 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001658 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001659 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001660 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1661 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001662 } else {
1663 return providers.get(0);
1664 }
1665 }
1666
Nick Pellye0fd6932012-07-11 10:26:13 -07001667 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001668 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1669 LocationProviderInterface p = mProvidersByName.get(provider);
1670 if (p == null) {
1671 throw new IllegalArgumentException("provider=" + provider);
1672 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001673
1674 boolean result = LocationProvider.propertiesMeetCriteria(
1675 p.getName(), p.getProperties(), criteria);
1676 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1677 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001678 }
1679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001681 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001682 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001683 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 boolean isEnabled = p.isEnabled();
1685 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001686 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001688 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001689 // If any provider has been disabled, clear all last locations for all providers.
1690 // This is to be on the safe side in case a provider has location derived from
1691 // this disabled provider.
1692 mLastLocation.clear();
1693 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001694 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001695 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001696 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001697 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001699 }
1700 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001701 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1702 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001703 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1704 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
1706 }
1707
Amith Yamasanib27528d2014-06-05 15:02:10 -07001708 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 int listeners = 0;
1710
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001711 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001712 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713
1714 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1717 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001718 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001719 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001720 // Sends a notification message to the receiver
1721 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1722 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001723 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001724 }
1725 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001727 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001729 }
1730 }
1731
1732 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001733 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 removeUpdatesLocked(deadReceivers.get(i));
1735 }
1736 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001737
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 if (enabled) {
1739 p.enable();
1740 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001741 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
1743 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 }
1747
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001748 private void applyRequirementsLocked(String provider) {
1749 LocationProviderInterface p = mProvidersByName.get(provider);
1750 if (p == null) return;
1751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001753 WorkSource worksource = new WorkSource();
1754 ProviderRequest providerRequest = new ProviderRequest();
1755
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001756 ContentResolver resolver = mContext.getContentResolver();
1757 long backgroundThrottleInterval = Settings.Global.getLong(
1758 resolver,
1759 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1760 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
gomo48f1a642017-11-10 20:35:46 -08001761 // initialize the low power mode to true and set to false if any of the records requires
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001762
gomo48f1a642017-11-10 20:35:46 -08001763 providerRequest.lowPowerMode = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001765 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001766 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001767 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001768 record.mReceiver.mIdentity.mPid,
1769 record.mReceiver.mIdentity.mUid,
1770 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001771 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001772 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001773 long interval = locationRequest.getInterval();
1774
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001775 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001776 if (!record.mIsForegroundUid) {
1777 interval = Math.max(interval, backgroundThrottleInterval);
1778 }
1779 if (interval != locationRequest.getInterval()) {
1780 locationRequest = new LocationRequest(locationRequest);
1781 locationRequest.setInterval(interval);
1782 }
1783 }
1784
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001785 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001786 providerRequest.locationRequests.add(locationRequest);
gomo48f1a642017-11-10 20:35:46 -08001787 if (!locationRequest.isLowPowerMode()) {
1788 providerRequest.lowPowerMode = false;
1789 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001790 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001791 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001792 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001793 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001794 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001795 }
1796 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001797
1798 if (providerRequest.reportLocation) {
1799 // calculate who to blame for power
1800 // This is somewhat arbitrary. We pick a threshold interval
1801 // that is slightly higher that the minimum interval, and
1802 // spread the blame across all applications with a request
1803 // under that threshold.
1804 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1805 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001806 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001807 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001808
1809 // Don't assign battery blame for update records whose
1810 // client has no permission to receive location data.
1811 if (!providerRequest.locationRequests.contains(locationRequest)) {
1812 continue;
1813 }
1814
Victoria Leaseb711d572012-10-02 13:14:11 -07001815 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001816 if (record.mReceiver.mWorkSource != null
1817 && record.mReceiver.mWorkSource.size() > 0
1818 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001819 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001820 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001821 worksource.add(record.mReceiver.mWorkSource);
1822 } else {
1823 // Assign blame to caller.
1824 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001825 record.mReceiver.mIdentity.mUid,
1826 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001827 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001828 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001829 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
1832 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001833
1834 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1835 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 }
1837
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001838 @Override
1839 public String[] getBackgroundThrottlingWhitelist() {
1840 synchronized (mLock) {
1841 return mBackgroundThrottlePackageWhitelist.toArray(
gomo48f1a642017-11-10 20:35:46 -08001842 new String[mBackgroundThrottlePackageWhitelist.size()]);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001843 }
1844 }
1845
1846 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001847 String setting = Settings.Global.getString(
gomo48f1a642017-11-10 20:35:46 -08001848 mContext.getContentResolver(),
1849 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001850 if (setting == null) {
1851 setting = "";
1852 }
1853
1854 mBackgroundThrottlePackageWhitelist.clear();
1855 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001856 SystemConfig.getInstance().getAllowUnthrottledLocation());
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001857 mBackgroundThrottlePackageWhitelist.addAll(
gomo48f1a642017-11-10 20:35:46 -08001858 Arrays.asList(setting.split(",")));
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001859 }
1860
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001861 private boolean isThrottlingExemptLocked(Identity identity) {
1862 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001863 return true;
1864 }
1865
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001866 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001867 return true;
1868 }
1869
1870 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001871 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001872 return true;
1873 }
1874 }
1875
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001876 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001877 }
1878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 private class UpdateRecord {
1880 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001881 final LocationRequest mRealRequest; // original request from client
1882 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001884 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001885 Location mLastFixBroadcast;
1886 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001887
1888 /**
1889 * Note: must be constructed with lock held.
1890 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001891 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001893 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001894 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001896 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001897 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898
1899 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1900 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001901 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 mRecordsByProvider.put(provider, records);
1903 }
1904 if (!records.contains(this)) {
1905 records.add(this);
1906 }
David Christie2ff96af2014-01-30 16:09:37 -08001907
1908 // Update statistics for historical location requests by package/provider
1909 mRequestStatistics.startRequesting(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001910 mReceiver.mIdentity.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
1912
1913 /**
David Christie2ff96af2014-01-30 16:09:37 -08001914 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001915 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001916 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001917 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001918
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001919 // remove from mRecordsByProvider
1920 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1921 if (globalRecords != null) {
1922 globalRecords.remove(this);
1923 }
1924
1925 if (!removeReceiver) return; // the caller will handle the rest
1926
1927 // remove from Receiver#mUpdateRecords
1928 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1929 if (receiverRecords != null) {
1930 receiverRecords.remove(this.mProvider);
1931
1932 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001933 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001934 removeUpdatesLocked(mReceiver);
1935 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001936 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 }
1938
1939 @Override
1940 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001941 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
gomo48f1a642017-11-10 20:35:46 -08001942 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground"
1943 : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001944 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001945 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001946 }
1947
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001948 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001949 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001950 IBinder binder = listener.asBinder();
1951 Receiver receiver = mReceivers.get(binder);
1952 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001953 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1954 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001955 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001956 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001957 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001958 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001959 return null;
1960 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001961 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001962 }
1963 return receiver;
1964 }
1965
David Christie82edc9b2013-07-19 11:31:42 -07001966 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001967 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001968 Receiver receiver = mReceivers.get(intent);
1969 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001970 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1971 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001972 mReceivers.put(intent, receiver);
1973 }
1974 return receiver;
1975 }
1976
Victoria Lease37425c32012-10-16 16:08:48 -07001977 /**
1978 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1979 * and consistency requirements.
1980 *
1981 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001982 * @return a version of request that meets the given resolution and consistency requirements
1983 * @hide
1984 */
gomo48f1a642017-11-10 20:35:46 -08001985 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel,
1986 boolean callerHasLocationHardwarePermission) {
Victoria Lease37425c32012-10-16 16:08:48 -07001987 LocationRequest sanitizedRequest = new LocationRequest(request);
gomo48f1a642017-11-10 20:35:46 -08001988 if (!callerHasLocationHardwarePermission) {
1989 // allow setting low power mode only for callers with location hardware permission
1990 sanitizedRequest.setLowPowerMode(false);
1991 }
Victoria Lease37425c32012-10-16 16:08:48 -07001992 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1993 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001994 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001995 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001996 break;
1997 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001998 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001999 break;
2000 }
2001 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07002002 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2003 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002004 }
Victoria Lease37425c32012-10-16 16:08:48 -07002005 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
2006 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07002007 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002008 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002009 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07002010 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002011 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002012 }
Victoria Lease37425c32012-10-16 16:08:48 -07002013 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002014 }
2015
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002016 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07002017 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002018 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002019 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002020 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07002021 String[] packages = mPackageManager.getPackagesForUid(uid);
2022 if (packages == null) {
2023 throw new SecurityException("invalid UID " + uid);
2024 }
2025 for (String pkg : packages) {
2026 if (packageName.equals(pkg)) return;
2027 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002028 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07002029 }
2030
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002031 private void checkPendingIntent(PendingIntent intent) {
2032 if (intent == null) {
2033 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002034 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002035 }
2036
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002037 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07002038 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002039 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002040 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002041 } else if (intent != null && listener != null) {
2042 throw new IllegalArgumentException("cannot register both listener and intent");
2043 } else if (intent != null) {
2044 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07002045 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002046 } else {
David Christie40e57822013-07-30 11:36:48 -07002047 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002048 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07002049 }
2050
Nick Pellye0fd6932012-07-11 10:26:13 -07002051 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002052 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2053 PendingIntent intent, String packageName) {
2054 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2055 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002056 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2057 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2058 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002059 WorkSource workSource = request.getWorkSource();
2060 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07002061 checkDeviceStatsAllowed();
2062 }
2063 boolean hideFromAppOps = request.getHideFromAppOps();
2064 if (hideFromAppOps) {
2065 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002066 }
gomo48f1a642017-11-10 20:35:46 -08002067 boolean callerHasLocationHardwarePermission =
2068 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002069 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002070 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2071 callerHasLocationHardwarePermission);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002072
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002073 final int pid = Binder.getCallingPid();
2074 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002075 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002076 long identity = Binder.clearCallingIdentity();
2077 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002078 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2079 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002080 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002081
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002082 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002083 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002084 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002085 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002087 } finally {
2088 Binder.restoreCallingIdentity(identity);
2089 }
2090 }
2091
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002092 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2093 int pid, int uid, String packageName) {
2094 // Figure out the provider. Either its explicitly request (legacy use cases), or
2095 // use the fused provider
2096 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2097 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002098 if (name == null) {
2099 throw new IllegalArgumentException("provider name must not be null");
2100 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002101
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002102 LocationProviderInterface provider = mProvidersByName.get(name);
2103 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002104 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002105 }
2106
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002107 UpdateRecord record = new UpdateRecord(name, request, receiver);
gomo48f1a642017-11-10 20:35:46 -08002108 if (D) {
2109 Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2110 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2111 + (record.mIsForegroundUid ? "foreground" : "background")
2112 + (isThrottlingExemptLocked(receiver.mIdentity)
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002113 ? " [whitelisted]" : "") + ")");
gomo48f1a642017-11-10 20:35:46 -08002114 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002115
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002116 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2117 if (oldRecord != null) {
2118 oldRecord.disposeLocked(false);
2119 }
2120
Victoria Lease09eeaec2013-02-05 11:34:13 -08002121 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002122 if (isProviderEnabled) {
2123 applyRequirementsLocked(name);
2124 } else {
2125 // Notify the listener that updates are currently disabled
2126 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002127 }
David Christie0b837452013-07-29 16:02:13 -07002128 // Update the monitoring here just in case multiple location requests were added to the
2129 // same receiver (this request may be high power and the initial might not have been).
2130 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002131 }
2132
Nick Pellye0fd6932012-07-11 10:26:13 -07002133 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002134 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2135 String packageName) {
2136 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002137
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002138 final int pid = Binder.getCallingPid();
2139 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002140
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002141 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002142 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002143 boolean hideFromAppOps = false;
2144 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2145 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002146
2147 // providers may use public location API's, need to clear identity
2148 long identity = Binder.clearCallingIdentity();
2149 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002150 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002151 } finally {
2152 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 }
2155 }
2156
2157 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002158 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002159
2160 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2161 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2162 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002163 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002165 }
2166
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002167 receiver.updateMonitoring(false);
2168
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002169 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002170 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002171 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2172 if (oldRecords != null) {
2173 // Call dispose() on the obsolete update records.
2174 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002175 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002176 record.disposeLocked(false);
2177 }
2178 // Accumulate providers
2179 providers.addAll(oldRecords.keySet());
2180 }
2181
2182 // update provider
2183 for (String provider : providers) {
2184 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002185 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002186 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002187 }
2188
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002189 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002190 }
2191 }
2192
Dianne Hackbornc2293022013-02-06 23:14:49 -08002193 private void applyAllProviderRequirementsLocked() {
2194 for (LocationProviderInterface p : mProviders) {
2195 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002196 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002197 continue;
2198 }
2199
2200 applyRequirementsLocked(p.getName());
2201 }
2202 }
2203
Nick Pellye0fd6932012-07-11 10:26:13 -07002204 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002205 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002206 if (D) Log.d(TAG, "getLastLocation: " + request);
2207 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002208 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002209 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002210 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2211 request.getProvider());
2212 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002213
David Christieb870dbf2015-06-22 12:42:53 -07002214 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002215 final int uid = Binder.getCallingUid();
2216 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002217 try {
2218 if (mBlacklist.isBlacklisted(packageName)) {
gomo48f1a642017-11-10 20:35:46 -08002219 if (D) {
2220 Log.d(TAG, "not returning last loc for blacklisted app: " +
2221 packageName);
2222 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002223 return null;
2224 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002225
David Christieb870dbf2015-06-22 12:42:53 -07002226 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002227 if (D) {
2228 Log.d(TAG, "not returning last loc for no op app: " +
2229 packageName);
2230 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002231 return null;
2232 }
2233
Victoria Leaseb711d572012-10-02 13:14:11 -07002234 synchronized (mLock) {
2235 // Figure out the provider. Either its explicitly request (deprecated API's),
2236 // or use the fused provider
2237 String name = request.getProvider();
2238 if (name == null) name = LocationManager.FUSED_PROVIDER;
2239 LocationProviderInterface provider = mProvidersByName.get(name);
2240 if (provider == null) return null;
2241
Victoria Lease09eeaec2013-02-05 11:34:13 -08002242 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002243
David Christie1b9b7b12013-04-15 15:31:11 -07002244 Location location;
2245 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2246 // Make sure that an app with coarse permissions can't get frequent location
2247 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2248 location = mLastLocationCoarseInterval.get(name);
2249 } else {
2250 location = mLastLocation.get(name);
2251 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002252 if (location == null) {
2253 return null;
2254 }
Victoria Lease37425c32012-10-16 16:08:48 -07002255 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
gomo48f1a642017-11-10 20:35:46 -08002256 Location noGPSLocation = location.getExtraLocation(
2257 Location.EXTRA_NO_GPS_LOCATION);
Victoria Leaseb711d572012-10-02 13:14:11 -07002258 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002259 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002260 }
Victoria Lease37425c32012-10-16 16:08:48 -07002261 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002262 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002263 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002264 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002265 return null;
2266 } finally {
2267 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002268 }
2269 }
2270
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002271 /**
2272 * Provides an interface to inject and set the last location if location is not available
2273 * currently.
2274 *
2275 * This helps in cases where the product (Cars for example) has saved the last known location
2276 * before powering off. This interface lets the client inject the saved location while the GPS
2277 * chipset is getting its first fix, there by improving user experience.
2278 *
2279 * @param location - Location object to inject
2280 * @return true if update was successful, false if not
2281 */
2282 @Override
2283 public boolean injectLocation(Location location) {
2284 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
2285 "Location Hardware permission not granted to inject location");
2286 mContext.enforceCallingPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
2287 "Access Fine Location permission not granted to inject Location");
2288
2289 if (location == null) {
2290 if (D) {
2291 Log.d(TAG, "injectLocation(): called with null location");
2292 }
2293 return false;
2294 }
2295 LocationProviderInterface p = null;
2296 String provider = location.getProvider();
2297 if (provider != null) {
2298 p = mProvidersByName.get(provider);
2299 }
2300 if (p == null) {
2301 if (D) {
2302 Log.d(TAG, "injectLocation(): unknown provider");
2303 }
2304 return false;
2305 }
2306 synchronized (mLock) {
2307 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
2308 if (D) {
2309 Log.d(TAG, "Location disabled in Settings for current user:" + mCurrentUserId);
2310 }
2311 return false;
2312 } else {
2313 // NOTE: If last location is already available, location is not injected. If
2314 // provider's normal source (like a GPS chipset) have already provided an output,
2315 // there is no need to inject this location.
2316 if (mLastLocation.get(provider) == null) {
2317 updateLastLocationLocked(location, provider);
2318 } else {
2319 if (D) {
2320 Log.d(TAG, "injectLocation(): Location exists. Not updating");
2321 }
2322 return false;
2323 }
2324 }
2325 }
2326 return true;
2327 }
2328
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002329 @Override
2330 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2331 String packageName) {
2332 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002333 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2334 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002335 checkPendingIntent(intent);
2336 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002337 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2338 request.getProvider());
gomo48f1a642017-11-10 20:35:46 -08002339 // Require that caller can manage given document
2340 boolean callerHasLocationHardwarePermission =
2341 mContext.checkCallingPermission(android.Manifest.permission.LOCATION_HARDWARE)
Maggieaa080f92018-01-04 15:35:11 -08002342 == PERMISSION_GRANTED;
gomo48f1a642017-11-10 20:35:46 -08002343 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel,
2344 callerHasLocationHardwarePermission);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002345
Victoria Lease37425c32012-10-16 16:08:48 -07002346 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002347
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002348 // geo-fence manager uses the public location API, need to clear identity
2349 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002350 // TODO: http://b/23822629
2351 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002352 // temporary measure until geofences work for secondary users
2353 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2354 return;
2355 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002356 long identity = Binder.clearCallingIdentity();
2357 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002358 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2359 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002360 } finally {
2361 Binder.restoreCallingIdentity(identity);
2362 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002363 }
2364
2365 @Override
2366 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002367 checkPendingIntent(intent);
2368 checkPackageName(packageName);
2369
2370 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2371
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002372 // geo-fence manager uses the public location API, need to clear identity
2373 long identity = Binder.clearCallingIdentity();
2374 try {
2375 mGeofenceManager.removeFence(geofence, intent);
2376 } finally {
2377 Binder.restoreCallingIdentity(identity);
2378 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002379 }
2380
2381
2382 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002383 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002384 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002385 return false;
2386 }
2387
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002388 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002389 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002390 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002391 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 return false;
2393 }
2394 return true;
2395 }
2396
Nick Pellye0fd6932012-07-11 10:26:13 -07002397 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002398 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002399 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002400 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002401 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002402 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002403 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002404 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002405 }
2406 }
2407
Nick Pellye0fd6932012-07-11 10:26:13 -07002408 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002409 public boolean addGnssMeasurementsListener(
gomo48f1a642017-11-10 20:35:46 -08002410 IGnssMeasurementsListener listener, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002411 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002412 return false;
2413 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002414
2415 synchronized (mLock) {
2416 Identity callerIdentity
2417 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002418 mGnssMeasurementsListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002419 long identity = Binder.clearCallingIdentity();
2420 try {
2421 if (isThrottlingExemptLocked(callerIdentity)
2422 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002423 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002424 return mGnssMeasurementsProvider.addListener(listener);
2425 }
2426 } finally {
2427 Binder.restoreCallingIdentity(identity);
2428 }
2429
2430 return true;
2431 }
destradaaea8a8a62014-06-23 18:19:03 -07002432 }
2433
2434 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002435 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2436 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002437 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002438 mGnssMeasurementsListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002439 mGnssMeasurementsProvider.removeListener(listener);
2440 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002441 }
destradaaea8a8a62014-06-23 18:19:03 -07002442 }
2443
2444 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002445 public boolean addGnssNavigationMessageListener(
2446 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002447 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002448 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002449 return false;
2450 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002451
2452 synchronized (mLock) {
2453 Identity callerIdentity
gomo48f1a642017-11-10 20:35:46 -08002454 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
Wyatt Riley11cc7492018-01-17 08:48:27 -08002455 mGnssNavigationMessageListeners.put(listener.asBinder(), callerIdentity);
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002456 long identity = Binder.clearCallingIdentity();
2457 try {
2458 if (isThrottlingExemptLocked(callerIdentity)
2459 || isImportanceForeground(
gomo48f1a642017-11-10 20:35:46 -08002460 mActivityManager.getPackageImportance(packageName))) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002461 return mGnssNavigationMessageProvider.addListener(listener);
2462 }
2463 } finally {
2464 Binder.restoreCallingIdentity(identity);
2465 }
2466
2467 return true;
2468 }
destradaa4b3e3932014-07-21 18:01:47 -07002469 }
2470
2471 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002472 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2473 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002474 synchronized (mLock) {
Wyatt Riley11cc7492018-01-17 08:48:27 -08002475 mGnssNavigationMessageListeners.remove(listener.asBinder());
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002476 mGnssNavigationMessageProvider.removeListener(listener);
2477 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002478 }
destradaa4b3e3932014-07-21 18:01:47 -07002479 }
2480
2481 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002483 if (provider == null) {
2484 // throw NullPointerException to remain compatible with previous implementation
2485 throw new NullPointerException();
2486 }
Victoria Lease37425c32012-10-16 16:08:48 -07002487 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2488 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002489
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002491 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
Maggieaa080f92018-01-04 15:35:11 -08002492 != PERMISSION_GRANTED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2494 }
2495
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002496 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002497 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002498 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002499
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002500 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 }
2502 }
2503
Nick Pellye0fd6932012-07-11 10:26:13 -07002504 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002505 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002506 if (Binder.getCallingUid() != Process.myUid()) {
2507 throw new SecurityException(
2508 "calling sendNiResponse from outside of the system is not allowed");
2509 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002510 try {
2511 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002512 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002513 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002514 return false;
2515 }
2516 }
2517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002518 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002519 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002520 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002521 * accessed by the caller
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002523 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002524 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002525 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002526 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002527 }
2528
Victoria Lease37425c32012-10-16 16:08:48 -07002529 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2530 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002532 LocationProviderInterface p;
2533 synchronized (mLock) {
2534 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002535 }
2536
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002537 if (p == null) return null;
2538 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
2540
Jason Monkb71218a2015-06-17 14:44:39 -04002541 /**
2542 * @return null if the provider does not exist
2543 * @throws SecurityException if the provider is not allowed to be
gomo48f1a642017-11-10 20:35:46 -08002544 * accessed by the caller
Jason Monkb71218a2015-06-17 14:44:39 -04002545 */
2546 @Override
2547 public String getNetworkProviderPackage() {
2548 LocationProviderInterface p;
2549 synchronized (mLock) {
2550 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2551 return null;
2552 }
2553 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2554 }
2555
2556 if (p instanceof LocationProviderProxy) {
2557 return ((LocationProviderProxy) p).getConnectedPackageName();
2558 }
2559 return null;
2560 }
2561
Maggieaa080f92018-01-04 15:35:11 -08002562 /**
2563 * Method for enabling or disabling location.
2564 *
2565 * @param enabled true to enable location. false to disable location
2566 * @param userId the user id to set
2567 */
2568 @Override
2569 public void setLocationEnabledForUser(boolean enabled, int userId) {
2570 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2571 checkInteractAcrossUsersPermission(userId);
2572
2573 // enable all location providers
2574 synchronized (mLock) {
2575 for(String provider : getAllProviders()) {
2576 setProviderEnabledForUser(provider, enabled, userId);
2577 }
2578 }
2579 }
2580
2581 /**
2582 * Returns the current enabled/disabled status of location
2583 *
2584 * @param userId the user id to query
2585 * @return true if location is enabled. false if location is disabled.
2586 */
2587 @Override
2588 public boolean isLocationEnabledForUser(int userId) {
2589
2590 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2591 checkInteractAcrossUsersPermission(userId);
2592
2593 synchronized (mLock) {
2594 for (String provider : getAllProviders()) {
2595 if (isProviderEnabledForUser(provider, userId)) {
2596 return true;
2597 }
2598 }
2599 return false;
2600 }
2601 }
2602
Nick Pellye0fd6932012-07-11 10:26:13 -07002603 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 public boolean isProviderEnabled(String provider) {
Maggieaa080f92018-01-04 15:35:11 -08002605 return isProviderEnabledForUser(provider, UserHandle.myUserId());
2606 }
2607
2608 /**
2609 * Method for determining if a location provider is enabled.
2610 *
2611 * @param provider the location provider to query
2612 * @param userId the user id to query
2613 * @return true if the provider is enabled
2614 */
2615 @Override
2616 public boolean isProviderEnabledForUser(String provider, int userId) {
2617 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2618 checkInteractAcrossUsersPermission(userId);
2619
Tom O'Neilld5759432013-09-11 11:03:03 -07002620 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2621 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002622 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2623
Victoria Lease09eeaec2013-02-05 11:34:13 -08002624 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002625 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002626 try {
2627 synchronized (mLock) {
2628 LocationProviderInterface p = mProvidersByName.get(provider);
Maggieaa080f92018-01-04 15:35:11 -08002629 return p != null
2630 && isAllowedByUserSettingsLockedForUser(provider, uid, userId);
Victoria Leaseb711d572012-10-02 13:14:11 -07002631 }
2632 } finally {
2633 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002634 }
2635 }
2636
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002637 /**
Maggieaa080f92018-01-04 15:35:11 -08002638 * Method for enabling or disabling a single location provider.
2639 *
2640 * @param provider the name of the provider
2641 * @param enabled true to enable the provider. false to disable the provider
2642 * @param userId the user id to set
2643 * @return true if the value was set successfully. false on failure.
2644 */
2645 @Override
2646 public boolean setProviderEnabledForUser(
2647 String provider, boolean enabled, int userId) {
2648 mContext.enforceCallingPermission(
2649 android.Manifest.permission.WRITE_SECURE_SETTINGS,
2650 "Requires WRITE_SECURE_SETTINGS permission");
2651
2652 // Check INTERACT_ACROSS_USERS permission if userId is not current user id.
2653 checkInteractAcrossUsersPermission(userId);
2654
2655 final long identity = Binder.clearCallingIdentity();
2656 try {
2657 synchronized (mLock) {
2658 // to ensure thread safety, we write the provider name with a '+' or '-'
2659 // and let the SettingsProvider handle it rather than reading and modifying
2660 // the list of enabled providers.
2661 if (enabled) {
2662 provider = "+" + provider;
2663 } else {
2664 provider = "-" + provider;
2665 }
2666 return Settings.Secure.putStringForUser(
2667 mContext.getContentResolver(),
2668 Settings.Secure.LOCATION_PROVIDERS_ALLOWED,
2669 provider,
2670 userId);
2671 }
2672 } finally {
2673 Binder.restoreCallingIdentity(identity);
2674 }
2675 }
2676
2677 /**
2678 * Read location provider status from Settings.Secure
2679 *
2680 * @param provider the location provider to query
2681 * @param userId the user id to query
2682 * @return true if the provider is enabled
2683 */
2684 private boolean isLocationProviderEnabledForUser(String provider, int userId) {
2685 long identity = Binder.clearCallingIdentity();
2686 try {
2687 // Use system settings
2688 ContentResolver cr = mContext.getContentResolver();
2689 String allowedProviders = Settings.Secure.getStringForUser(
2690 cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED, userId);
2691 return TextUtils.delimitedStringContains(allowedProviders, ',', provider);
2692 } finally {
2693 Binder.restoreCallingIdentity(identity);
2694 }
2695 }
2696
2697 /**
2698 * Method for checking INTERACT_ACROSS_USERS permission if specified user id is not the same as
2699 * current user id
2700 *
2701 * @param userId the user id to get or set value
2702 */
2703 private void checkInteractAcrossUsersPermission(int userId) {
2704 int uid = Binder.getCallingUid();
2705 if (UserHandle.getUserId(uid) != userId) {
2706 if (ActivityManager.checkComponentPermission(
2707 android.Manifest.permission.INTERACT_ACROSS_USERS, uid, -1, true)
2708 != PERMISSION_GRANTED) {
2709 throw new SecurityException("Requires INTERACT_ACROSS_USERS permission");
2710 }
2711 }
2712 }
2713
2714 /**
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002715 * Returns "true" if the UID belongs to a bound location provider.
2716 *
2717 * @param uid the uid
2718 * @return true if uid belongs to a bound location provider
2719 */
2720 private boolean isUidALocationProvider(int uid) {
2721 if (uid == Process.SYSTEM_UID) {
2722 return true;
2723 }
2724 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002725 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002726 }
2727 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002728 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002729 }
2730 return false;
2731 }
2732
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002733 private void checkCallerIsProvider() {
2734 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
Maggieaa080f92018-01-04 15:35:11 -08002735 == PERMISSION_GRANTED) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002736 return;
2737 }
2738
2739 // Previously we only used the INSTALL_LOCATION_PROVIDER
2740 // check. But that is system or signature
2741 // protection level which is not flexible enough for
2742 // providers installed oustide the system image. So
2743 // also allow providers with a UID matching the
2744 // currently bound package name
2745
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002746 if (isUidALocationProvider(Binder.getCallingUid())) {
2747 return;
2748 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002749
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002750 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2751 "or UID of a currently bound location provider");
2752 }
2753
David Christie1f141c12014-05-14 15:11:15 -07002754 /**
2755 * Returns true if the given package belongs to the given uid.
2756 */
2757 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002758 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 return false;
2760 }
David Christie1f141c12014-05-14 15:11:15 -07002761 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2762 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002763 return false;
2764 }
David Christie1f141c12014-05-14 15:11:15 -07002765 for (String name : packageNames) {
2766 if (packageName.equals(name)) {
2767 return true;
2768 }
2769 }
2770 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002771 }
2772
Nick Pellye0fd6932012-07-11 10:26:13 -07002773 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002774 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002775 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002776
Nick Pelly2eeeec22012-07-18 13:13:37 -07002777 if (!location.isComplete()) {
2778 Log.w(TAG, "Dropping incomplete location: " + location);
2779 return;
2780 }
2781
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002782 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2783 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002784 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002785 mLocationHandler.sendMessageAtFrontOfQueue(m);
2786 }
2787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002788
Laurent Tu75defb62012-11-01 16:21:52 -07002789 private static boolean shouldBroadcastSafe(
2790 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002791 // Always broadcast the first update
2792 if (lastLoc == null) {
2793 return true;
2794 }
2795
Nick Pellyf1be6862012-05-15 10:53:42 -07002796 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002797 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002798 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2799 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002800 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002801 return false;
2802 }
2803
2804 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002805 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 if (minDistance > 0.0) {
2807 if (loc.distanceTo(lastLoc) <= minDistance) {
2808 return false;
2809 }
2810 }
2811
Laurent Tu75defb62012-11-01 16:21:52 -07002812 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002813 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002814 return false;
2815 }
2816
2817 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002818 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820
Mike Lockwooda4903f22010-02-17 06:42:23 -05002821 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002822 if (D) Log.d(TAG, "incoming location: " + location);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002823 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002824 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
Laurent Tu60ec50a2012-10-04 17:00:10 -07002825 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002826 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002827 if (p == null) return;
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002828 updateLastLocationLocked(location, provider);
2829 // mLastLocation should have been updated from the updateLastLocationLocked call above.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002830 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002831 if (lastLocation == null) {
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002832 Log.e(TAG, "handleLocationChangedLocked() updateLastLocation failed");
2833 return;
Mike Lockwood4e50b782009-04-03 08:24:43 -07002834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002835
David Christie1b9b7b12013-04-15 15:31:11 -07002836 // Update last known coarse interval location if enough time has passed.
2837 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2838 if (lastLocationCoarseInterval == null) {
2839 lastLocationCoarseInterval = new Location(location);
2840 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2841 }
2842 long timeDiffNanos = location.getElapsedRealtimeNanos()
2843 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2844 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2845 lastLocationCoarseInterval.set(location);
2846 }
2847 // Don't ever return a coarse location that is more recent than the allowed update
2848 // interval (i.e. don't allow an app to keep registering and unregistering for
2849 // location updates to overcome the minimum interval).
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002850 Location noGPSLocation =
David Christie1b9b7b12013-04-15 15:31:11 -07002851 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2852
Laurent Tu60ec50a2012-10-04 17:00:10 -07002853 // Skip if there are no UpdateRecords for this provider.
2854 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2855 if (records == null || records.size() == 0) return;
2856
Victoria Lease09016ab2012-09-16 12:33:15 -07002857 // Fetch coarse location
2858 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002859 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002860 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2861 }
2862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 // Fetch latest status update time
2864 long newStatusUpdateTime = p.getStatusUpdateTime();
2865
David Christie2ff96af2014-01-30 16:09:37 -08002866 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002867 Bundle extras = new Bundle();
2868 int status = p.getStatus(extras);
2869
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002870 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002871 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002872
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002873 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002874 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002875 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002876 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002877
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002878 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2879 if (!isCurrentProfile(receiverUserId)
2880 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002881 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002882 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002883 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002884 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002885 }
2886 continue;
2887 }
2888
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002889 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
gomo48f1a642017-11-10 20:35:46 -08002890 if (D) {
2891 Log.d(TAG, "skipping loc update for blacklisted app: " +
2892 receiver.mIdentity.mPackageName);
2893 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002894 continue;
2895 }
2896
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002897 if (!reportLocationAccessNoThrow(
2898 receiver.mIdentity.mPid,
2899 receiver.mIdentity.mUid,
2900 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002901 receiver.mAllowedResolutionLevel)) {
gomo48f1a642017-11-10 20:35:46 -08002902 if (D) {
2903 Log.d(TAG, "skipping loc update for no op app: " +
2904 receiver.mIdentity.mPackageName);
2905 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002906 continue;
2907 }
2908
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002909 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002910 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2911 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002912 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002913 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002914 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002915 if (notifyLocation != null) {
2916 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002917 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002918 if (lastLoc == null) {
2919 lastLoc = new Location(notifyLocation);
2920 r.mLastFixBroadcast = lastLoc;
2921 } else {
2922 lastLoc.set(notifyLocation);
2923 }
2924 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2925 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2926 receiverDead = true;
2927 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002928 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002929 }
2930 }
2931
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002932 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002934 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002936 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002938 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002939 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002940 }
2941 }
2942
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002943 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002944 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002945 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002946 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002947 }
2948 deadUpdateRecords.add(r);
2949 }
2950 // track dead receivers
2951 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002952 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002953 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07002954 }
2955 if (!deadReceivers.contains(receiver)) {
2956 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002957 }
2958 }
2959 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002960
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002961 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002962 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002963 for (Receiver receiver : deadReceivers) {
2964 removeUpdatesLocked(receiver);
2965 }
2966 }
2967 if (deadUpdateRecords != null) {
2968 for (UpdateRecord r : deadUpdateRecords) {
2969 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002971 applyRequirementsLocked(provider);
2972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 }
2974
Ram Periathiruvadi8671fea2017-12-08 18:35:10 -08002975 /**
2976 * Updates last location with the given location
2977 *
2978 * @param location new location to update
2979 * @param provider Location provider to update for
2980 */
2981 private void updateLastLocationLocked(Location location, String provider) {
2982 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2983 Location lastNoGPSLocation;
2984 Location lastLocation = mLastLocation.get(provider);
2985 if (lastLocation == null) {
2986 lastLocation = new Location(provider);
2987 mLastLocation.put(provider, lastLocation);
2988 } else {
2989 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2990 if (noGPSLocation == null && lastNoGPSLocation != null) {
2991 // New location has no no-GPS location: adopt last no-GPS location. This is set
2992 // directly into location because we do not want to notify COARSE clients.
2993 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2994 }
2995 }
2996 lastLocation.set(location);
2997 }
2998
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08003000 public LocationWorkerHandler(Looper looper) {
3001 super(looper, null, true);
3002 }
3003
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003004 @Override
3005 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003006 switch (msg.what) {
3007 case MSG_LOCATION_CHANGED:
3008 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
3009 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 }
3011 }
3012 }
3013
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003014 private boolean isMockProvider(String provider) {
3015 synchronized (mLock) {
3016 return mMockProviders.containsKey(provider);
3017 }
3018 }
3019
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003020 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003021 // create a working copy of the incoming Location so that the service can modify it without
3022 // disturbing the caller's copy
3023 Location myLocation = new Location(location);
3024 String provider = myLocation.getProvider();
3025
3026 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
3027 // bit if location did not come from a mock provider because passive/fused providers can
3028 // forward locations from mock providers, and should not grant them legitimacy in doing so.
3029 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
3030 myLocation.setIsFromMockProvider(true);
3031 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08003032
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003033 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08003034 if (isAllowedByCurrentUserSettingsLocked(provider)) {
3035 if (!passive) {
3036 // notify passive provider of the new location
3037 mPassiveProvider.updateLocation(myLocation);
3038 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08003039 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003040 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003041 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003043
Mike Lockwoode97ae402010-09-29 15:23:46 -04003044 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
3045 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003046 public void onPackageDisappeared(String packageName, int reason) {
3047 // remove all receivers associated with this package name
3048 synchronized (mLock) {
3049 ArrayList<Receiver> deadReceivers = null;
3050
3051 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08003052 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003053 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003054 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003055 }
3056 deadReceivers.add(receiver);
3057 }
3058 }
3059
3060 // perform removal outside of mReceivers loop
3061 if (deadReceivers != null) {
3062 for (Receiver receiver : deadReceivers) {
3063 removeUpdatesLocked(receiver);
3064 }
3065 }
3066 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003067 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04003068 };
3069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 // Geocoder
3071
Nick Pellye0fd6932012-07-11 10:26:13 -07003072 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04003073 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07003074 return mGeocodeProvider != null;
3075 }
3076
Nick Pellye0fd6932012-07-11 10:26:13 -07003077 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003079 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003080 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003081 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
3082 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003084 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086
Mike Lockwooda55c3212009-04-15 11:10:11 -04003087
Nick Pellye0fd6932012-07-11 10:26:13 -07003088 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003089 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04003090 double lowerLeftLatitude, double lowerLeftLongitude,
3091 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05003092 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04003093
3094 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05003095 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
3096 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
3097 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04003099 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003100 }
3101
3102 // Mock Providers
3103
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003104 private boolean canCallerAccessMockLocation(String opPackageName) {
3105 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
3106 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 }
3108
Nick Pellye0fd6932012-07-11 10:26:13 -07003109 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003110 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
3111 if (!canCallerAccessMockLocation(opPackageName)) {
3112 return;
3113 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003114
Mike Lockwooda4903f22010-02-17 06:42:23 -05003115 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
3116 throw new IllegalArgumentException("Cannot mock the passive location provider");
3117 }
3118
Mike Lockwood86328a92009-10-23 08:38:25 -04003119 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003120 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003121 // remove the real provider if we are replacing GPS or network provider
3122 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07003123 || LocationManager.NETWORK_PROVIDER.equals(name)
3124 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05003125 LocationProviderInterface p = mProvidersByName.get(name);
3126 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003127 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003128 }
3129 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003130 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 updateProvidersLocked();
3132 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003133 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 }
3135
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09003136 private void addTestProviderLocked(String name, ProviderProperties properties) {
3137 if (mProvidersByName.get(name) != null) {
3138 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
3139 }
3140 MockProvider provider = new MockProvider(name, this, properties);
3141 addProviderLocked(provider);
3142 mMockProviders.put(name, provider);
3143 mLastLocation.put(name, null);
3144 mLastLocationCoarseInterval.put(name, null);
3145 }
3146
Nick Pellye0fd6932012-07-11 10:26:13 -07003147 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003148 public void removeTestProvider(String provider, String opPackageName) {
3149 if (!canCallerAccessMockLocation(opPackageName)) {
3150 return;
3151 }
3152
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003153 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003154
3155 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08003156 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003157 clearTestProviderEnabled(provider, opPackageName);
3158 clearTestProviderLocation(provider, opPackageName);
3159 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08003160
You Kima6d0b6f2012-10-28 03:58:44 +09003161 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003162 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3164 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003165 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003166 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003167
3168 // reinstate real provider if available
3169 LocationProviderInterface realProvider = mRealProviders.get(provider);
3170 if (realProvider != null) {
3171 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07003172 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003173 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07003174 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003176 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 }
3178 }
3179
Nick Pellye0fd6932012-07-11 10:26:13 -07003180 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003181 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
3182 if (!canCallerAccessMockLocation(opPackageName)) {
3183 return;
3184 }
3185
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003186 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003187 MockProvider mockProvider = mMockProviders.get(provider);
3188 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003189 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3190 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003191
3192 // Ensure that the location is marked as being mock. There's some logic to do this in
3193 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
3194 Location mock = new Location(loc);
3195 mock.setIsFromMockProvider(true);
3196
3197 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
3198 // The location has an explicit provider that is different from the mock provider
3199 // name. The caller may be trying to fool us via bug 33091107.
3200 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
3201 provider + "!=" + loc.getProvider());
3202 }
3203
Mike Lockwood95427cd2009-05-07 13:27:54 -04003204 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
3205 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08003206 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04003207 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003208 }
3209 }
3210
Nick Pellye0fd6932012-07-11 10:26:13 -07003211 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003212 public void clearTestProviderLocation(String provider, String opPackageName) {
3213 if (!canCallerAccessMockLocation(opPackageName)) {
3214 return;
3215 }
3216
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003217 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003218 MockProvider mockProvider = mMockProviders.get(provider);
3219 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003220 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3221 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003222 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
3224 }
3225
Nick Pellye0fd6932012-07-11 10:26:13 -07003226 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003227 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
3228 if (!canCallerAccessMockLocation(opPackageName)) {
3229 return;
3230 }
3231
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003232 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003233 MockProvider mockProvider = mMockProviders.get(provider);
3234 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003235 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3236 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003237 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003239 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 mEnabledProviders.add(provider);
3241 mDisabledProviders.remove(provider);
3242 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003243 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003244 mEnabledProviders.remove(provider);
3245 mDisabledProviders.add(provider);
3246 }
3247 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003248 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003249 }
3250 }
3251
Nick Pellye0fd6932012-07-11 10:26:13 -07003252 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003253 public void clearTestProviderEnabled(String provider, String opPackageName) {
3254 if (!canCallerAccessMockLocation(opPackageName)) {
3255 return;
3256 }
3257
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003258 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003259 MockProvider mockProvider = mMockProviders.get(provider);
3260 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003261 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3262 }
Mike Lockwood86328a92009-10-23 08:38:25 -04003263 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 mEnabledProviders.remove(provider);
3265 mDisabledProviders.remove(provider);
3266 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04003267 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 }
3269 }
3270
Nick Pellye0fd6932012-07-11 10:26:13 -07003271 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003272 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
3273 String opPackageName) {
3274 if (!canCallerAccessMockLocation(opPackageName)) {
3275 return;
3276 }
3277
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003278 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003279 MockProvider mockProvider = mMockProviders.get(provider);
3280 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3282 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003283 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
3285 }
3286
Nick Pellye0fd6932012-07-11 10:26:13 -07003287 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003288 public void clearTestProviderStatus(String provider, String opPackageName) {
3289 if (!canCallerAccessMockLocation(opPackageName)) {
3290 return;
3291 }
3292
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003293 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003294 MockProvider mockProvider = mMockProviders.get(provider);
3295 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3297 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003298 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
3300 }
3301
3302 private void log(String log) {
3303 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003304 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003305 }
3306 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003307
3308 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003309 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003310 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003311
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003312 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003313 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3314 if (mGnssMetricsProvider != null) {
3315 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3316 }
3317 return;
3318 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003319 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003320 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003321 for (Receiver receiver : mReceivers.values()) {
3322 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 }
David Christie2ff96af2014-01-30 16:09:37 -08003324 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003325 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3326 pw.println(" " + entry.getKey() + ":");
3327 for (UpdateRecord record : entry.getValue()) {
3328 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 }
3330 }
Wyatt Riley11cc7492018-01-17 08:48:27 -08003331 pw.println(" Active GnssMeasurement Listeners:");
3332 for (Identity identity : mGnssMeasurementsListeners.values()) {
3333 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3334 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3335 }
3336 pw.println(" Active GnssNavigationMessage Listeners:");
3337 for (Identity identity : mGnssNavigationMessageListeners.values()) {
3338 pw.println(" " + identity.mPid + " " + identity.mUid + " "
3339 + identity.mPackageName + ": " + isThrottlingExemptLocked(identity));
3340 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003341 pw.println(" Overlay Provider Packages:");
3342 for (LocationProviderInterface provider : mProviders) {
3343 if (provider instanceof LocationProviderProxy) {
3344 pw.println(" " + provider.getName() + ": "
3345 + ((LocationProviderProxy) provider).getConnectedPackageName());
3346 }
3347 }
David Christie2ff96af2014-01-30 16:09:37 -08003348 pw.println(" Historical Records by Provider:");
3349 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3350 : mRequestStatistics.statistics.entrySet()) {
3351 PackageProviderKey key = entry.getKey();
3352 PackageStatistics stats = entry.getValue();
3353 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003355 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003356 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3357 String provider = entry.getKey();
3358 Location location = entry.getValue();
3359 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003361
David Christie1b9b7b12013-04-15 15:31:11 -07003362 pw.println(" Last Known Locations Coarse Intervals:");
3363 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3364 String provider = entry.getKey();
3365 Location location = entry.getValue();
3366 pw.println(" " + provider + ": " + location);
3367 }
3368
Nick Pellye0fd6932012-07-11 10:26:13 -07003369 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003371 if (mEnabledProviders.size() > 0) {
3372 pw.println(" Enabled Providers:");
3373 for (String i : mEnabledProviders) {
3374 pw.println(" " + i);
3375 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
3378 if (mDisabledProviders.size() > 0) {
3379 pw.println(" Disabled Providers:");
3380 for (String i : mDisabledProviders) {
3381 pw.println(" " + i);
3382 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003384 pw.append(" ");
3385 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 if (mMockProviders.size() > 0) {
3387 pw.println(" Mock Providers:");
3388 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003389 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003390 }
3391 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003392
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003393 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3394 pw.println(" Throttling Whitelisted Packages:");
3395 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3396 pw.println(" " + packageName);
3397 }
3398 }
3399
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003400 pw.append(" fudger: ");
gomo48f1a642017-11-10 20:35:46 -08003401 mLocationFudger.dump(fd, pw, args);
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003402
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003403 if (args.length > 0 && "short".equals(args[0])) {
3404 return;
3405 }
gomo48f1a642017-11-10 20:35:46 -08003406 for (LocationProviderInterface provider : mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003407 pw.print(provider.getName() + " Internal State");
3408 if (provider instanceof LocationProviderProxy) {
3409 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3410 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003411 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003412 pw.println(":");
3413 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003414 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003415 if (mGnssBatchingInProgress) {
3416 pw.println(" GNSS batching in progress");
3417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418 }
3419 }
3420}