blob: 6cc72deb7faadbf53d85abe8e255e8e1ce5a7d7e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Soonil Nagarkar7decfb62017-01-18 12:18:49 -080019import android.app.ActivityManager;
Svet Ganovadc1cf42015-06-15 16:36:24 -070020import android.content.pm.PackageManagerInternal;
destradaaea8a8a62014-06-23 18:19:03 -070021import com.android.internal.content.PackageMonitor;
22import com.android.internal.location.ProviderProperties;
23import com.android.internal.location.ProviderRequest;
24import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070025import com.android.internal.util.ArrayUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070026import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070027import com.android.server.location.FlpHardwareProvider;
28import com.android.server.location.FusedProxy;
29import com.android.server.location.GeocoderProxy;
30import com.android.server.location.GeofenceManager;
31import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080032import com.android.server.location.GnssLocationProvider;
33import com.android.server.location.GnssMeasurementsProvider;
34import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070035import com.android.server.location.LocationBlacklist;
36import com.android.server.location.LocationFudger;
37import com.android.server.location.LocationProviderInterface;
38import com.android.server.location.LocationProviderProxy;
39import com.android.server.location.LocationRequestStatistics;
40import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
41import com.android.server.location.LocationRequestStatistics.PackageStatistics;
42import com.android.server.location.MockProvider;
43import com.android.server.location.PassiveProvider;
44
Dianne Hackborna06de0f2012-12-11 16:34:47 -080045import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070047import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.ContentResolver;
49import android.content.Context;
50import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070051import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070052import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050053import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.content.pm.PackageManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070055import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050056import android.content.pm.ResolveInfo;
57import android.content.pm.Signature;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050058import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070059import android.database.ContentObserver;
destradaaa4fa3b52014-07-09 10:46:39 -070060import android.hardware.location.ActivityRecognitionHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070062import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050063import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070064import android.location.Geofence;
Lifu Tang818aa2c2016-02-01 01:52:00 -080065import android.location.IGnssMeasurementsListener;
Lifu Tang30f95a72016-01-07 23:20:38 -080066import android.location.IGnssStatusListener;
67import android.location.IGnssStatusProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -070068import android.location.IGpsGeofenceHardware;
Lifu Tang818aa2c2016-02-01 01:52:00 -080069import android.location.IGnssNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.location.ILocationListener;
71import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040072import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.location.Location;
74import android.location.LocationManager;
75import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070076import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Binder;
78import android.os.Bundle;
79import android.os.Handler;
80import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070081import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Message;
83import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070084import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070086import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070087import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070088import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070089import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Tom O'Neilla206a0f2016-12-15 10:26:28 -080091import android.text.TextUtils;
92import android.util.EventLog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080093import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080094import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070095
Mike Lockwood43e33f22010-03-26 10:41:48 -040096import java.io.FileDescriptor;
97import java.io.PrintWriter;
98import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070099import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400100import java.util.HashMap;
101import java.util.HashSet;
102import java.util.List;
103import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400104import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
106/**
107 * The service class that manages LocationProviders and issues location
108 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800110public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800112 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700113
114 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Victoria Lease37425c32012-10-16 16:08:48 -0700116 // Location resolution level: no location data whatsoever
117 private static final int RESOLUTION_LEVEL_NONE = 0;
118 // Location resolution level: coarse location data only
119 private static final int RESOLUTION_LEVEL_COARSE = 1;
120 // Location resolution level: fine location data
121 private static final int RESOLUTION_LEVEL_FINE = 2;
122
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800123 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700124 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800125 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700126 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400127 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700128 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
129
130 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700131 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700132 private static final String FUSED_LOCATION_SERVICE_ACTION =
133 "com.android.location.service.FusedLocationProvider";
134
135 private static final int MSG_LOCATION_CHANGED = 1;
136
David Christie1b9b7b12013-04-15 15:31:11 -0700137 private static final long NANOS_PER_MILLI = 1000000L;
138
David Christie0b837452013-07-29 16:02:13 -0700139 // The maximum interval a location request can have and still be considered "high power".
140 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
141
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800142 // default background throttling interval if not overriden in settings
143 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 1000;
144
Nick Pellyf1be6862012-05-15 10:53:42 -0700145 // Location Providers may sometimes deliver location updates
146 // slightly faster that requested - provide grace period so
147 // we don't unnecessarily filter events that are otherwise on
148 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700149 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700150
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700151 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
152
153 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800154 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700155
156 // used internally for synchronization
157 private final Object mLock = new Object();
158
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700159 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700160 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700161 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700162 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700163 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800164 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700165 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700166 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800167 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700168 private INetInitiatedListener mNetInitiatedListener;
169 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700170 private PassiveProvider mPassiveProvider; // track passive provider for special cases
171 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800172 private GnssMeasurementsProvider mGnssMeasurementsProvider;
173 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700174 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700175
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700176 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700178 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800179 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
181 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800182 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700184 // Mock (test) providers
185 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800186 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700188 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800189 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700191 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500192 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800193 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400194
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700195 // real providers, saved here when mocked out
196 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800197 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700199 // mapping from provider name to provider
200 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800201 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700203 // mapping from provider name to all its UpdateRecords
204 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800205 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700206
David Christie2ff96af2014-01-30 16:09:37 -0800207 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800210 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
David Christie1b9b7b12013-04-15 15:31:11 -0700212 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
213 // locations stored here are not fudged for coarse permissions.
214 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800215 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700216
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700217 // all providers that operate over proxy, for authorizing incoming location
218 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800219 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800220
Victoria Lease38389b62012-09-30 11:44:22 -0700221 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700222 private int mCurrentUserId = UserHandle.USER_SYSTEM;
223 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_SYSTEM };
Victoria Lease38389b62012-09-30 11:44:22 -0700224
Lifu Tang9363b942016-02-16 18:07:00 -0800225 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800226
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700227 public LocationManagerService(Context context) {
228 super();
229 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800230 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800231
Svet Ganovadc1cf42015-06-15 16:36:24 -0700232 // Let the package manager query which are the default location
233 // providers as they get certain permissions granted by default.
234 PackageManagerInternal packageManagerInternal = LocalServices.getService(
235 PackageManagerInternal.class);
236 packageManagerInternal.setLocationPackagesProvider(
237 new PackageManagerInternal.PackagesProvider() {
238 @Override
239 public String[] getPackages(int userId) {
240 return mContext.getResources().getStringArray(
241 com.android.internal.R.array.config_locationProviderPackageNames);
242 }
243 });
244
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700245 if (D) Log.d(TAG, "Constructed");
246
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700247 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700248 }
249
Svetoslav Ganova0027152013-06-25 14:59:53 -0700250 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700251 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700252 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700253
Victoria Lease5cd731a2012-12-19 15:04:21 -0800254 // fetch package manager
255 mPackageManager = mContext.getPackageManager();
256
Victoria Lease0aa28602013-05-29 15:28:26 -0700257 // fetch power manager
258 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800259
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800260 // fetch activity manager
261 mActivityManager
262 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
263
Victoria Lease5cd731a2012-12-19 15:04:21 -0800264 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700265 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800266
267 // prepare mLocationHandler's dependents
268 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
269 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
270 mBlacklist.init();
271 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
272
Dianne Hackbornc2293022013-02-06 23:14:49 -0800273 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700274 AppOpsManager.OnOpChangedListener callback
275 = new AppOpsManager.OnOpChangedInternalListener() {
276 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800277 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700278 for (Receiver receiver : mReceivers.values()) {
279 receiver.updateMonitoring(true);
280 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800281 applyAllProviderRequirementsLocked();
282 }
283 }
284 };
285 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
286
David Christieb870dbf2015-06-22 12:42:53 -0700287 PackageManager.OnPermissionsChangedListener permissionListener
288 = new PackageManager.OnPermissionsChangedListener() {
289 @Override
290 public void onPermissionsChanged(final int uid) {
291 synchronized (mLock) {
292 applyAllProviderRequirementsLocked();
293 }
294 }
295 };
296 mPackageManager.addOnPermissionsChangeListener(permissionListener);
297
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800298 // listen for background/foreground changes
299 ActivityManager.OnUidImportanceListener uidImportanceListener
300 = new ActivityManager.OnUidImportanceListener() {
301 @Override
302 public void onUidImportance(int uid, int importance) {
303 boolean foreground = isImportanceForeground(importance);
304 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
305 synchronized (mLock) {
306 for (Map.Entry<String, ArrayList<UpdateRecord>> entry
307 : mRecordsByProvider.entrySet()) {
308 String provider = entry.getKey();
309 for (UpdateRecord record : entry.getValue()) {
310 if (record.mReceiver.mUid == uid
311 && record.mIsForegroundUid != foreground) {
312 if (D) Log.d(TAG, "request from uid " + uid + " is now "
313 + (foreground ? "foreground" : "background)"));
314 record.mIsForegroundUid = foreground;
315
316 if (!isThrottlingExemptLocked(record.mReceiver)) {
317 affectedProviders.add(provider);
318 }
319 }
320 }
321 }
322 for (String provider : affectedProviders) {
323 applyRequirementsLocked(provider);
324 }
325 }
326
327 }
328 };
329 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
330 ActivityManager.RunningAppProcessInfo.IMPORTANCE_PERCEPTIBLE);
331
Amith Yamasanib27528d2014-06-05 15:02:10 -0700332 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
333 updateUserProfiles(mCurrentUserId);
334
Victoria Lease5cd731a2012-12-19 15:04:21 -0800335 // prepare providers
336 loadProvidersLocked();
337 updateProvidersLocked();
338 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700339
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700340 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700341 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700342 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700343 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800344 @Override
345 public void onChange(boolean selfChange) {
346 synchronized (mLock) {
347 updateProvidersLocked();
348 }
349 }
350 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800351 mContext.getContentResolver().registerContentObserver(
352 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
353 true,
354 new ContentObserver(mLocationHandler) {
355 @Override
356 public void onChange(boolean selfChange) {
357 synchronized (mLock) {
358 updateProvidersLocked();
359 }
360 }
361 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800362 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700363
Victoria Lease38389b62012-09-30 11:44:22 -0700364 // listen for user change
365 IntentFilter intentFilter = new IntentFilter();
366 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700367 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
368 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700369 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700370
371 mContext.registerReceiverAsUser(new BroadcastReceiver() {
372 @Override
373 public void onReceive(Context context, Intent intent) {
374 String action = intent.getAction();
375 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
376 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700377 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
378 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
379 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700380 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700381 // shutdown only if UserId indicates whole system, not just one user
382 if(D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
383 if (getSendingUserId() == UserHandle.USER_ALL) {
384 shutdownComponents();
385 }
Victoria Lease38389b62012-09-30 11:44:22 -0700386 }
387 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800388 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700389 }
390
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800391 private static boolean isImportanceForeground(int importance) {
392 return importance <= ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
393 }
394
Amith Yamasanib27528d2014-06-05 15:02:10 -0700395 /**
destradaab9026982015-08-27 17:34:54 -0700396 * Provides a way for components held by the {@link LocationManagerService} to clean-up
397 * gracefully on system's shutdown.
398 *
399 * NOTES:
400 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
401 * support for components that do not wish to handle such event.
402 */
403 private void shutdownComponents() {
404 if(D) Log.d(TAG, "Shutting down components...");
405
406 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
407 if (gpsProvider != null && gpsProvider.isEnabled()) {
408 gpsProvider.disable();
409 }
410
destradaa2e385072015-10-14 16:45:58 -0700411 // it is needed to check if FLP HW provider is supported before accessing the instance, this
412 // avoids an exception to be thrown by the singleton factory method
413 if (FlpHardwareProvider.isSupported()) {
414 FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaab9026982015-08-27 17:34:54 -0700415 flpHardwareProvider.cleanup();
416 }
417 }
418
419 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700420 * Makes a list of userids that are related to the current user. This is
421 * relevant when using managed profiles. Otherwise the list only contains
422 * the current user.
423 *
424 * @param currentUserId the current user, who might have an alter-ego.
425 */
426 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700427 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700428 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700429 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700430 }
431 }
432
433 /**
434 * Checks if the specified userId matches any of the current foreground
435 * users stored in mCurrentUserProfiles.
436 */
437 private boolean isCurrentProfile(int userId) {
438 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700439 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700440 }
441 }
442
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500443 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
444 PackageManager pm = mContext.getPackageManager();
445 String systemPackageName = mContext.getPackageName();
446 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
447
448 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
449 new Intent(FUSED_LOCATION_SERVICE_ACTION),
450 PackageManager.GET_META_DATA, mCurrentUserId);
451 for (ResolveInfo rInfo : rInfos) {
452 String packageName = rInfo.serviceInfo.packageName;
453
454 // Check that the signature is in the list of supported sigs. If it's not in
455 // this list the standard provider binding logic won't bind to it.
456 try {
457 PackageInfo pInfo;
458 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
459 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
460 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
461 ", but has wrong signature, ignoring");
462 continue;
463 }
464 } catch (NameNotFoundException e) {
465 Log.e(TAG, "missing package: " + packageName);
466 continue;
467 }
468
469 // Get the version info
470 if (rInfo.serviceInfo.metaData == null) {
471 Log.w(TAG, "Found fused provider without metadata: " + packageName);
472 continue;
473 }
474
475 int version = rInfo.serviceInfo.metaData.getInt(
476 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
477 if (version == 0) {
478 // This should be the fallback fused location provider.
479
480 // Make sure it's in the system partition.
481 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
482 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
483 continue;
484 }
485
486 // Check that the fallback is signed the same as the OS
487 // as a proxy for coreApp="true"
488 if (pm.checkSignatures(systemPackageName, packageName)
489 != PackageManager.SIGNATURE_MATCH) {
490 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
491 + packageName);
492 continue;
493 }
494
495 // Found a valid fallback.
496 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
497 return;
498 } else {
499 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
500 }
501 }
502
503 throw new IllegalStateException("Unable to find a fused location provider that is in the "
504 + "system partition with version 0 and signed with the platform certificate. "
505 + "Such a package is needed to provide a default fused location provider in the "
506 + "event that no other fused location provider has been installed or is currently "
507 + "available. For example, coreOnly boot mode when decrypting the data "
508 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
509 }
510
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700511 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700512 // create a passive location provider, which is always enabled
513 PassiveProvider passiveProvider = new PassiveProvider(this);
514 addProviderLocked(passiveProvider);
515 mEnabledProviders.add(passiveProvider.getName());
516 mPassiveProvider = passiveProvider;
517
Lifu Tang30f95a72016-01-07 23:20:38 -0800518 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700519 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800520 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700521 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800522 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800523 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
524 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
525 addProviderLocked(gnssProvider);
526 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800527 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
528 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800529 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700530 }
531
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700532 /*
533 Load package name(s) containing location provider support.
534 These packages can contain services implementing location providers:
535 Geocoder Provider, Network Location Provider, and
536 Fused Location Provider. They will each be searched for
537 service components implementing these providers.
538 The location framework also has support for installation
539 of new location providers at run-time. The new package does not
540 have to be explicitly listed here, however it must have a signature
541 that matches the signature of at least one package on this list.
542 */
543 Resources resources = mContext.getResources();
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800544 ArrayList<String> providerPackageNames = new ArrayList<>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500545 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700546 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500547 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
548 Arrays.toString(pkgs));
549 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
550
551 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700552
553 // bind to network provider
554 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
555 mContext,
556 LocationManager.NETWORK_PROVIDER,
557 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700558 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
559 com.android.internal.R.string.config_networkLocationProviderPackageName,
560 com.android.internal.R.array.config_locationProviderPackageNames,
561 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700562 if (networkProvider != null) {
563 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
564 mProxyProviders.add(networkProvider);
565 addProviderLocked(networkProvider);
566 } else {
567 Slog.w(TAG, "no network location provider found");
568 }
569
570 // bind to fused provider
571 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
572 mContext,
573 LocationManager.FUSED_PROVIDER,
574 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700575 com.android.internal.R.bool.config_enableFusedLocationOverlay,
576 com.android.internal.R.string.config_fusedLocationProviderPackageName,
577 com.android.internal.R.array.config_locationProviderPackageNames,
578 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700579 if (fusedLocationProvider != null) {
580 addProviderLocked(fusedLocationProvider);
581 mProxyProviders.add(fusedLocationProvider);
582 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700583 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700584 } else {
585 Slog.e(TAG, "no fused location provider found",
586 new IllegalStateException("Location service needs a fused location provider"));
587 }
588
589 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700590 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
591 com.android.internal.R.bool.config_enableGeocoderOverlay,
592 com.android.internal.R.string.config_geocoderProviderPackageName,
593 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800594 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700595 if (mGeocodeProvider == null) {
596 Slog.e(TAG, "no geocoder provider found");
597 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700598
destradaaa4fa3b52014-07-09 10:46:39 -0700599 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700600 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
601 // exception, so make sure we only do that when supported
602 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700603 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700604 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700605 FusedProxy fusedProxy = FusedProxy.createAndBind(
606 mContext,
607 mLocationHandler,
608 flpHardwareProvider.getLocationHardware(),
609 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
610 com.android.internal.R.string.config_hardwareFlpPackageName,
611 com.android.internal.R.array.config_locationProviderPackageNames);
612 if (fusedProxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700613 Slog.d(TAG, "Unable to bind FusedProxy.");
destradaaf9a274c2014-07-25 15:11:56 -0700614 }
destradaacfbdcd22014-04-30 11:29:11 -0700615 } else {
destradaabeea4422014-07-30 18:17:21 -0700616 flpHardwareProvider = null;
destradaa6b4893a2016-05-03 15:33:43 -0700617 Slog.d(TAG, "FLP HAL not supported");
destradaaf9a274c2014-07-25 15:11:56 -0700618 }
619
620 // bind to geofence provider
621 GeofenceProxy provider = GeofenceProxy.createAndBind(
622 mContext,com.android.internal.R.bool.config_enableGeofenceOverlay,
623 com.android.internal.R.string.config_geofenceProviderPackageName,
624 com.android.internal.R.array.config_locationProviderPackageNames,
625 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700626 mGpsGeofenceProxy,
destradaabeea4422014-07-30 18:17:21 -0700627 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700628 if (provider == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700629 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700630 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900631
destradaa6e2fe752015-06-23 17:25:53 -0700632 // bind to hardware activity recognition
633 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
634 ActivityRecognitionHardware activityRecognitionHardware = null;
635 if (activityRecognitionHardwareIsSupported) {
636 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700637 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700638 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700639 }
destradaa6e2fe752015-06-23 17:25:53 -0700640 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
641 mContext,
642 mLocationHandler,
643 activityRecognitionHardwareIsSupported,
644 activityRecognitionHardware,
645 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
646 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
647 com.android.internal.R.array.config_locationProviderPackageNames);
648 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700649 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700650 }
destradaaa4fa3b52014-07-09 10:46:39 -0700651
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900652 String[] testProviderStrings = resources.getStringArray(
653 com.android.internal.R.array.config_testLocationProviders);
654 for (String testProviderString : testProviderStrings) {
655 String fragments[] = testProviderString.split(",");
656 String name = fragments[0].trim();
657 if (mProvidersByName.get(name) != null) {
658 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
659 }
660 ProviderProperties properties = new ProviderProperties(
661 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
662 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
663 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
664 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
665 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
666 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
667 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
668 Integer.parseInt(fragments[8]) /* powerRequirement */,
669 Integer.parseInt(fragments[9]) /* accuracy */);
670 addTestProviderLocked(name, properties);
671 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700672 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800674 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700675 * Called when the device's active user changes.
676 * @param userId the new active user's UserId
677 */
678 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800679 if (mCurrentUserId == userId) {
680 return;
681 }
Victoria Lease83762d22012-10-03 13:51:17 -0700682 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800683 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700684 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700685 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700686 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700687 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700688 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700689 }
Victoria Lease38389b62012-09-30 11:44:22 -0700690 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700691 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700692 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700693 }
694 }
695
696 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800697 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
698 * location updates.
699 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700700 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700701 final int mUid; // uid of receiver
702 final int mPid; // pid of receiver
703 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700704 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700705
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800706 final ILocationListener mListener;
707 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700708 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700709 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800710 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700711
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800712 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700713
David Christie0b837452013-07-29 16:02:13 -0700714 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700715 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700716 // True if app ops has started monitoring this receiver for high power (gps) locations.
717 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700718 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700719 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800720
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700721 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700722 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800723 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800724 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700725 if (listener != null) {
726 mKey = listener.asBinder();
727 } else {
728 mKey = intent;
729 }
Victoria Lease37425c32012-10-16 16:08:48 -0700730 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700731 mUid = uid;
732 mPid = pid;
733 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700734 if (workSource != null && workSource.size() <= 0) {
735 workSource = null;
736 }
737 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700738 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700739
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700740 updateMonitoring(true);
741
Victoria Lease0aa28602013-05-29 15:28:26 -0700742 // construct/configure wakelock
743 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700744 if (workSource == null) {
745 workSource = new WorkSource(mUid, mPackageName);
746 }
747 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800748 }
749
750 @Override
751 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800752 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800753 }
754
755 @Override
756 public int hashCode() {
757 return mKey.hashCode();
758 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800760 @Override
761 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700762 StringBuilder s = new StringBuilder();
763 s.append("Reciever[");
764 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800765 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700766 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700768 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800769 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700770 for (String p : mUpdateRecords.keySet()) {
771 s.append(" ").append(mUpdateRecords.get(p).toString());
772 }
773 s.append("]");
774 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800775 }
776
David Christie15b31912013-08-13 15:54:32 -0700777 /**
778 * Update AppOp monitoring for this receiver.
779 *
780 * @param allow If true receiver is currently active, if false it's been removed.
781 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700782 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700783 if (mHideFromAppOps) {
784 return;
785 }
786
David Christie15b31912013-08-13 15:54:32 -0700787 boolean requestingLocation = false;
788 boolean requestingHighPowerLocation = false;
789 if (allow) {
790 // See if receiver has any enabled update records. Also note if any update records
791 // are high power (has a high power provider with an interval under a threshold).
792 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
793 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
794 requestingLocation = true;
795 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800796 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700797 ProviderProperties properties = locationProvider != null
798 ? locationProvider.getProperties() : null;
799 if (properties != null
800 && properties.mPowerRequirement == Criteria.POWER_HIGH
801 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
802 requestingHighPowerLocation = true;
803 break;
804 }
805 }
806 }
807 }
808
David Christie0b837452013-07-29 16:02:13 -0700809 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700810 mOpMonitoring = updateMonitoring(
811 requestingLocation,
812 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700813 AppOpsManager.OP_MONITOR_LOCATION);
814
815 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700816 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700817 mOpHighPowerMonitoring = updateMonitoring(
818 requestingHighPowerLocation,
819 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700820 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700821 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700822 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700823 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
824 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
825 }
David Christie0b837452013-07-29 16:02:13 -0700826 }
827
828 /**
829 * Update AppOps monitoring for a single location request and op type.
830 *
831 * @param allowMonitoring True if monitoring is allowed for this request/op.
832 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
833 * @param op AppOps code for the op to update.
834 * @return True if monitoring is on for this request/op after updating.
835 */
836 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
837 int op) {
838 if (!currentlyMonitoring) {
839 if (allowMonitoring) {
840 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
841 == AppOpsManager.MODE_ALLOWED;
842 }
843 } else {
844 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
845 != AppOpsManager.MODE_ALLOWED) {
846 mAppOps.finishOp(op, mUid, mPackageName);
847 return false;
848 }
849 }
850
851 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700852 }
853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 public boolean isListener() {
855 return mListener != null;
856 }
857
858 public boolean isPendingIntent() {
859 return mPendingIntent != null;
860 }
861
862 public ILocationListener getListener() {
863 if (mListener != null) {
864 return mListener;
865 }
866 throw new IllegalStateException("Request for non-existent listener");
867 }
868
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
870 if (mListener != null) {
871 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700872 synchronized (this) {
873 // synchronize to ensure incrementPendingBroadcastsLocked()
874 // is called before decrementPendingBroadcasts()
875 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700876 // call this after broadcasting so we do not increment
877 // if we throw an exeption.
878 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 } catch (RemoteException e) {
881 return false;
882 }
883 } else {
884 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800885 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800886 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
887 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700888 synchronized (this) {
889 // synchronize to ensure incrementPendingBroadcastsLocked()
890 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700891 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700892 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700893 // call this after broadcasting so we do not increment
894 // if we throw an exeption.
895 incrementPendingBroadcastsLocked();
896 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800897 } catch (PendingIntent.CanceledException e) {
898 return false;
899 }
900 }
901 return true;
902 }
903
904 public boolean callLocationChangedLocked(Location location) {
905 if (mListener != null) {
906 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700907 synchronized (this) {
908 // synchronize to ensure incrementPendingBroadcastsLocked()
909 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800910 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700911 // call this after broadcasting so we do not increment
912 // if we throw an exeption.
913 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700914 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800915 } catch (RemoteException e) {
916 return false;
917 }
918 } else {
919 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800920 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800921 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700922 synchronized (this) {
923 // synchronize to ensure incrementPendingBroadcastsLocked()
924 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700925 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700926 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700927 // call this after broadcasting so we do not increment
928 // if we throw an exeption.
929 incrementPendingBroadcastsLocked();
930 }
931 } catch (PendingIntent.CanceledException e) {
932 return false;
933 }
934 }
935 return true;
936 }
937
938 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700939 // First update AppOp monitoring.
940 // An app may get/lose location access as providers are enabled/disabled.
941 updateMonitoring(true);
942
Mike Lockwood48f17512009-04-23 09:12:08 -0700943 if (mListener != null) {
944 try {
945 synchronized (this) {
946 // synchronize to ensure incrementPendingBroadcastsLocked()
947 // is called before decrementPendingBroadcasts()
948 if (enabled) {
949 mListener.onProviderEnabled(provider);
950 } else {
951 mListener.onProviderDisabled(provider);
952 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700953 // call this after broadcasting so we do not increment
954 // if we throw an exeption.
955 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700956 }
957 } catch (RemoteException e) {
958 return false;
959 }
960 } else {
961 Intent providerIntent = new Intent();
962 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
963 try {
964 synchronized (this) {
965 // synchronize to ensure incrementPendingBroadcastsLocked()
966 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700967 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700968 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700969 // call this after broadcasting so we do not increment
970 // if we throw an exeption.
971 incrementPendingBroadcastsLocked();
972 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 } catch (PendingIntent.CanceledException e) {
974 return false;
975 }
976 }
977 return true;
978 }
979
Nick Pellyf1be6862012-05-15 10:53:42 -0700980 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700982 if (D) Log.d(TAG, "Location listener died");
983
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400984 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 removeUpdatesLocked(this);
986 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700987 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700988 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700989 }
990 }
991
Nick Pellye0fd6932012-07-11 10:26:13 -0700992 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700993 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
994 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400995 synchronized (this) {
996 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700997 }
998 }
999
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001000 // this must be called while synchronized by caller in a synchronized block
1001 // containing the sending of the broadcaset
1002 private void incrementPendingBroadcastsLocked() {
1003 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001004 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001005 }
1006 }
1007
1008 private void decrementPendingBroadcastsLocked() {
1009 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001010 if (mWakeLock.isHeld()) {
1011 mWakeLock.release();
1012 }
1013 }
1014 }
1015
1016 public void clearPendingBroadcastsLocked() {
1017 if (mPendingBroadcasts > 0) {
1018 mPendingBroadcasts = 0;
1019 if (mWakeLock.isHeld()) {
1020 mWakeLock.release();
1021 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001022 }
1023 }
1024 }
1025
Nick Pellye0fd6932012-07-11 10:26:13 -07001026 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001027 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001028 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001029 //the receiver list if it is not found. If it is not found then the
1030 //LocationListener was removed when it had a pending broadcast and should
1031 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001032 synchronized (mLock) {
1033 IBinder binder = listener.asBinder();
1034 Receiver receiver = mReceivers.get(binder);
1035 if (receiver != null) {
1036 synchronized (receiver) {
1037 // so wakelock calls will succeed
1038 long identity = Binder.clearCallingIdentity();
1039 receiver.decrementPendingBroadcastsLocked();
1040 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001041 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 }
1044 }
1045
Lifu Tang82f893d2016-01-21 18:15:33 -08001046 /**
Lifu Tang9363b942016-02-16 18:07:00 -08001047 * Returns the system information of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001048 */
1049 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001050 public int getGnssYearOfHardware() {
Lifu Tang818aa2c2016-02-01 01:52:00 -08001051 if (mGnssNavigationMessageProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001052 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001053 } else {
1054 return 0;
1055 }
1056 }
1057
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001058 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001059 mProviders.add(provider);
1060 mProvidersByName.put(provider.getName(), provider);
1061 }
1062
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001063 private void removeProviderLocked(LocationProviderInterface provider) {
1064 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001065 mProviders.remove(provider);
1066 mProvidersByName.remove(provider.getName());
1067 }
1068
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001069 private boolean isOverlayProviderPackageLocked(String packageName) {
1070 for (LocationProviderInterface provider : mProviders) {
1071 if (provider instanceof LocationProviderProxy) {
1072 if (packageName.equals(
1073 ((LocationProviderProxy) provider).getConnectedPackageName())) {
1074 return true;
1075 }
1076 }
1077 }
1078
1079 return false;
1080 }
1081
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001082 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001083 * Returns "true" if access to the specified location provider is allowed by the current
1084 * user's settings. Access to all location providers is forbidden to non-location-provider
1085 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001086 *
1087 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001088 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001089 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 if (mEnabledProviders.contains(provider)) {
1091 return true;
1092 }
1093 if (mDisabledProviders.contains(provider)) {
1094 return false;
1095 }
1096 // Use system settings
1097 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001098
Victoria Leaseb711d572012-10-02 13:14:11 -07001099 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 }
1101
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001102 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001103 * Returns "true" if access to the specified location provider is allowed by the specified
1104 * user's settings. Access to all location providers is forbidden to non-location-provider
1105 * processes belonging to background users.
1106 *
1107 * @param provider the name of the location provider
1108 * @param uid the requestor's UID
Victoria Lease09eeaec2013-02-05 11:34:13 -08001109 */
1110 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001111 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001112 return false;
1113 }
1114 return isAllowedByCurrentUserSettingsLocked(provider);
1115 }
1116
1117 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001118 * Returns the permission string associated with the specified resolution level.
1119 *
1120 * @param resolutionLevel the resolution level
1121 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001122 */
Victoria Lease37425c32012-10-16 16:08:48 -07001123 private String getResolutionPermission(int resolutionLevel) {
1124 switch (resolutionLevel) {
1125 case RESOLUTION_LEVEL_FINE:
1126 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1127 case RESOLUTION_LEVEL_COARSE:
1128 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1129 default:
1130 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001132 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001133
Victoria Leaseda479c52012-10-15 15:24:16 -07001134 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001135 * Returns the resolution level allowed to the given PID/UID pair.
1136 *
1137 * @param pid the PID
1138 * @param uid the UID
1139 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001140 */
Victoria Lease37425c32012-10-16 16:08:48 -07001141 private int getAllowedResolutionLevel(int pid, int uid) {
1142 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1143 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1144 return RESOLUTION_LEVEL_FINE;
1145 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1146 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1147 return RESOLUTION_LEVEL_COARSE;
1148 } else {
1149 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001150 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001151 }
1152
1153 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001154 * Returns the resolution level allowed to the caller
1155 *
1156 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001157 */
Victoria Lease37425c32012-10-16 16:08:48 -07001158 private int getCallerAllowedResolutionLevel() {
1159 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1160 }
1161
1162 /**
1163 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1164 *
1165 * @param allowedResolutionLevel resolution level allowed to caller
1166 */
1167 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1168 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001169 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1170 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172
Victoria Lease37425c32012-10-16 16:08:48 -07001173 /**
1174 * Return the minimum resolution level required to use the specified location provider.
1175 *
1176 * @param provider the name of the location provider
1177 * @return minimum resolution level required for provider
1178 */
1179 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001180 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1181 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1182 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001183 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001184 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1185 LocationManager.FUSED_PROVIDER.equals(provider)) {
1186 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001187 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001188 } else {
1189 // mock providers
1190 LocationProviderInterface lp = mMockProviders.get(provider);
1191 if (lp != null) {
1192 ProviderProperties properties = lp.getProperties();
1193 if (properties != null) {
1194 if (properties.mRequiresSatellite) {
1195 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001196 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001197 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1198 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001199 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001200 }
1201 }
1202 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001203 }
Victoria Lease37425c32012-10-16 16:08:48 -07001204 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001205 }
1206
Victoria Lease37425c32012-10-16 16:08:48 -07001207 /**
1208 * Throw SecurityException if specified resolution level is insufficient to use the named
1209 * location provider.
1210 *
1211 * @param allowedResolutionLevel resolution level allowed to caller
1212 * @param providerName the name of the location provider
1213 */
1214 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1215 String providerName) {
1216 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1217 if (allowedResolutionLevel < requiredResolutionLevel) {
1218 switch (requiredResolutionLevel) {
1219 case RESOLUTION_LEVEL_FINE:
1220 throw new SecurityException("\"" + providerName + "\" location provider " +
1221 "requires ACCESS_FINE_LOCATION permission.");
1222 case RESOLUTION_LEVEL_COARSE:
1223 throw new SecurityException("\"" + providerName + "\" location provider " +
1224 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1225 default:
1226 throw new SecurityException("Insufficient permission for \"" + providerName +
1227 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001228 }
1229 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001230 }
1231
David Christie82edc9b2013-07-19 11:31:42 -07001232 /**
1233 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1234 * for battery).
1235 */
David Christie40e57822013-07-30 11:36:48 -07001236 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001237 mContext.enforceCallingOrSelfPermission(
1238 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1239 }
1240
David Christie40e57822013-07-30 11:36:48 -07001241 private void checkUpdateAppOpsAllowed() {
1242 mContext.enforceCallingOrSelfPermission(
1243 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1244 }
1245
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001246 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001247 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1248 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001249 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001250 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001251 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001252 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001253 }
1254 return -1;
1255 }
1256
David Christieb870dbf2015-06-22 12:42:53 -07001257 boolean reportLocationAccessNoThrow(
1258 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001259 int op = resolutionLevelToOp(allowedResolutionLevel);
1260 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001261 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1262 return false;
1263 }
1264 }
David Christieb870dbf2015-06-22 12:42:53 -07001265
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001266 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001267 }
1268
David Christieb870dbf2015-06-22 12:42:53 -07001269 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001270 int op = resolutionLevelToOp(allowedResolutionLevel);
1271 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001272 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1273 return false;
1274 }
1275 }
David Christieb870dbf2015-06-22 12:42:53 -07001276
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001277 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001278 }
1279
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001280 /**
1281 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001282 * fused, also including ones that are not permitted to
1283 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001284 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001285 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001287 ArrayList<String> out;
1288 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001289 out = new ArrayList<>(mProviders.size());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001290 for (LocationProviderInterface provider : mProviders) {
1291 String name = provider.getName();
1292 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001293 continue;
1294 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 out.add(name);
1296 }
1297 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001298
1299 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001300 return out;
1301 }
1302
Mike Lockwood03ca2162010-04-01 08:10:09 -07001303 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001304 * Return all providers by name, that match criteria and are optionally
1305 * enabled.
1306 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001307 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001308 @Override
1309 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001310 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001311 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001312 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001313 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001314 try {
1315 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001316 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001317 for (LocationProviderInterface provider : mProviders) {
1318 String name = provider.getName();
1319 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001320 continue;
1321 }
Victoria Lease37425c32012-10-16 16:08:48 -07001322 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001323 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001324 continue;
1325 }
1326 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1327 name, provider.getProperties(), criteria)) {
1328 continue;
1329 }
1330 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001331 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001332 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001333 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001334 } finally {
1335 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001336 }
1337
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001338 if (D) Log.d(TAG, "getProviders()=" + out);
1339 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001340 }
1341
1342 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001343 * Return the name of the best provider given a Criteria object.
1344 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001345 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001346 * has been deprecated as well. So this method now uses
1347 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001348 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001349 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001350 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001351 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001352
1353 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001354 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001355 result = pickBest(providers);
1356 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1357 return result;
1358 }
1359 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001360 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001361 result = pickBest(providers);
1362 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1363 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001364 }
1365
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001366 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001367 return null;
1368 }
1369
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001370 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001371 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001372 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001373 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1374 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001375 } else {
1376 return providers.get(0);
1377 }
1378 }
1379
Nick Pellye0fd6932012-07-11 10:26:13 -07001380 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001381 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1382 LocationProviderInterface p = mProvidersByName.get(provider);
1383 if (p == null) {
1384 throw new IllegalArgumentException("provider=" + provider);
1385 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001386
1387 boolean result = LocationProvider.propertiesMeetCriteria(
1388 p.getName(), p.getProperties(), criteria);
1389 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1390 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001391 }
1392
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001394 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001395 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001396 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001397 boolean isEnabled = p.isEnabled();
1398 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001399 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001401 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001402 // If any provider has been disabled, clear all last locations for all providers.
1403 // This is to be on the safe side in case a provider has location derived from
1404 // this disabled provider.
1405 mLastLocation.clear();
1406 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001407 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001409 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001410 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001412 }
1413 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001414 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1415 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001416 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1417 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
1419 }
1420
Amith Yamasanib27528d2014-06-05 15:02:10 -07001421 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 int listeners = 0;
1423
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001424 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001425 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426
1427 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1430 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001431 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001432 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001433 // Sends a notification message to the receiver
1434 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1435 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001436 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001437 }
1438 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001440 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443 }
1444
1445 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001446 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 removeUpdatesLocked(deadReceivers.get(i));
1448 }
1449 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 if (enabled) {
1452 p.enable();
1453 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001454 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001455 }
1456 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 }
1460
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001461 private void applyRequirementsLocked(String provider) {
1462 LocationProviderInterface p = mProvidersByName.get(provider);
1463 if (p == null) return;
1464
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001466 WorkSource worksource = new WorkSource();
1467 ProviderRequest providerRequest = new ProviderRequest();
1468
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001469 ContentResolver resolver = mContext.getContentResolver();
1470 long backgroundThrottleInterval = Settings.Global.getLong(
1471 resolver,
1472 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1473 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
1474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001476 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001477 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001478 if (checkLocationAccess(
1479 record.mReceiver.mPid,
1480 record.mReceiver.mUid,
1481 record.mReceiver.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001482 record.mReceiver.mAllowedResolutionLevel)) {
1483 LocationRequest locationRequest = record.mRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001484 long interval = locationRequest.getInterval();
1485
1486 if (!isThrottlingExemptLocked(record.mReceiver)) {
1487 if (!record.mIsForegroundUid) {
1488 interval = Math.max(interval, backgroundThrottleInterval);
1489 }
1490 if (interval != locationRequest.getInterval()) {
1491 locationRequest = new LocationRequest(locationRequest);
1492 locationRequest.setInterval(interval);
1493 }
1494 }
1495
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001496 providerRequest.locationRequests.add(locationRequest);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001497 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001498 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001499 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001500 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001501 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001502 }
1503 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001504
1505 if (providerRequest.reportLocation) {
1506 // calculate who to blame for power
1507 // This is somewhat arbitrary. We pick a threshold interval
1508 // that is slightly higher that the minimum interval, and
1509 // spread the blame across all applications with a request
1510 // under that threshold.
1511 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1512 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001513 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001514 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001515
1516 // Don't assign battery blame for update records whose
1517 // client has no permission to receive location data.
1518 if (!providerRequest.locationRequests.contains(locationRequest)) {
1519 continue;
1520 }
1521
Victoria Leaseb711d572012-10-02 13:14:11 -07001522 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001523 if (record.mReceiver.mWorkSource != null
1524 && record.mReceiver.mWorkSource.size() > 0
1525 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001526 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001527 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001528 worksource.add(record.mReceiver.mWorkSource);
1529 } else {
1530 // Assign blame to caller.
1531 worksource.add(
1532 record.mReceiver.mUid,
1533 record.mReceiver.mPackageName);
1534 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001535 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001536 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001540
1541 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1542 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001543 }
1544
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001545 private boolean isThrottlingExemptLocked(Receiver recevier) {
1546 return isOverlayProviderPackageLocked(recevier.mPackageName);
1547 }
1548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 private class UpdateRecord {
1550 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001551 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001553 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001554 Location mLastFixBroadcast;
1555 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556
1557 /**
1558 * Note: must be constructed with lock held.
1559 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001560 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001562 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001564 mIsForegroundUid = isImportanceForeground(
1565 mActivityManager.getPackageImportance(mReceiver.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566
1567 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1568 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001569 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001570 mRecordsByProvider.put(provider, records);
1571 }
1572 if (!records.contains(this)) {
1573 records.add(this);
1574 }
David Christie2ff96af2014-01-30 16:09:37 -08001575
1576 // Update statistics for historical location requests by package/provider
1577 mRequestStatistics.startRequesting(
1578 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 }
1580
1581 /**
David Christie2ff96af2014-01-30 16:09:37 -08001582 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001584 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001585 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1586
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001587 // remove from mRecordsByProvider
1588 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1589 if (globalRecords != null) {
1590 globalRecords.remove(this);
1591 }
1592
1593 if (!removeReceiver) return; // the caller will handle the rest
1594
1595 // remove from Receiver#mUpdateRecords
1596 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1597 if (receiverRecords != null) {
1598 receiverRecords.remove(this.mProvider);
1599
1600 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001601 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001602 removeUpdatesLocked(mReceiver);
1603 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001604 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
1606
1607 @Override
1608 public String toString() {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001609 return "UpdateRecord[" + mProvider + " " + mReceiver.mPackageName
1610 + "(" + mReceiver.mUid + (mIsForegroundUid ? " foreground" : " background")
1611 + ")" + " " + mRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001612 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001615 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001616 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001617 IBinder binder = listener.asBinder();
1618 Receiver receiver = mReceivers.get(binder);
1619 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001620 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1621 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001622 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001623 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001624 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001625 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001626 return null;
1627 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001628 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001629 }
1630 return receiver;
1631 }
1632
David Christie82edc9b2013-07-19 11:31:42 -07001633 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001634 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001635 Receiver receiver = mReceivers.get(intent);
1636 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001637 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1638 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001639 mReceivers.put(intent, receiver);
1640 }
1641 return receiver;
1642 }
1643
Victoria Lease37425c32012-10-16 16:08:48 -07001644 /**
1645 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1646 * and consistency requirements.
1647 *
1648 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001649 * @return a version of request that meets the given resolution and consistency requirements
1650 * @hide
1651 */
1652 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1653 LocationRequest sanitizedRequest = new LocationRequest(request);
1654 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1655 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001656 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001657 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001658 break;
1659 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001660 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001661 break;
1662 }
1663 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001664 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1665 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001666 }
Victoria Lease37425c32012-10-16 16:08:48 -07001667 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1668 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001669 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001670 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001671 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001672 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001673 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001674 }
Victoria Lease37425c32012-10-16 16:08:48 -07001675 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001676 }
1677
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001678 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001679 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001680 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001681 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001682 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001683 String[] packages = mPackageManager.getPackagesForUid(uid);
1684 if (packages == null) {
1685 throw new SecurityException("invalid UID " + uid);
1686 }
1687 for (String pkg : packages) {
1688 if (packageName.equals(pkg)) return;
1689 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001690 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001691 }
1692
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001693 private void checkPendingIntent(PendingIntent intent) {
1694 if (intent == null) {
1695 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001696 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001697 }
1698
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001699 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001700 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001701 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001702 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001703 } else if (intent != null && listener != null) {
1704 throw new IllegalArgumentException("cannot register both listener and intent");
1705 } else if (intent != null) {
1706 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001707 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001708 } else {
David Christie40e57822013-07-30 11:36:48 -07001709 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001710 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001711 }
1712
Nick Pellye0fd6932012-07-11 10:26:13 -07001713 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001714 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1715 PendingIntent intent, String packageName) {
1716 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1717 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001718 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1719 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1720 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07001721 WorkSource workSource = request.getWorkSource();
1722 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07001723 checkDeviceStatsAllowed();
1724 }
1725 boolean hideFromAppOps = request.getHideFromAppOps();
1726 if (hideFromAppOps) {
1727 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07001728 }
Victoria Lease37425c32012-10-16 16:08:48 -07001729 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001731 final int pid = Binder.getCallingPid();
1732 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001733 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 long identity = Binder.clearCallingIdentity();
1735 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001736 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1737 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07001738 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001739
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001740 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001741 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07001742 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07001743 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001744 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001745 } finally {
1746 Binder.restoreCallingIdentity(identity);
1747 }
1748 }
1749
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001750 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1751 int pid, int uid, String packageName) {
1752 // Figure out the provider. Either its explicitly request (legacy use cases), or
1753 // use the fused provider
1754 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1755 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001756 if (name == null) {
1757 throw new IllegalArgumentException("provider name must not be null");
1758 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001759
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001760 LocationProviderInterface provider = mProvidersByName.get(name);
1761 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07001762 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001763 }
1764
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001765 UpdateRecord record = new UpdateRecord(name, request, receiver);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001766 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1767 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
1768 + (record.mIsForegroundUid ? "foreground" : "background")
1769 + (isOverlayProviderPackageLocked(receiver.mPackageName) ? " [whitelisted]" : "") + ")");
1770
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001771 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1772 if (oldRecord != null) {
1773 oldRecord.disposeLocked(false);
1774 }
1775
Victoria Lease09eeaec2013-02-05 11:34:13 -08001776 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001777 if (isProviderEnabled) {
1778 applyRequirementsLocked(name);
1779 } else {
1780 // Notify the listener that updates are currently disabled
1781 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 }
David Christie0b837452013-07-29 16:02:13 -07001783 // Update the monitoring here just in case multiple location requests were added to the
1784 // same receiver (this request may be high power and the initial might not have been).
1785 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787
Nick Pellye0fd6932012-07-11 10:26:13 -07001788 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001789 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1790 String packageName) {
1791 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001792
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001793 final int pid = Binder.getCallingPid();
1794 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001795
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001796 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07001797 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07001798 boolean hideFromAppOps = false;
1799 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
1800 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001801
1802 // providers may use public location API's, need to clear identity
1803 long identity = Binder.clearCallingIdentity();
1804 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001805 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001806 } finally {
1807 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
1810 }
1811
1812 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001813 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001814
1815 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1816 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1817 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001818 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07001822 receiver.updateMonitoring(false);
1823
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001824 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001825 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001826 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1827 if (oldRecords != null) {
1828 // Call dispose() on the obsolete update records.
1829 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08001830 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001831 record.disposeLocked(false);
1832 }
1833 // Accumulate providers
1834 providers.addAll(oldRecords.keySet());
1835 }
1836
1837 // update provider
1838 for (String provider : providers) {
1839 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001840 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001841 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 }
1843
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001844 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
1847
Dianne Hackbornc2293022013-02-06 23:14:49 -08001848 private void applyAllProviderRequirementsLocked() {
1849 for (LocationProviderInterface p : mProviders) {
1850 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001851 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001852 continue;
1853 }
1854
1855 applyRequirementsLocked(p.getName());
1856 }
1857 }
1858
Nick Pellye0fd6932012-07-11 10:26:13 -07001859 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001860 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001861 if (D) Log.d(TAG, "getLastLocation: " + request);
1862 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001863 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001864 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001865 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1866 request.getProvider());
1867 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001868
David Christieb870dbf2015-06-22 12:42:53 -07001869 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001870 final int uid = Binder.getCallingUid();
1871 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001872 try {
1873 if (mBlacklist.isBlacklisted(packageName)) {
1874 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1875 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001876 return null;
1877 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001878
David Christieb870dbf2015-06-22 12:42:53 -07001879 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001880 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1881 packageName);
1882 return null;
1883 }
1884
Victoria Leaseb711d572012-10-02 13:14:11 -07001885 synchronized (mLock) {
1886 // Figure out the provider. Either its explicitly request (deprecated API's),
1887 // or use the fused provider
1888 String name = request.getProvider();
1889 if (name == null) name = LocationManager.FUSED_PROVIDER;
1890 LocationProviderInterface provider = mProvidersByName.get(name);
1891 if (provider == null) return null;
1892
Victoria Lease09eeaec2013-02-05 11:34:13 -08001893 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001894
David Christie1b9b7b12013-04-15 15:31:11 -07001895 Location location;
1896 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1897 // Make sure that an app with coarse permissions can't get frequent location
1898 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1899 location = mLastLocationCoarseInterval.get(name);
1900 } else {
1901 location = mLastLocation.get(name);
1902 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001903 if (location == null) {
1904 return null;
1905 }
Victoria Lease37425c32012-10-16 16:08:48 -07001906 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001907 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1908 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001909 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001910 }
Victoria Lease37425c32012-10-16 16:08:48 -07001911 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001912 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001913 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001914 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001915 return null;
1916 } finally {
1917 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001918 }
1919 }
1920
1921 @Override
1922 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1923 String packageName) {
1924 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001925 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1926 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001927 checkPendingIntent(intent);
1928 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001929 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1930 request.getProvider());
1931 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001932
Victoria Lease37425c32012-10-16 16:08:48 -07001933 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001934
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001935 // geo-fence manager uses the public location API, need to clear identity
1936 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07001937 // TODO: http://b/23822629
1938 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08001939 // temporary measure until geofences work for secondary users
1940 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1941 return;
1942 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001943 long identity = Binder.clearCallingIdentity();
1944 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001945 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1946 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001947 } finally {
1948 Binder.restoreCallingIdentity(identity);
1949 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001950 }
1951
1952 @Override
1953 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001954 checkPendingIntent(intent);
1955 checkPackageName(packageName);
1956
1957 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1958
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001959 // geo-fence manager uses the public location API, need to clear identity
1960 long identity = Binder.clearCallingIdentity();
1961 try {
1962 mGeofenceManager.removeFence(geofence, intent);
1963 } finally {
1964 Binder.restoreCallingIdentity(identity);
1965 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001966 }
1967
1968
1969 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08001970 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001971 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1972 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001973 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001974
David Christieb870dbf2015-06-22 12:42:53 -07001975 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001976 final int uid = Binder.getCallingUid();
1977 final long ident = Binder.clearCallingIdentity();
1978 try {
David Christieb870dbf2015-06-22 12:42:53 -07001979 if (!checkLocationAccess(pid, uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001980 return false;
1981 }
1982 } finally {
1983 Binder.restoreCallingIdentity(ident);
1984 }
1985
Lifu Tang30f95a72016-01-07 23:20:38 -08001986 if (mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09001987 return false;
1988 }
1989
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08001991 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08001993 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001994 return false;
1995 }
1996 return true;
1997 }
1998
Nick Pellye0fd6932012-07-11 10:26:13 -07001999 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002000 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002001 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002002 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002003 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002004 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002005 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002006 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002007 }
2008 }
2009
Nick Pellye0fd6932012-07-11 10:26:13 -07002010 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002011 public boolean addGnssMeasurementsListener(
2012 IGnssMeasurementsListener listener,
destradaaea8a8a62014-06-23 18:19:03 -07002013 String packageName) {
2014 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2015 checkResolutionLevelIsSufficientForProviderUse(
2016 allowedResolutionLevel,
2017 LocationManager.GPS_PROVIDER);
2018
David Christieb870dbf2015-06-22 12:42:53 -07002019 int pid = Binder.getCallingPid();
destradaaea8a8a62014-06-23 18:19:03 -07002020 int uid = Binder.getCallingUid();
2021 long identity = Binder.clearCallingIdentity();
2022 boolean hasLocationAccess;
2023 try {
David Christieb870dbf2015-06-22 12:42:53 -07002024 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
destradaaea8a8a62014-06-23 18:19:03 -07002025 } finally {
2026 Binder.restoreCallingIdentity(identity);
2027 }
2028
Lifu Tang818aa2c2016-02-01 01:52:00 -08002029 if (!hasLocationAccess || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002030 return false;
2031 }
Lifu Tang818aa2c2016-02-01 01:52:00 -08002032 return mGnssMeasurementsProvider.addListener(listener);
destradaaea8a8a62014-06-23 18:19:03 -07002033 }
2034
2035 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002036 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2037 if (mGnssMeasurementsProvider != null) {
2038 mGnssMeasurementsProvider.removeListener(listener);
Wei Liu5241a4c2015-05-11 14:00:36 -07002039 }
destradaaea8a8a62014-06-23 18:19:03 -07002040 }
2041
2042 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002043 public boolean addGnssNavigationMessageListener(
2044 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002045 String packageName) {
2046 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2047 checkResolutionLevelIsSufficientForProviderUse(
2048 allowedResolutionLevel,
2049 LocationManager.GPS_PROVIDER);
2050
David Christieb870dbf2015-06-22 12:42:53 -07002051 int pid = Binder.getCallingPid();
destradaa4b3e3932014-07-21 18:01:47 -07002052 int uid = Binder.getCallingUid();
2053 long identity = Binder.clearCallingIdentity();
2054 boolean hasLocationAccess;
2055 try {
David Christieb870dbf2015-06-22 12:42:53 -07002056 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
destradaa4b3e3932014-07-21 18:01:47 -07002057 } finally {
2058 Binder.restoreCallingIdentity(identity);
2059 }
2060
Lifu Tang818aa2c2016-02-01 01:52:00 -08002061 if (!hasLocationAccess || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002062 return false;
2063 }
Lifu Tang818aa2c2016-02-01 01:52:00 -08002064 return mGnssNavigationMessageProvider.addListener(listener);
destradaa4b3e3932014-07-21 18:01:47 -07002065 }
2066
2067 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002068 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2069 if (mGnssNavigationMessageProvider != null) {
2070 mGnssNavigationMessageProvider.removeListener(listener);
Wei Liu5241a4c2015-05-11 14:00:36 -07002071 }
destradaa4b3e3932014-07-21 18:01:47 -07002072 }
2073
2074 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002075 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002076 if (provider == null) {
2077 // throw NullPointerException to remain compatible with previous implementation
2078 throw new NullPointerException();
2079 }
Victoria Lease37425c32012-10-16 16:08:48 -07002080 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2081 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002082
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002083 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002084 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 != PackageManager.PERMISSION_GRANTED)) {
2086 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2087 }
2088
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002089 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002090 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002091 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002092
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002093 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002094 }
2095 }
2096
Nick Pellye0fd6932012-07-11 10:26:13 -07002097 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002098 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002099 if (Binder.getCallingUid() != Process.myUid()) {
2100 throw new SecurityException(
2101 "calling sendNiResponse from outside of the system is not allowed");
2102 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002103 try {
2104 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002105 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002106 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002107 return false;
2108 }
2109 }
2110
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002111 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002112 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002113 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114 * accessed by the caller
2115 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002116 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002117 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002118 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002119 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002120 }
2121
Victoria Lease37425c32012-10-16 16:08:48 -07002122 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2123 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002124
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002125 LocationProviderInterface p;
2126 synchronized (mLock) {
2127 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002128 }
2129
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002130 if (p == null) return null;
2131 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002132 }
2133
Jason Monkb71218a2015-06-17 14:44:39 -04002134 /**
2135 * @return null if the provider does not exist
2136 * @throws SecurityException if the provider is not allowed to be
2137 * accessed by the caller
2138 */
2139 @Override
2140 public String getNetworkProviderPackage() {
2141 LocationProviderInterface p;
2142 synchronized (mLock) {
2143 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2144 return null;
2145 }
2146 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2147 }
2148
2149 if (p instanceof LocationProviderProxy) {
2150 return ((LocationProviderProxy) p).getConnectedPackageName();
2151 }
2152 return null;
2153 }
2154
Nick Pellye0fd6932012-07-11 10:26:13 -07002155 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07002157 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2158 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002159 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2160
Victoria Lease09eeaec2013-02-05 11:34:13 -08002161 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002162 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002163 try {
2164 synchronized (mLock) {
2165 LocationProviderInterface p = mProvidersByName.get(provider);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002166 return p != null && isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07002167 }
2168 } finally {
2169 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002170 }
2171 }
2172
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002173 /**
2174 * Returns "true" if the UID belongs to a bound location provider.
2175 *
2176 * @param uid the uid
2177 * @return true if uid belongs to a bound location provider
2178 */
2179 private boolean isUidALocationProvider(int uid) {
2180 if (uid == Process.SYSTEM_UID) {
2181 return true;
2182 }
2183 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002184 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002185 }
2186 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002187 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002188 }
2189 return false;
2190 }
2191
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002192 private void checkCallerIsProvider() {
2193 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
2194 == PackageManager.PERMISSION_GRANTED) {
2195 return;
2196 }
2197
2198 // Previously we only used the INSTALL_LOCATION_PROVIDER
2199 // check. But that is system or signature
2200 // protection level which is not flexible enough for
2201 // providers installed oustide the system image. So
2202 // also allow providers with a UID matching the
2203 // currently bound package name
2204
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002205 if (isUidALocationProvider(Binder.getCallingUid())) {
2206 return;
2207 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002208
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002209 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2210 "or UID of a currently bound location provider");
2211 }
2212
David Christie1f141c12014-05-14 15:11:15 -07002213 /**
2214 * Returns true if the given package belongs to the given uid.
2215 */
2216 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002217 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002218 return false;
2219 }
David Christie1f141c12014-05-14 15:11:15 -07002220 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2221 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002222 return false;
2223 }
David Christie1f141c12014-05-14 15:11:15 -07002224 for (String name : packageNames) {
2225 if (packageName.equals(name)) {
2226 return true;
2227 }
2228 }
2229 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002230 }
2231
Nick Pellye0fd6932012-07-11 10:26:13 -07002232 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002233 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002234 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002235
Nick Pelly2eeeec22012-07-18 13:13:37 -07002236 if (!location.isComplete()) {
2237 Log.w(TAG, "Dropping incomplete location: " + location);
2238 return;
2239 }
2240
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002241 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2242 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002243 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002244 mLocationHandler.sendMessageAtFrontOfQueue(m);
2245 }
2246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002247
Laurent Tu75defb62012-11-01 16:21:52 -07002248 private static boolean shouldBroadcastSafe(
2249 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 // Always broadcast the first update
2251 if (lastLoc == null) {
2252 return true;
2253 }
2254
Nick Pellyf1be6862012-05-15 10:53:42 -07002255 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002256 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002257 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2258 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002259 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 return false;
2261 }
2262
2263 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002264 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 if (minDistance > 0.0) {
2266 if (loc.distanceTo(lastLoc) <= minDistance) {
2267 return false;
2268 }
2269 }
2270
Laurent Tu75defb62012-11-01 16:21:52 -07002271 // Check whether sufficient number of udpates is left
2272 if (record.mRequest.getNumUpdates() <= 0) {
2273 return false;
2274 }
2275
2276 // Check whether the expiry date has passed
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002277 return record.mRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002278 }
2279
Mike Lockwooda4903f22010-02-17 06:42:23 -05002280 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002281 if (D) Log.d(TAG, "incoming location: " + location);
2282
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002283 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002284 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002285
Laurent Tu60ec50a2012-10-04 17:00:10 -07002286 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002287 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002288 if (p == null) return;
2289
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002290 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002291 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002292 Location lastNoGPSLocation;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002293 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002294 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002295 lastLocation = new Location(provider);
2296 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002297 } else {
2298 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2299 if (noGPSLocation == null && lastNoGPSLocation != null) {
2300 // New location has no no-GPS location: adopt last no-GPS location. This is set
2301 // directly into location because we do not want to notify COARSE clients.
2302 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2303 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002304 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002305 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002306
David Christie1b9b7b12013-04-15 15:31:11 -07002307 // Update last known coarse interval location if enough time has passed.
2308 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2309 if (lastLocationCoarseInterval == null) {
2310 lastLocationCoarseInterval = new Location(location);
2311 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2312 }
2313 long timeDiffNanos = location.getElapsedRealtimeNanos()
2314 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2315 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2316 lastLocationCoarseInterval.set(location);
2317 }
2318 // Don't ever return a coarse location that is more recent than the allowed update
2319 // interval (i.e. don't allow an app to keep registering and unregistering for
2320 // location updates to overcome the minimum interval).
2321 noGPSLocation =
2322 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2323
Laurent Tu60ec50a2012-10-04 17:00:10 -07002324 // Skip if there are no UpdateRecords for this provider.
2325 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2326 if (records == null || records.size() == 0) return;
2327
Victoria Lease09016ab2012-09-16 12:33:15 -07002328 // Fetch coarse location
2329 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002330 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002331 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2332 }
2333
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 // Fetch latest status update time
2335 long newStatusUpdateTime = p.getStatusUpdateTime();
2336
David Christie2ff96af2014-01-30 16:09:37 -08002337 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 Bundle extras = new Bundle();
2339 int status = p.getStatus(extras);
2340
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002341 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002342 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002345 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002346 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002347 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002348
Victoria Lease269518e2012-10-29 08:25:39 -07002349 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002350 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002351 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002352 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002353 " (current user: " + mCurrentUserId + ", app: " +
2354 receiver.mPackageName + ")");
2355 }
2356 continue;
2357 }
2358
Nick Pelly4035f5a2012-08-17 14:43:49 -07002359 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2360 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2361 receiver.mPackageName);
2362 continue;
2363 }
2364
David Christieb870dbf2015-06-22 12:42:53 -07002365 if (!reportLocationAccessNoThrow(receiver.mPid, receiver.mUid, receiver.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002366 receiver.mAllowedResolutionLevel)) {
2367 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2368 receiver.mPackageName);
2369 continue;
2370 }
2371
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002372 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002373 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2374 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002375 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002376 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002377 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002378 if (notifyLocation != null) {
2379 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002380 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002381 if (lastLoc == null) {
2382 lastLoc = new Location(notifyLocation);
2383 r.mLastFixBroadcast = lastLoc;
2384 } else {
2385 lastLoc.set(notifyLocation);
2386 }
2387 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2388 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2389 receiverDead = true;
2390 }
Laurent Tu75defb62012-11-01 16:21:52 -07002391 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002392 }
2393 }
2394
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002395 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002396 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002397 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002398
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002399 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002400 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002401 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002402 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002403 }
2404 }
2405
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002406 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002407 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002408 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002409 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002410 }
2411 deadUpdateRecords.add(r);
2412 }
2413 // track dead receivers
2414 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002415 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002416 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07002417 }
2418 if (!deadReceivers.contains(receiver)) {
2419 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 }
2421 }
2422 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002423
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002424 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002426 for (Receiver receiver : deadReceivers) {
2427 removeUpdatesLocked(receiver);
2428 }
2429 }
2430 if (deadUpdateRecords != null) {
2431 for (UpdateRecord r : deadUpdateRecords) {
2432 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002433 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002434 applyRequirementsLocked(provider);
2435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 }
2437
2438 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002439 public LocationWorkerHandler(Looper looper) {
2440 super(looper, null, true);
2441 }
2442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002443 @Override
2444 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002445 switch (msg.what) {
2446 case MSG_LOCATION_CHANGED:
2447 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2448 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450 }
2451 }
2452
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002453 private boolean isMockProvider(String provider) {
2454 synchronized (mLock) {
2455 return mMockProviders.containsKey(provider);
2456 }
2457 }
2458
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002459 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002460 // create a working copy of the incoming Location so that the service can modify it without
2461 // disturbing the caller's copy
2462 Location myLocation = new Location(location);
2463 String provider = myLocation.getProvider();
2464
2465 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2466 // bit if location did not come from a mock provider because passive/fused providers can
2467 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2468 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2469 myLocation.setIsFromMockProvider(true);
2470 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002471
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002472 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002473 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2474 if (!passive) {
2475 // notify passive provider of the new location
2476 mPassiveProvider.updateLocation(myLocation);
2477 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002478 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002480 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482
Mike Lockwoode97ae402010-09-29 15:23:46 -04002483 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2484 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002485 public void onPackageDisappeared(String packageName, int reason) {
2486 // remove all receivers associated with this package name
2487 synchronized (mLock) {
2488 ArrayList<Receiver> deadReceivers = null;
2489
2490 for (Receiver receiver : mReceivers.values()) {
2491 if (receiver.mPackageName.equals(packageName)) {
2492 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002493 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002494 }
2495 deadReceivers.add(receiver);
2496 }
2497 }
2498
2499 // perform removal outside of mReceivers loop
2500 if (deadReceivers != null) {
2501 for (Receiver receiver : deadReceivers) {
2502 removeUpdatesLocked(receiver);
2503 }
2504 }
2505 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002506 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002507 };
2508
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 // Geocoder
2510
Nick Pellye0fd6932012-07-11 10:26:13 -07002511 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002512 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002513 return mGeocodeProvider != null;
2514 }
2515
Nick Pellye0fd6932012-07-11 10:26:13 -07002516 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002518 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002519 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002520 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2521 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002523 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525
Mike Lockwooda55c3212009-04-15 11:10:11 -04002526
Nick Pellye0fd6932012-07-11 10:26:13 -07002527 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002528 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002529 double lowerLeftLatitude, double lowerLeftLongitude,
2530 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002531 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002532
2533 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002534 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2535 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2536 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002538 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002539 }
2540
2541 // Mock Providers
2542
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002543 private boolean canCallerAccessMockLocation(String opPackageName) {
2544 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
2545 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002546 }
2547
Nick Pellye0fd6932012-07-11 10:26:13 -07002548 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002549 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
2550 if (!canCallerAccessMockLocation(opPackageName)) {
2551 return;
2552 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002553
Mike Lockwooda4903f22010-02-17 06:42:23 -05002554 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2555 throw new IllegalArgumentException("Cannot mock the passive location provider");
2556 }
2557
Mike Lockwood86328a92009-10-23 08:38:25 -04002558 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002559 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002560 // remove the real provider if we are replacing GPS or network provider
2561 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002562 || LocationManager.NETWORK_PROVIDER.equals(name)
2563 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002564 LocationProviderInterface p = mProvidersByName.get(name);
2565 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002566 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002567 }
2568 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002569 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002570 updateProvidersLocked();
2571 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002572 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002573 }
2574
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002575 private void addTestProviderLocked(String name, ProviderProperties properties) {
2576 if (mProvidersByName.get(name) != null) {
2577 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2578 }
2579 MockProvider provider = new MockProvider(name, this, properties);
2580 addProviderLocked(provider);
2581 mMockProviders.put(name, provider);
2582 mLastLocation.put(name, null);
2583 mLastLocationCoarseInterval.put(name, null);
2584 }
2585
Nick Pellye0fd6932012-07-11 10:26:13 -07002586 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002587 public void removeTestProvider(String provider, String opPackageName) {
2588 if (!canCallerAccessMockLocation(opPackageName)) {
2589 return;
2590 }
2591
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002592 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002593
2594 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002595 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002596 clearTestProviderEnabled(provider, opPackageName);
2597 clearTestProviderLocation(provider, opPackageName);
2598 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002599
You Kima6d0b6f2012-10-28 03:58:44 +09002600 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002601 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2603 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002604 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002605 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002606
2607 // reinstate real provider if available
2608 LocationProviderInterface realProvider = mRealProviders.get(provider);
2609 if (realProvider != null) {
2610 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002611 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002612 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002613 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002614 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002615 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002616 }
2617 }
2618
Nick Pellye0fd6932012-07-11 10:26:13 -07002619 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002620 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
2621 if (!canCallerAccessMockLocation(opPackageName)) {
2622 return;
2623 }
2624
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002625 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002626 MockProvider mockProvider = mMockProviders.get(provider);
2627 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002628 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2629 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002630
2631 // Ensure that the location is marked as being mock. There's some logic to do this in
2632 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
2633 Location mock = new Location(loc);
2634 mock.setIsFromMockProvider(true);
2635
2636 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
2637 // The location has an explicit provider that is different from the mock provider
2638 // name. The caller may be trying to fool us via bug 33091107.
2639 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
2640 provider + "!=" + loc.getProvider());
2641 }
2642
Mike Lockwood95427cd2009-05-07 13:27:54 -04002643 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2644 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002645 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002646 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002647 }
2648 }
2649
Nick Pellye0fd6932012-07-11 10:26:13 -07002650 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002651 public void clearTestProviderLocation(String provider, String opPackageName) {
2652 if (!canCallerAccessMockLocation(opPackageName)) {
2653 return;
2654 }
2655
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002656 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002657 MockProvider mockProvider = mMockProviders.get(provider);
2658 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002659 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2660 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002661 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002662 }
2663 }
2664
Nick Pellye0fd6932012-07-11 10:26:13 -07002665 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002666 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
2667 if (!canCallerAccessMockLocation(opPackageName)) {
2668 return;
2669 }
2670
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002671 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002672 MockProvider mockProvider = mMockProviders.get(provider);
2673 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002674 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2675 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002676 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002678 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 mEnabledProviders.add(provider);
2680 mDisabledProviders.remove(provider);
2681 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002682 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 mEnabledProviders.remove(provider);
2684 mDisabledProviders.add(provider);
2685 }
2686 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002687 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688 }
2689 }
2690
Nick Pellye0fd6932012-07-11 10:26:13 -07002691 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002692 public void clearTestProviderEnabled(String provider, String opPackageName) {
2693 if (!canCallerAccessMockLocation(opPackageName)) {
2694 return;
2695 }
2696
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002697 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002698 MockProvider mockProvider = mMockProviders.get(provider);
2699 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002700 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2701 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002702 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002703 mEnabledProviders.remove(provider);
2704 mDisabledProviders.remove(provider);
2705 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002706 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708 }
2709
Nick Pellye0fd6932012-07-11 10:26:13 -07002710 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002711 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
2712 String opPackageName) {
2713 if (!canCallerAccessMockLocation(opPackageName)) {
2714 return;
2715 }
2716
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002717 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002718 MockProvider mockProvider = mMockProviders.get(provider);
2719 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2721 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002722 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724 }
2725
Nick Pellye0fd6932012-07-11 10:26:13 -07002726 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002727 public void clearTestProviderStatus(String provider, String opPackageName) {
2728 if (!canCallerAccessMockLocation(opPackageName)) {
2729 return;
2730 }
2731
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002732 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002733 MockProvider mockProvider = mMockProviders.get(provider);
2734 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2736 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002737 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738 }
2739 }
2740
2741 private void log(String log) {
2742 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002743 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002744 }
2745 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002746
2747 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002748 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2749 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2750 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002751 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002752 + Binder.getCallingPid()
2753 + ", uid=" + Binder.getCallingUid());
2754 return;
2755 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002756
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002757 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002758 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002759 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002760 for (Receiver receiver : mReceivers.values()) {
2761 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002762 }
David Christie2ff96af2014-01-30 16:09:37 -08002763 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002764 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2765 pw.println(" " + entry.getKey() + ":");
2766 for (UpdateRecord record : entry.getValue()) {
2767 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002768 }
2769 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002770 pw.println(" Overlay Provider Packages:");
2771 for (LocationProviderInterface provider : mProviders) {
2772 if (provider instanceof LocationProviderProxy) {
2773 pw.println(" " + provider.getName() + ": "
2774 + ((LocationProviderProxy) provider).getConnectedPackageName());
2775 }
2776 }
David Christie2ff96af2014-01-30 16:09:37 -08002777 pw.println(" Historical Records by Provider:");
2778 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2779 : mRequestStatistics.statistics.entrySet()) {
2780 PackageProviderKey key = entry.getKey();
2781 PackageStatistics stats = entry.getValue();
2782 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002784 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002785 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2786 String provider = entry.getKey();
2787 Location location = entry.getValue();
2788 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002789 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002790
David Christie1b9b7b12013-04-15 15:31:11 -07002791 pw.println(" Last Known Locations Coarse Intervals:");
2792 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2793 String provider = entry.getKey();
2794 Location location = entry.getValue();
2795 pw.println(" " + provider + ": " + location);
2796 }
2797
Nick Pellye0fd6932012-07-11 10:26:13 -07002798 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002799
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002800 if (mEnabledProviders.size() > 0) {
2801 pw.println(" Enabled Providers:");
2802 for (String i : mEnabledProviders) {
2803 pw.println(" " + i);
2804 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002805
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002806 }
2807 if (mDisabledProviders.size() > 0) {
2808 pw.println(" Disabled Providers:");
2809 for (String i : mDisabledProviders) {
2810 pw.println(" " + i);
2811 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002813 pw.append(" ");
2814 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 if (mMockProviders.size() > 0) {
2816 pw.println(" Mock Providers:");
2817 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002818 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819 }
2820 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002821
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002822 pw.append(" fudger: ");
2823 mLocationFudger.dump(fd, pw, args);
2824
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002825 if (args.length > 0 && "short".equals(args[0])) {
2826 return;
2827 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002828 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002829 pw.print(provider.getName() + " Internal State");
2830 if (provider instanceof LocationProviderProxy) {
2831 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2832 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002833 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002834 pw.println(":");
2835 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002836 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002837 }
2838 }
2839}