blob: 0fd59eaa111f8e93e7445f270e885e5883fe52e8 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Soonil Nagarkar7decfb62017-01-18 12:18:49 -080019import android.app.ActivityManager;
Wyatt Rileycf879db2017-01-12 13:57:38 -080020import android.annotation.NonNull;
Soonil Nagarkar681d7112017-02-23 17:14:16 -080021import android.util.ArrayMap;
Soonil Nagarkar2b565df2017-02-14 13:33:23 -080022import android.util.ArraySet;
destradaaea8a8a62014-06-23 18:19:03 -070023import com.android.internal.content.PackageMonitor;
24import com.android.internal.location.ProviderProperties;
25import com.android.internal.location.ProviderRequest;
26import com.android.internal.os.BackgroundThread;
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -070027import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060028import com.android.internal.util.DumpUtils;
destradaaa4fa3b52014-07-09 10:46:39 -070029import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070030import com.android.server.location.FlpHardwareProvider;
31import com.android.server.location.FusedProxy;
32import com.android.server.location.GeocoderProxy;
33import com.android.server.location.GeofenceManager;
34import com.android.server.location.GeofenceProxy;
Lifu Tang818aa2c2016-02-01 01:52:00 -080035import com.android.server.location.GnssLocationProvider;
36import com.android.server.location.GnssMeasurementsProvider;
37import com.android.server.location.GnssNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070038import com.android.server.location.LocationBlacklist;
39import com.android.server.location.LocationFudger;
40import com.android.server.location.LocationProviderInterface;
41import com.android.server.location.LocationProviderProxy;
42import com.android.server.location.LocationRequestStatistics;
43import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
44import com.android.server.location.LocationRequestStatistics.PackageStatistics;
45import com.android.server.location.MockProvider;
46import com.android.server.location.PassiveProvider;
47
Dianne Hackborna06de0f2012-12-11 16:34:47 -080048import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070050import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.ContentResolver;
52import android.content.Context;
53import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070054import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070055import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050056import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.content.pm.PackageManager;
Todd Kennedy0eb97382017-10-03 16:57:22 -070058import android.content.pm.PackageManagerInternal;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070059import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050060import android.content.pm.ResolveInfo;
61import android.content.pm.Signature;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050062import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070063import android.database.ContentObserver;
destradaaa4fa3b52014-07-09 10:46:39 -070064import android.hardware.location.ActivityRecognitionHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070066import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050067import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070068import android.location.Geofence;
Wyatt Rileycf879db2017-01-12 13:57:38 -080069import android.location.IBatchedLocationCallback;
Lifu Tang818aa2c2016-02-01 01:52:00 -080070import android.location.IGnssMeasurementsListener;
Lifu Tang30f95a72016-01-07 23:20:38 -080071import android.location.IGnssStatusListener;
72import android.location.IGnssStatusProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -070073import android.location.IGpsGeofenceHardware;
Lifu Tang818aa2c2016-02-01 01:52:00 -080074import android.location.IGnssNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.location.ILocationListener;
76import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040077import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import android.location.Location;
79import android.location.LocationManager;
80import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070081import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
83import android.os.Bundle;
84import android.os.Handler;
85import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070086import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Message;
88import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070089import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070091import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070093import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070094import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.provider.Settings;
Tom O'Neilla206a0f2016-12-15 10:26:28 -080096import android.text.TextUtils;
97import android.util.EventLog;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080099import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700100
Mike Lockwood43e33f22010-03-26 10:41:48 -0400101import java.io.FileDescriptor;
102import java.io.PrintWriter;
103import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700104import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400105import java.util.HashMap;
106import java.util.HashSet;
107import java.util.List;
108import java.util.Map;
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800109import java.util.Map.Entry;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800110import java.util.NoSuchElementException;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400111import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
113/**
114 * The service class that manages LocationProviders and issues location
115 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800117public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800119 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700120
121 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122
Victoria Lease37425c32012-10-16 16:08:48 -0700123 // Location resolution level: no location data whatsoever
124 private static final int RESOLUTION_LEVEL_NONE = 0;
125 // Location resolution level: coarse location data only
126 private static final int RESOLUTION_LEVEL_COARSE = 1;
127 // Location resolution level: fine location data
128 private static final int RESOLUTION_LEVEL_FINE = 2;
129
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700131 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700133 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400134 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700135 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
136
137 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700138 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700139 private static final String FUSED_LOCATION_SERVICE_ACTION =
140 "com.android.location.service.FusedLocationProvider";
141
142 private static final int MSG_LOCATION_CHANGED = 1;
143
David Christie1b9b7b12013-04-15 15:31:11 -0700144 private static final long NANOS_PER_MILLI = 1000000L;
145
David Christie0b837452013-07-29 16:02:13 -0700146 // The maximum interval a location request can have and still be considered "high power".
147 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
148
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700149 private static final int FOREGROUND_IMPORTANCE_CUTOFF
150 = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE;
151
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800152 // default background throttling interval if not overriden in settings
Soonil Nagarkarde6780a2017-02-07 10:39:41 -0800153 private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800154
Nick Pellyf1be6862012-05-15 10:53:42 -0700155 // Location Providers may sometimes deliver location updates
156 // slightly faster that requested - provide grace period so
157 // we don't unnecessarily filter events that are otherwise on
158 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700159 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700160
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700161 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
162
163 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800164 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700165
166 // used internally for synchronization
167 private final Object mLock = new Object();
168
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700169 // --- fields below are final after systemRunning() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700170 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700171 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700172 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700173 private PowerManager mPowerManager;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800174 private ActivityManager mActivityManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700175 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700176 private GeocoderProxy mGeocodeProvider;
Lifu Tang30f95a72016-01-07 23:20:38 -0800177 private IGnssStatusProvider mGnssStatusProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700178 private INetInitiatedListener mNetInitiatedListener;
179 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700180 private PassiveProvider mPassiveProvider; // track passive provider for special cases
181 private LocationBlacklist mBlacklist;
Lifu Tang818aa2c2016-02-01 01:52:00 -0800182 private GnssMeasurementsProvider mGnssMeasurementsProvider;
183 private GnssNavigationMessageProvider mGnssNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700184 private IGpsGeofenceHardware mGpsGeofenceProxy;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700185
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187 // Set of providers that are explicitly enabled
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700188 // Only used by passive, fused & test. Network & GPS are controlled separately, and not listed.
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800189 private final Set<String> mEnabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
191 // Set of providers that are explicitly disabled
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800192 private final Set<String> mDisabledProviders = new HashSet<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700194 // Mock (test) providers
195 private final HashMap<String, MockProvider> mMockProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800196 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700198 // all receivers
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800199 private final HashMap<Object, Receiver> mReceivers = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700201 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500202 private final ArrayList<LocationProviderInterface> mProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800203 new ArrayList<>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400204
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700205 // real providers, saved here when mocked out
206 private final HashMap<String, LocationProviderInterface> mRealProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800207 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800208
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700209 // mapping from provider name to provider
210 private final HashMap<String, LocationProviderInterface> mProvidersByName =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800211 new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700213 // mapping from provider name to all its UpdateRecords
214 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800215 new HashMap<>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700216
David Christie2ff96af2014-01-30 16:09:37 -0800217 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
218
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700219 // mapping from provider name to last known location
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800220 private final HashMap<String, Location> mLastLocation = new HashMap<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
David Christie1b9b7b12013-04-15 15:31:11 -0700222 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
223 // locations stored here are not fudged for coarse permissions.
224 private final HashMap<String, Location> mLastLocationCoarseInterval =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800225 new HashMap<>();
David Christie1b9b7b12013-04-15 15:31:11 -0700226
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800227 // all providers that operate over proxy, for authorizing incoming location and whitelisting
228 // throttling
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700229 private final ArrayList<LocationProviderProxy> mProxyProviders =
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800230 new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800232 private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800233
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800234 private final ArrayMap<IGnssMeasurementsListener, Identity> mGnssMeasurementsListeners =
235 new ArrayMap<>();
236
237 private final ArrayMap<IGnssNavigationMessageListener, Identity>
238 mGnssNavigationMessageListeners = new ArrayMap<>();
239
Victoria Lease38389b62012-09-30 11:44:22 -0700240 // current active user on the device - other users are denied location data
Xiaohui Chena4490622015-09-22 15:29:31 -0700241 private int mCurrentUserId = UserHandle.USER_SYSTEM;
242 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_SYSTEM };
Victoria Lease38389b62012-09-30 11:44:22 -0700243
Lifu Tang9363b942016-02-16 18:07:00 -0800244 private GnssLocationProvider.GnssSystemInfoProvider mGnssSystemInfoProvider;
Lifu Tang82f893d2016-01-21 18:15:33 -0800245
Siddharth Raybb608c82017-03-16 11:33:34 -0700246 private GnssLocationProvider.GnssMetricsProvider mGnssMetricsProvider;
Wyatt Rileyaa420d52017-07-03 15:14:42 -0700247
248 private GnssLocationProvider.GnssBatchingProvider mGnssBatchingProvider;
Wyatt Rileycf879db2017-01-12 13:57:38 -0800249 private IBatchedLocationCallback mGnssBatchingCallback;
250 private LinkedCallback mGnssBatchingDeathCallback;
251 private boolean mGnssBatchingInProgress = false;
252
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700253 public LocationManagerService(Context context) {
254 super();
255 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800256 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800257
Svet Ganovadc1cf42015-06-15 16:36:24 -0700258 // Let the package manager query which are the default location
259 // providers as they get certain permissions granted by default.
260 PackageManagerInternal packageManagerInternal = LocalServices.getService(
261 PackageManagerInternal.class);
262 packageManagerInternal.setLocationPackagesProvider(
263 new PackageManagerInternal.PackagesProvider() {
264 @Override
265 public String[] getPackages(int userId) {
266 return mContext.getResources().getStringArray(
267 com.android.internal.R.array.config_locationProviderPackageNames);
268 }
269 });
270
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700271 if (D) Log.d(TAG, "Constructed");
272
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700273 // most startup is deferred until systemRunning()
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700274 }
275
Svetoslav Ganova0027152013-06-25 14:59:53 -0700276 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700277 synchronized (mLock) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700278 if (D) Log.d(TAG, "systemRunning()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700279
Victoria Lease5cd731a2012-12-19 15:04:21 -0800280 // fetch package manager
281 mPackageManager = mContext.getPackageManager();
282
Victoria Lease0aa28602013-05-29 15:28:26 -0700283 // fetch power manager
284 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800285
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800286 // fetch activity manager
287 mActivityManager
288 = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
289
Victoria Lease5cd731a2012-12-19 15:04:21 -0800290 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700291 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800292
293 // prepare mLocationHandler's dependents
294 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
295 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
296 mBlacklist.init();
297 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
298
Dianne Hackbornc2293022013-02-06 23:14:49 -0800299 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700300 AppOpsManager.OnOpChangedListener callback
301 = new AppOpsManager.OnOpChangedInternalListener() {
302 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800303 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700304 for (Receiver receiver : mReceivers.values()) {
305 receiver.updateMonitoring(true);
306 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800307 applyAllProviderRequirementsLocked();
308 }
309 }
310 };
311 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
312
David Christieb870dbf2015-06-22 12:42:53 -0700313 PackageManager.OnPermissionsChangedListener permissionListener
314 = new PackageManager.OnPermissionsChangedListener() {
315 @Override
316 public void onPermissionsChanged(final int uid) {
317 synchronized (mLock) {
318 applyAllProviderRequirementsLocked();
319 }
320 }
321 };
322 mPackageManager.addOnPermissionsChangeListener(permissionListener);
323
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800324 // listen for background/foreground changes
325 ActivityManager.OnUidImportanceListener uidImportanceListener
326 = new ActivityManager.OnUidImportanceListener() {
327 @Override
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700328 public void onUidImportance(final int uid, final int importance) {
329 mLocationHandler.post(new Runnable() {
330 @Override
331 public void run() {
332 onUidImportanceChanged(uid, importance);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800333 }
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700334 });
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800335 }
336 };
337 mActivityManager.addOnUidImportanceListener(uidImportanceListener,
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700338 FOREGROUND_IMPORTANCE_CUTOFF);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800339
Amith Yamasanib27528d2014-06-05 15:02:10 -0700340 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
341 updateUserProfiles(mCurrentUserId);
342
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800343 updateBackgroundThrottlingWhitelistLocked();
Soonil Nagarkar2b565df2017-02-14 13:33:23 -0800344
Victoria Lease5cd731a2012-12-19 15:04:21 -0800345 // prepare providers
346 loadProvidersLocked();
347 updateProvidersLocked();
348 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700349
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700350 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700351 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700352 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700353 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800354 @Override
355 public void onChange(boolean selfChange) {
356 synchronized (mLock) {
357 updateProvidersLocked();
358 }
359 }
360 }, UserHandle.USER_ALL);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800361 mContext.getContentResolver().registerContentObserver(
362 Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS),
363 true,
364 new ContentObserver(mLocationHandler) {
365 @Override
366 public void onChange(boolean selfChange) {
367 synchronized (mLock) {
368 updateProvidersLocked();
369 }
370 }
371 }, UserHandle.USER_ALL);
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800372 mContext.getContentResolver().registerContentObserver(
373 Settings.Global.getUriFor(
374 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST),
375 true,
376 new ContentObserver(mLocationHandler) {
377 @Override
378 public void onChange(boolean selfChange) {
379 synchronized (mLock) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800380 updateBackgroundThrottlingWhitelistLocked();
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -0800381 updateProvidersLocked();
382 }
383 }
384 }, UserHandle.USER_ALL);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800385 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700386
Victoria Lease38389b62012-09-30 11:44:22 -0700387 // listen for user change
388 IntentFilter intentFilter = new IntentFilter();
389 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700390 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
391 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
destradaab9026982015-08-27 17:34:54 -0700392 intentFilter.addAction(Intent.ACTION_SHUTDOWN);
Victoria Lease38389b62012-09-30 11:44:22 -0700393
394 mContext.registerReceiverAsUser(new BroadcastReceiver() {
395 @Override
396 public void onReceive(Context context, Intent intent) {
397 String action = intent.getAction();
398 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
399 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700400 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
401 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
402 updateUserProfiles(mCurrentUserId);
destradaab9026982015-08-27 17:34:54 -0700403 } else if (Intent.ACTION_SHUTDOWN.equals(action)) {
Wyatt Rileya8037ff2016-08-04 16:10:06 -0700404 // shutdown only if UserId indicates whole system, not just one user
405 if(D) Log.d(TAG, "Shutdown received with UserId: " + getSendingUserId());
406 if (getSendingUserId() == UserHandle.USER_ALL) {
407 shutdownComponents();
408 }
Victoria Lease38389b62012-09-30 11:44:22 -0700409 }
410 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800411 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700412 }
413
Soonil Nagarkare056b0d2017-06-21 13:08:16 -0700414 private void onUidImportanceChanged(int uid, int importance) {
415 boolean foreground = isImportanceForeground(importance);
416 HashSet<String> affectedProviders = new HashSet<>(mRecordsByProvider.size());
417 synchronized (mLock) {
418 for (Entry<String, ArrayList<UpdateRecord>> entry
419 : mRecordsByProvider.entrySet()) {
420 String provider = entry.getKey();
421 for (UpdateRecord record : entry.getValue()) {
422 if (record.mReceiver.mIdentity.mUid == uid
423 && record.mIsForegroundUid != foreground) {
424 if (D) Log.d(TAG, "request from uid " + uid + " is now "
425 + (foreground ? "foreground" : "background)"));
426 record.mIsForegroundUid = foreground;
427
428 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
429 affectedProviders.add(provider);
430 }
431 }
432 }
433 }
434 for (String provider : affectedProviders) {
435 applyRequirementsLocked(provider);
436 }
437
438 for (Entry<IGnssMeasurementsListener, Identity> entry
439 : mGnssMeasurementsListeners.entrySet()) {
440 if (entry.getValue().mUid == uid) {
441 if (D) Log.d(TAG, "gnss measurements listener from uid " + uid
442 + " is now " + (foreground ? "foreground" : "background)"));
443 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
444 mGnssMeasurementsProvider.addListener(entry.getKey());
445 } else {
446 mGnssMeasurementsProvider.removeListener(entry.getKey());
447 }
448 }
449 }
450
451 for (Entry<IGnssNavigationMessageListener, Identity> entry
452 : mGnssNavigationMessageListeners.entrySet()) {
453 if (entry.getValue().mUid == uid) {
454 if (D) Log.d(TAG, "gnss navigation message listener from uid "
455 + uid + " is now "
456 + (foreground ? "foreground" : "background)"));
457 if (foreground || isThrottlingExemptLocked(entry.getValue())) {
458 mGnssNavigationMessageProvider.addListener(entry.getKey());
459 } else {
460 mGnssNavigationMessageProvider.removeListener(entry.getKey());
461 }
462 }
463 }
464 }
465 }
466
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800467 private static boolean isImportanceForeground(int importance) {
Soonil Nagarkarebda0282017-04-10 14:55:37 -0700468 return importance <= FOREGROUND_IMPORTANCE_CUTOFF;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800469 }
470
Amith Yamasanib27528d2014-06-05 15:02:10 -0700471 /**
destradaab9026982015-08-27 17:34:54 -0700472 * Provides a way for components held by the {@link LocationManagerService} to clean-up
473 * gracefully on system's shutdown.
474 *
475 * NOTES:
476 * 1) Only provides a chance to clean-up on an opt-in basis. This guarantees back-compat
477 * support for components that do not wish to handle such event.
478 */
479 private void shutdownComponents() {
480 if(D) Log.d(TAG, "Shutting down components...");
481
482 LocationProviderInterface gpsProvider = mProvidersByName.get(LocationManager.GPS_PROVIDER);
483 if (gpsProvider != null && gpsProvider.isEnabled()) {
484 gpsProvider.disable();
485 }
486
destradaa2e385072015-10-14 16:45:58 -0700487 // it is needed to check if FLP HW provider is supported before accessing the instance, this
488 // avoids an exception to be thrown by the singleton factory method
489 if (FlpHardwareProvider.isSupported()) {
490 FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaab9026982015-08-27 17:34:54 -0700491 flpHardwareProvider.cleanup();
492 }
493 }
494
495 /**
Amith Yamasanib27528d2014-06-05 15:02:10 -0700496 * Makes a list of userids that are related to the current user. This is
497 * relevant when using managed profiles. Otherwise the list only contains
498 * the current user.
499 *
500 * @param currentUserId the current user, who might have an alter-ego.
501 */
502 void updateUserProfiles(int currentUserId) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700503 int[] profileIds = mUserManager.getProfileIdsWithDisabled(currentUserId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700504 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700505 mCurrentUserProfiles = profileIds;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700506 }
507 }
508
509 /**
510 * Checks if the specified userId matches any of the current foreground
511 * users stored in mCurrentUserProfiles.
512 */
513 private boolean isCurrentProfile(int userId) {
514 synchronized (mLock) {
Fyodor Kupolov7f98aa42016-04-07 14:56:25 -0700515 return ArrayUtils.contains(mCurrentUserProfiles, userId);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700516 }
517 }
518
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500519 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
520 PackageManager pm = mContext.getPackageManager();
521 String systemPackageName = mContext.getPackageName();
522 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
523
524 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
525 new Intent(FUSED_LOCATION_SERVICE_ACTION),
526 PackageManager.GET_META_DATA, mCurrentUserId);
527 for (ResolveInfo rInfo : rInfos) {
528 String packageName = rInfo.serviceInfo.packageName;
529
530 // Check that the signature is in the list of supported sigs. If it's not in
531 // this list the standard provider binding logic won't bind to it.
532 try {
533 PackageInfo pInfo;
534 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
535 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
536 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
537 ", but has wrong signature, ignoring");
538 continue;
539 }
540 } catch (NameNotFoundException e) {
541 Log.e(TAG, "missing package: " + packageName);
542 continue;
543 }
544
545 // Get the version info
546 if (rInfo.serviceInfo.metaData == null) {
547 Log.w(TAG, "Found fused provider without metadata: " + packageName);
548 continue;
549 }
550
551 int version = rInfo.serviceInfo.metaData.getInt(
552 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
553 if (version == 0) {
554 // This should be the fallback fused location provider.
555
556 // Make sure it's in the system partition.
557 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
558 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
559 continue;
560 }
561
562 // Check that the fallback is signed the same as the OS
563 // as a proxy for coreApp="true"
564 if (pm.checkSignatures(systemPackageName, packageName)
565 != PackageManager.SIGNATURE_MATCH) {
566 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
567 + packageName);
568 continue;
569 }
570
571 // Found a valid fallback.
572 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
573 return;
574 } else {
575 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
576 }
577 }
578
579 throw new IllegalStateException("Unable to find a fused location provider that is in the "
580 + "system partition with version 0 and signed with the platform certificate. "
581 + "Such a package is needed to provide a default fused location provider in the "
582 + "event that no other fused location provider has been installed or is currently "
583 + "available. For example, coreOnly boot mode when decrypting the data "
584 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
585 }
586
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700587 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700588 // create a passive location provider, which is always enabled
589 PassiveProvider passiveProvider = new PassiveProvider(this);
590 addProviderLocked(passiveProvider);
591 mEnabledProviders.add(passiveProvider.getName());
592 mPassiveProvider = passiveProvider;
593
Lifu Tang30f95a72016-01-07 23:20:38 -0800594 if (GnssLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700595 // Create a gps location provider
Lifu Tang30f95a72016-01-07 23:20:38 -0800596 GnssLocationProvider gnssProvider = new GnssLocationProvider(mContext, this,
Wei Liu5241a4c2015-05-11 14:00:36 -0700597 mLocationHandler.getLooper());
Lifu Tang9363b942016-02-16 18:07:00 -0800598 mGnssSystemInfoProvider = gnssProvider.getGnssSystemInfoProvider();
Wyatt Rileycf879db2017-01-12 13:57:38 -0800599 mGnssBatchingProvider = gnssProvider.getGnssBatchingProvider();
Siddharth Raybb608c82017-03-16 11:33:34 -0700600 mGnssMetricsProvider = gnssProvider.getGnssMetricsProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800601 mGnssStatusProvider = gnssProvider.getGnssStatusProvider();
602 mNetInitiatedListener = gnssProvider.getNetInitiatedListener();
603 addProviderLocked(gnssProvider);
604 mRealProviders.put(LocationManager.GPS_PROVIDER, gnssProvider);
Lifu Tang818aa2c2016-02-01 01:52:00 -0800605 mGnssMeasurementsProvider = gnssProvider.getGnssMeasurementsProvider();
606 mGnssNavigationMessageProvider = gnssProvider.getGnssNavigationMessageProvider();
Lifu Tang30f95a72016-01-07 23:20:38 -0800607 mGpsGeofenceProxy = gnssProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700608 }
609
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700610 /*
611 Load package name(s) containing location provider support.
612 These packages can contain services implementing location providers:
613 Geocoder Provider, Network Location Provider, and
614 Fused Location Provider. They will each be searched for
615 service components implementing these providers.
616 The location framework also has support for installation
617 of new location providers at run-time. The new package does not
618 have to be explicitly listed here, however it must have a signature
619 that matches the signature of at least one package on this list.
620 */
621 Resources resources = mContext.getResources();
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800622 ArrayList<String> providerPackageNames = new ArrayList<>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500623 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700624 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500625 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
626 Arrays.toString(pkgs));
627 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
628
629 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700630
631 // bind to network provider
632 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
633 mContext,
634 LocationManager.NETWORK_PROVIDER,
635 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700636 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
637 com.android.internal.R.string.config_networkLocationProviderPackageName,
638 com.android.internal.R.array.config_locationProviderPackageNames,
639 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700640 if (networkProvider != null) {
641 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
642 mProxyProviders.add(networkProvider);
643 addProviderLocked(networkProvider);
644 } else {
645 Slog.w(TAG, "no network location provider found");
646 }
647
648 // bind to fused provider
649 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
650 mContext,
651 LocationManager.FUSED_PROVIDER,
652 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700653 com.android.internal.R.bool.config_enableFusedLocationOverlay,
654 com.android.internal.R.string.config_fusedLocationProviderPackageName,
655 com.android.internal.R.array.config_locationProviderPackageNames,
656 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700657 if (fusedLocationProvider != null) {
658 addProviderLocked(fusedLocationProvider);
659 mProxyProviders.add(fusedLocationProvider);
660 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700661 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700662 } else {
663 Slog.e(TAG, "no fused location provider found",
664 new IllegalStateException("Location service needs a fused location provider"));
665 }
666
667 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700668 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
669 com.android.internal.R.bool.config_enableGeocoderOverlay,
670 com.android.internal.R.string.config_geocoderProviderPackageName,
671 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800672 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700673 if (mGeocodeProvider == null) {
674 Slog.e(TAG, "no geocoder provider found");
675 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700676
destradaaa4fa3b52014-07-09 10:46:39 -0700677 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700678 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
679 // exception, so make sure we only do that when supported
680 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700681 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700682 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700683 FusedProxy fusedProxy = FusedProxy.createAndBind(
684 mContext,
685 mLocationHandler,
686 flpHardwareProvider.getLocationHardware(),
687 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
688 com.android.internal.R.string.config_hardwareFlpPackageName,
689 com.android.internal.R.array.config_locationProviderPackageNames);
690 if (fusedProxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700691 Slog.d(TAG, "Unable to bind FusedProxy.");
destradaaf9a274c2014-07-25 15:11:56 -0700692 }
destradaacfbdcd22014-04-30 11:29:11 -0700693 } else {
destradaabeea4422014-07-30 18:17:21 -0700694 flpHardwareProvider = null;
destradaa6b4893a2016-05-03 15:33:43 -0700695 Slog.d(TAG, "FLP HAL not supported");
destradaaf9a274c2014-07-25 15:11:56 -0700696 }
697
698 // bind to geofence provider
699 GeofenceProxy provider = GeofenceProxy.createAndBind(
700 mContext,com.android.internal.R.bool.config_enableGeofenceOverlay,
701 com.android.internal.R.string.config_geofenceProviderPackageName,
702 com.android.internal.R.array.config_locationProviderPackageNames,
703 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700704 mGpsGeofenceProxy,
destradaabeea4422014-07-30 18:17:21 -0700705 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700706 if (provider == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700707 Slog.d(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700708 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900709
destradaa6e2fe752015-06-23 17:25:53 -0700710 // bind to hardware activity recognition
711 boolean activityRecognitionHardwareIsSupported = ActivityRecognitionHardware.isSupported();
712 ActivityRecognitionHardware activityRecognitionHardware = null;
713 if (activityRecognitionHardwareIsSupported) {
714 activityRecognitionHardware = ActivityRecognitionHardware.getInstance(mContext);
destradaaa4fa3b52014-07-09 10:46:39 -0700715 } else {
destradaa6b4893a2016-05-03 15:33:43 -0700716 Slog.d(TAG, "Hardware Activity-Recognition not supported.");
destradaaa4fa3b52014-07-09 10:46:39 -0700717 }
destradaa6e2fe752015-06-23 17:25:53 -0700718 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
719 mContext,
720 mLocationHandler,
721 activityRecognitionHardwareIsSupported,
722 activityRecognitionHardware,
723 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
724 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
725 com.android.internal.R.array.config_locationProviderPackageNames);
726 if (proxy == null) {
destradaa6b4893a2016-05-03 15:33:43 -0700727 Slog.d(TAG, "Unable to bind ActivityRecognitionProxy.");
destradaa6e2fe752015-06-23 17:25:53 -0700728 }
destradaaa4fa3b52014-07-09 10:46:39 -0700729
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900730 String[] testProviderStrings = resources.getStringArray(
731 com.android.internal.R.array.config_testLocationProviders);
732 for (String testProviderString : testProviderStrings) {
733 String fragments[] = testProviderString.split(",");
734 String name = fragments[0].trim();
735 if (mProvidersByName.get(name) != null) {
736 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
737 }
738 ProviderProperties properties = new ProviderProperties(
739 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
740 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
741 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
742 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
743 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
744 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
745 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
746 Integer.parseInt(fragments[8]) /* powerRequirement */,
747 Integer.parseInt(fragments[9]) /* accuracy */);
748 addTestProviderLocked(name, properties);
749 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700750 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700751
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700753 * Called when the device's active user changes.
754 * @param userId the new active user's UserId
755 */
756 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800757 if (mCurrentUserId == userId) {
758 return;
759 }
Victoria Lease83762d22012-10-03 13:51:17 -0700760 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800761 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700762 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700763 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700764 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700765 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700766 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700767 }
Victoria Lease38389b62012-09-30 11:44:22 -0700768 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700769 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700770 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700771 }
772 }
773
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800774 private static final class Identity {
775 final int mUid;
776 final int mPid;
777 final String mPackageName;
778
779 Identity(int uid, int pid, String packageName) {
780 mUid = uid;
781 mPid = pid;
782 mPackageName = packageName;
783 }
784 }
785
Victoria Lease38389b62012-09-30 11:44:22 -0700786 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800787 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
788 * location updates.
789 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700790 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800791 final Identity mIdentity;
Victoria Lease37425c32012-10-16 16:08:48 -0700792 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700793
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800794 final ILocationListener mListener;
795 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700796 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700797 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800798 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700799
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800800 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700801
David Christie0b837452013-07-29 16:02:13 -0700802 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700803 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700804 // True if app ops has started monitoring this receiver for high power (gps) locations.
805 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700806 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700807 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700809 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700810 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800811 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800812 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700813 if (listener != null) {
814 mKey = listener.asBinder();
815 } else {
816 mKey = intent;
817 }
Victoria Lease37425c32012-10-16 16:08:48 -0700818 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800819 mIdentity = new Identity(uid, pid, packageName);
David Christie82edc9b2013-07-19 11:31:42 -0700820 if (workSource != null && workSource.size() <= 0) {
821 workSource = null;
822 }
823 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700824 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700825
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700826 updateMonitoring(true);
827
Victoria Lease0aa28602013-05-29 15:28:26 -0700828 // construct/configure wakelock
829 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700830 if (workSource == null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800831 workSource = new WorkSource(mIdentity.mUid, mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -0700832 }
833 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
835
836 @Override
837 public boolean equals(Object otherObj) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -0800838 return (otherObj instanceof Receiver) && mKey.equals(((Receiver) otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800839 }
840
841 @Override
842 public int hashCode() {
843 return mKey.hashCode();
844 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800846 @Override
847 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700848 StringBuilder s = new StringBuilder();
849 s.append("Reciever[");
850 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700852 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800853 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700854 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800855 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700856 for (String p : mUpdateRecords.keySet()) {
857 s.append(" ").append(mUpdateRecords.get(p).toString());
858 }
859 s.append("]");
860 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
862
David Christie15b31912013-08-13 15:54:32 -0700863 /**
864 * Update AppOp monitoring for this receiver.
865 *
866 * @param allow If true receiver is currently active, if false it's been removed.
867 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700868 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700869 if (mHideFromAppOps) {
870 return;
871 }
872
David Christie15b31912013-08-13 15:54:32 -0700873 boolean requestingLocation = false;
874 boolean requestingHighPowerLocation = false;
875 if (allow) {
876 // See if receiver has any enabled update records. Also note if any update records
877 // are high power (has a high power provider with an interval under a threshold).
878 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
879 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
880 requestingLocation = true;
881 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800882 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700883 ProviderProperties properties = locationProvider != null
884 ? locationProvider.getProperties() : null;
885 if (properties != null
886 && properties.mPowerRequirement == Criteria.POWER_HIGH
887 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
888 requestingHighPowerLocation = true;
889 break;
890 }
891 }
892 }
893 }
894
David Christie0b837452013-07-29 16:02:13 -0700895 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700896 mOpMonitoring = updateMonitoring(
897 requestingLocation,
898 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700899 AppOpsManager.OP_MONITOR_LOCATION);
900
901 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700902 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700903 mOpHighPowerMonitoring = updateMonitoring(
904 requestingHighPowerLocation,
905 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700906 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700907 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700908 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700909 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
910 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
911 }
David Christie0b837452013-07-29 16:02:13 -0700912 }
913
914 /**
915 * Update AppOps monitoring for a single location request and op type.
916 *
917 * @param allowMonitoring True if monitoring is allowed for this request/op.
918 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
919 * @param op AppOps code for the op to update.
920 * @return True if monitoring is on for this request/op after updating.
921 */
922 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
923 int op) {
924 if (!currentlyMonitoring) {
925 if (allowMonitoring) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800926 return mAppOps.startOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700927 == AppOpsManager.MODE_ALLOWED;
928 }
929 } else {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800930 if (!allowMonitoring
931 || mAppOps.checkOpNoThrow(op, mIdentity.mUid, mIdentity.mPackageName)
David Christie0b837452013-07-29 16:02:13 -0700932 != AppOpsManager.MODE_ALLOWED) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -0800933 mAppOps.finishOp(op, mIdentity.mUid, mIdentity.mPackageName);
David Christie0b837452013-07-29 16:02:13 -0700934 return false;
935 }
936 }
937
938 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700939 }
940
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 public boolean isListener() {
942 return mListener != null;
943 }
944
945 public boolean isPendingIntent() {
946 return mPendingIntent != null;
947 }
948
949 public ILocationListener getListener() {
950 if (mListener != null) {
951 return mListener;
952 }
953 throw new IllegalStateException("Request for non-existent listener");
954 }
955
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
957 if (mListener != null) {
958 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700959 synchronized (this) {
960 // synchronize to ensure incrementPendingBroadcastsLocked()
961 // is called before decrementPendingBroadcasts()
962 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700963 // call this after broadcasting so we do not increment
964 // if we throw an exeption.
965 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700966 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800967 } catch (RemoteException e) {
968 return false;
969 }
970 } else {
971 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800972 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800973 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
974 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700975 synchronized (this) {
976 // synchronize to ensure incrementPendingBroadcastsLocked()
977 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700978 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700979 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700980 // call this after broadcasting so we do not increment
981 // if we throw an exeption.
982 incrementPendingBroadcastsLocked();
983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 } catch (PendingIntent.CanceledException e) {
985 return false;
986 }
987 }
988 return true;
989 }
990
991 public boolean callLocationChangedLocked(Location location) {
992 if (mListener != null) {
993 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700994 synchronized (this) {
995 // synchronize to ensure incrementPendingBroadcastsLocked()
996 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800997 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700998 // call this after broadcasting so we do not increment
999 // if we throw an exeption.
1000 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001001 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 } catch (RemoteException e) {
1003 return false;
1004 }
1005 } else {
1006 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -08001007 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 try {
Mike Lockwood48f17512009-04-23 09:12:08 -07001009 synchronized (this) {
1010 // synchronize to ensure incrementPendingBroadcastsLocked()
1011 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001012 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001013 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001014 // call this after broadcasting so we do not increment
1015 // if we throw an exeption.
1016 incrementPendingBroadcastsLocked();
1017 }
1018 } catch (PendingIntent.CanceledException e) {
1019 return false;
1020 }
1021 }
1022 return true;
1023 }
1024
1025 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -07001026 // First update AppOp monitoring.
1027 // An app may get/lose location access as providers are enabled/disabled.
1028 updateMonitoring(true);
1029
Mike Lockwood48f17512009-04-23 09:12:08 -07001030 if (mListener != null) {
1031 try {
1032 synchronized (this) {
1033 // synchronize to ensure incrementPendingBroadcastsLocked()
1034 // is called before decrementPendingBroadcasts()
1035 if (enabled) {
1036 mListener.onProviderEnabled(provider);
1037 } else {
1038 mListener.onProviderDisabled(provider);
1039 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001040 // call this after broadcasting so we do not increment
1041 // if we throw an exeption.
1042 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001043 }
1044 } catch (RemoteException e) {
1045 return false;
1046 }
1047 } else {
1048 Intent providerIntent = new Intent();
1049 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
1050 try {
1051 synchronized (this) {
1052 // synchronize to ensure incrementPendingBroadcastsLocked()
1053 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001054 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -07001055 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -07001056 // call this after broadcasting so we do not increment
1057 // if we throw an exeption.
1058 incrementPendingBroadcastsLocked();
1059 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 } catch (PendingIntent.CanceledException e) {
1061 return false;
1062 }
1063 }
1064 return true;
1065 }
1066
Nick Pellyf1be6862012-05-15 10:53:42 -07001067 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001069 if (D) Log.d(TAG, "Location listener died");
1070
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001071 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 removeUpdatesLocked(this);
1073 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001074 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001075 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001076 }
1077 }
1078
Nick Pellye0fd6932012-07-11 10:26:13 -07001079 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001080 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
1081 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001082 synchronized (this) {
1083 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -07001084 }
1085 }
1086
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001087 // this must be called while synchronized by caller in a synchronized block
1088 // containing the sending of the broadcaset
1089 private void incrementPendingBroadcastsLocked() {
1090 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001091 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -04001092 }
1093 }
1094
1095 private void decrementPendingBroadcastsLocked() {
1096 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001097 if (mWakeLock.isHeld()) {
1098 mWakeLock.release();
1099 }
1100 }
1101 }
1102
1103 public void clearPendingBroadcastsLocked() {
1104 if (mPendingBroadcasts > 0) {
1105 mPendingBroadcasts = 0;
1106 if (mWakeLock.isHeld()) {
1107 mWakeLock.release();
1108 }
Mike Lockwood48f17512009-04-23 09:12:08 -07001109 }
1110 }
1111 }
1112
Nick Pellye0fd6932012-07-11 10:26:13 -07001113 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -07001114 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001115 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -04001116 //the receiver list if it is not found. If it is not found then the
1117 //LocationListener was removed when it had a pending broadcast and should
1118 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001119 synchronized (mLock) {
1120 IBinder binder = listener.asBinder();
1121 Receiver receiver = mReceivers.get(binder);
1122 if (receiver != null) {
1123 synchronized (receiver) {
1124 // so wakelock calls will succeed
1125 long identity = Binder.clearCallingIdentity();
1126 receiver.decrementPendingBroadcastsLocked();
1127 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -08001128 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
1131 }
1132
Lifu Tang82f893d2016-01-21 18:15:33 -08001133 /**
Lifu Tang9363b942016-02-16 18:07:00 -08001134 * Returns the system information of the GNSS hardware.
Lifu Tang82f893d2016-01-21 18:15:33 -08001135 */
1136 @Override
Lifu Tang9363b942016-02-16 18:07:00 -08001137 public int getGnssYearOfHardware() {
Wyatt Rileycf879db2017-01-12 13:57:38 -08001138 if (mGnssSystemInfoProvider != null) {
Lifu Tang9363b942016-02-16 18:07:00 -08001139 return mGnssSystemInfoProvider.getGnssYearOfHardware();
Lifu Tang82f893d2016-01-21 18:15:33 -08001140 } else {
1141 return 0;
1142 }
1143 }
1144
Wyatt Rileycf879db2017-01-12 13:57:38 -08001145 /**
1146 * Runs some checks for GNSS (FINE) level permissions, used by several methods which directly
1147 * (try to) access GNSS information at this layer.
1148 */
1149 private boolean hasGnssPermissions(String packageName) {
1150 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1151 checkResolutionLevelIsSufficientForProviderUse(
1152 allowedResolutionLevel,
1153 LocationManager.GPS_PROVIDER);
1154
1155 int pid = Binder.getCallingPid();
1156 int uid = Binder.getCallingUid();
1157 long identity = Binder.clearCallingIdentity();
1158 boolean hasLocationAccess;
1159 try {
1160 hasLocationAccess = checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
1161 } finally {
1162 Binder.restoreCallingIdentity(identity);
1163 }
1164
1165 return hasLocationAccess;
1166 }
1167
1168 /**
1169 * Returns the GNSS batching size, if available.
1170 */
1171 @Override
1172 public int getGnssBatchSize(String packageName) {
1173 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1174 "Location Hardware permission not granted to access hardware batching");
1175
1176 if (hasGnssPermissions(packageName) && mGnssBatchingProvider != null) {
1177 return mGnssBatchingProvider.getSize();
1178 } else {
1179 return 0;
1180 }
1181 }
1182
1183 /**
1184 * Adds a callback for GNSS Batching events, if permissions allow, which are transported
1185 * to potentially multiple listeners by the BatchedLocationCallbackTransport above this.
1186 */
1187 @Override
1188 public boolean addGnssBatchingCallback(IBatchedLocationCallback callback, String packageName) {
1189 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1190 "Location Hardware permission not granted to access hardware batching");
1191
1192 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1193 return false;
1194 }
1195
1196 mGnssBatchingCallback = callback;
1197 mGnssBatchingDeathCallback = new LinkedCallback(callback);
1198 try {
1199 callback.asBinder().linkToDeath(mGnssBatchingDeathCallback, 0 /* flags */);
1200 } catch (RemoteException e) {
1201 // if the remote process registering the listener is already dead, just swallow the
1202 // exception and return
1203 Log.e(TAG, "Remote listener already died.", e);
1204 return false;
1205 }
1206
1207 return true;
1208 }
1209
1210 private class LinkedCallback implements IBinder.DeathRecipient {
1211 private final IBatchedLocationCallback mCallback;
1212
1213 public LinkedCallback(@NonNull IBatchedLocationCallback callback) {
1214 mCallback = callback;
1215 }
1216
1217 @NonNull
1218 public IBatchedLocationCallback getUnderlyingListener() {
1219 return mCallback;
1220 }
1221
1222 @Override
1223 public void binderDied() {
1224 Log.d(TAG, "Remote Batching Callback died: " + mCallback);
1225 stopGnssBatch();
1226 removeGnssBatchingCallback();
1227 }
1228 }
1229
1230 /**
1231 * Removes callback for GNSS batching
1232 */
1233 @Override
1234 public void removeGnssBatchingCallback() {
1235 try {
1236 mGnssBatchingCallback.asBinder().unlinkToDeath(mGnssBatchingDeathCallback,
1237 0 /* flags */);
1238 } catch (NoSuchElementException e) {
1239 // if the death callback isn't connected (it should be...), log error, swallow the
1240 // exception and return
1241 Log.e(TAG, "Couldn't unlink death callback.", e);
1242 }
1243 mGnssBatchingCallback = null;
1244 mGnssBatchingDeathCallback = null;
1245 }
1246
1247
1248 /**
1249 * Starts GNSS batching, if available.
1250 */
1251 @Override
1252 public boolean startGnssBatch(long periodNanos, boolean wakeOnFifoFull, String packageName) {
1253 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1254 "Location Hardware permission not granted to access hardware batching");
1255
1256 if (!hasGnssPermissions(packageName) || mGnssBatchingProvider == null) {
1257 return false;
1258 }
1259
1260 if (mGnssBatchingInProgress) {
1261 // Current design does not expect multiple starts to be called repeatedly
1262 Log.e(TAG, "startGnssBatch unexpectedly called w/o stopping prior batch");
1263 // Try to clean up anyway, and continue
1264 stopGnssBatch();
1265 }
1266
1267 mGnssBatchingInProgress = true;
1268 return mGnssBatchingProvider.start(periodNanos, wakeOnFifoFull);
1269 }
1270
1271 /**
1272 * Flushes a GNSS batch in progress
1273 */
1274 @Override
1275 public void flushGnssBatch(String packageName) {
1276 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1277 "Location Hardware permission not granted to access hardware batching");
1278
1279 if (!hasGnssPermissions(packageName)) {
1280 Log.e(TAG, "flushGnssBatch called without GNSS permissions");
1281 return;
1282 }
1283
1284 if (!mGnssBatchingInProgress) {
1285 Log.w(TAG, "flushGnssBatch called with no batch in progress");
1286 }
1287
1288 if (mGnssBatchingProvider != null) {
1289 mGnssBatchingProvider.flush();
1290 }
1291 }
1292
1293 /**
1294 * Stops GNSS batching
1295 */
1296 @Override
1297 public boolean stopGnssBatch() {
1298 mContext.enforceCallingPermission(android.Manifest.permission.LOCATION_HARDWARE,
1299 "Location Hardware permission not granted to access hardware batching");
1300
1301 if (mGnssBatchingProvider != null) {
1302 mGnssBatchingInProgress = false;
1303 return mGnssBatchingProvider.stop();
1304 } else {
1305 return false;
1306 }
1307 }
1308
1309 @Override
1310 public void reportLocationBatch(List<Location> locations) {
1311 checkCallerIsProvider();
1312
1313 // Currently used only for GNSS locations - update permissions check if changed
1314 if (isAllowedByCurrentUserSettingsLocked(LocationManager.GPS_PROVIDER)) {
1315 if (mGnssBatchingCallback == null) {
1316 Slog.e(TAG, "reportLocationBatch() called without active Callback");
1317 return;
1318 }
1319 try {
1320 mGnssBatchingCallback.onLocationBatch(locations);
1321 } catch (RemoteException e) {
1322 Slog.e(TAG, "mGnssBatchingCallback.onLocationBatch failed", e);
1323 }
1324 } else {
1325 Slog.w(TAG, "reportLocationBatch() called without user permission, locations blocked");
1326 }
1327 }
1328
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001329 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001330 mProviders.add(provider);
1331 mProvidersByName.put(provider.getName(), provider);
1332 }
1333
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001334 private void removeProviderLocked(LocationProviderInterface provider) {
1335 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001336 mProviders.remove(provider);
1337 mProvidersByName.remove(provider.getName());
1338 }
1339
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001340 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001341 * Returns "true" if access to the specified location provider is allowed by the current
1342 * user's settings. Access to all location providers is forbidden to non-location-provider
1343 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001344 *
1345 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001346 */
Victoria Lease09eeaec2013-02-05 11:34:13 -08001347 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 if (mEnabledProviders.contains(provider)) {
1349 return true;
1350 }
1351 if (mDisabledProviders.contains(provider)) {
1352 return false;
1353 }
1354 // Use system settings
1355 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001356
Victoria Leaseb711d572012-10-02 13:14:11 -07001357 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001360 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -08001361 * Returns "true" if access to the specified location provider is allowed by the specified
1362 * user's settings. Access to all location providers is forbidden to non-location-provider
1363 * processes belonging to background users.
1364 *
1365 * @param provider the name of the location provider
1366 * @param uid the requestor's UID
Victoria Lease09eeaec2013-02-05 11:34:13 -08001367 */
1368 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001369 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001370 return false;
1371 }
1372 return isAllowedByCurrentUserSettingsLocked(provider);
1373 }
1374
1375 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001376 * Returns the permission string associated with the specified resolution level.
1377 *
1378 * @param resolutionLevel the resolution level
1379 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001380 */
Victoria Lease37425c32012-10-16 16:08:48 -07001381 private String getResolutionPermission(int resolutionLevel) {
1382 switch (resolutionLevel) {
1383 case RESOLUTION_LEVEL_FINE:
1384 return android.Manifest.permission.ACCESS_FINE_LOCATION;
1385 case RESOLUTION_LEVEL_COARSE:
1386 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
1387 default:
1388 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
Victoria Leaseda479c52012-10-15 15:24:16 -07001390 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001391
Victoria Leaseda479c52012-10-15 15:24:16 -07001392 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001393 * Returns the resolution level allowed to the given PID/UID pair.
1394 *
1395 * @param pid the PID
1396 * @param uid the UID
1397 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001398 */
Victoria Lease37425c32012-10-16 16:08:48 -07001399 private int getAllowedResolutionLevel(int pid, int uid) {
1400 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1401 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1402 return RESOLUTION_LEVEL_FINE;
1403 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1404 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1405 return RESOLUTION_LEVEL_COARSE;
1406 } else {
1407 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001408 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001409 }
1410
1411 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001412 * Returns the resolution level allowed to the caller
1413 *
1414 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001415 */
Victoria Lease37425c32012-10-16 16:08:48 -07001416 private int getCallerAllowedResolutionLevel() {
1417 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1418 }
1419
1420 /**
1421 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1422 *
1423 * @param allowedResolutionLevel resolution level allowed to caller
1424 */
1425 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1426 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001427 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1428 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430
Victoria Lease37425c32012-10-16 16:08:48 -07001431 /**
1432 * Return the minimum resolution level required to use the specified location provider.
1433 *
1434 * @param provider the name of the location provider
1435 * @return minimum resolution level required for provider
1436 */
1437 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001438 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1439 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1440 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001441 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001442 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1443 LocationManager.FUSED_PROVIDER.equals(provider)) {
1444 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001445 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001446 } else {
1447 // mock providers
1448 LocationProviderInterface lp = mMockProviders.get(provider);
1449 if (lp != null) {
1450 ProviderProperties properties = lp.getProperties();
1451 if (properties != null) {
1452 if (properties.mRequiresSatellite) {
1453 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001454 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001455 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1456 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001457 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001458 }
1459 }
1460 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001461 }
Victoria Lease37425c32012-10-16 16:08:48 -07001462 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001463 }
1464
Victoria Lease37425c32012-10-16 16:08:48 -07001465 /**
1466 * Throw SecurityException if specified resolution level is insufficient to use the named
1467 * location provider.
1468 *
1469 * @param allowedResolutionLevel resolution level allowed to caller
1470 * @param providerName the name of the location provider
1471 */
1472 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1473 String providerName) {
1474 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1475 if (allowedResolutionLevel < requiredResolutionLevel) {
1476 switch (requiredResolutionLevel) {
1477 case RESOLUTION_LEVEL_FINE:
1478 throw new SecurityException("\"" + providerName + "\" location provider " +
1479 "requires ACCESS_FINE_LOCATION permission.");
1480 case RESOLUTION_LEVEL_COARSE:
1481 throw new SecurityException("\"" + providerName + "\" location provider " +
1482 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1483 default:
1484 throw new SecurityException("Insufficient permission for \"" + providerName +
1485 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001486 }
1487 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001488 }
1489
David Christie82edc9b2013-07-19 11:31:42 -07001490 /**
1491 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1492 * for battery).
1493 */
David Christie40e57822013-07-30 11:36:48 -07001494 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001495 mContext.enforceCallingOrSelfPermission(
1496 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1497 }
1498
David Christie40e57822013-07-30 11:36:48 -07001499 private void checkUpdateAppOpsAllowed() {
1500 mContext.enforceCallingOrSelfPermission(
1501 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1502 }
1503
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001504 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001505 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1506 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001507 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001508 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001509 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001510 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001511 }
1512 return -1;
1513 }
1514
David Christieb870dbf2015-06-22 12:42:53 -07001515 boolean reportLocationAccessNoThrow(
1516 int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001517 int op = resolutionLevelToOp(allowedResolutionLevel);
1518 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001519 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1520 return false;
1521 }
1522 }
David Christieb870dbf2015-06-22 12:42:53 -07001523
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001524 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001525 }
1526
David Christieb870dbf2015-06-22 12:42:53 -07001527 boolean checkLocationAccess(int pid, int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001528 int op = resolutionLevelToOp(allowedResolutionLevel);
1529 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001530 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1531 return false;
1532 }
1533 }
David Christieb870dbf2015-06-22 12:42:53 -07001534
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001535 return getAllowedResolutionLevel(pid, uid) >= allowedResolutionLevel;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001536 }
1537
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001538 /**
1539 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001540 * fused, also including ones that are not permitted to
1541 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001542 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001543 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 public List<String> getAllProviders() {
destradaab376b3b2017-09-06 14:09:42 -07001545 List<String> out = getProviders(null /*criteria*/, false /*enabledOnly*/);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001546 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 return out;
1548 }
1549
Mike Lockwood03ca2162010-04-01 08:10:09 -07001550 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001551 * Return all providers by name, that match criteria and are optionally
1552 * enabled.
1553 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001554 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001555 @Override
1556 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001557 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001558 ArrayList<String> out;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001559 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001560 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001561 try {
1562 synchronized (mLock) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001563 out = new ArrayList<>(mProviders.size());
Victoria Leaseb711d572012-10-02 13:14:11 -07001564 for (LocationProviderInterface provider : mProviders) {
1565 String name = provider.getName();
1566 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001567 continue;
1568 }
Victoria Lease37425c32012-10-16 16:08:48 -07001569 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001570 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001571 continue;
1572 }
1573 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1574 name, provider.getProperties(), criteria)) {
1575 continue;
1576 }
1577 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001578 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001579 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001580 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001581 } finally {
1582 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001583 }
1584
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001585 if (D) Log.d(TAG, "getProviders()=" + out);
1586 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001587 }
1588
1589 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001590 * Return the name of the best provider given a Criteria object.
1591 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001592 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001593 * has been deprecated as well. So this method now uses
1594 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001595 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001596 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001597 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001598 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001599
1600 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001601 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001602 result = pickBest(providers);
1603 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1604 return result;
1605 }
1606 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001607 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001608 result = pickBest(providers);
1609 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1610 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001611 }
1612
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001613 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001614 return null;
1615 }
1616
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001617 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001618 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001619 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001620 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1621 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001622 } else {
1623 return providers.get(0);
1624 }
1625 }
1626
Nick Pellye0fd6932012-07-11 10:26:13 -07001627 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001628 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1629 LocationProviderInterface p = mProvidersByName.get(provider);
1630 if (p == null) {
1631 throw new IllegalArgumentException("provider=" + provider);
1632 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001633
1634 boolean result = LocationProvider.propertiesMeetCriteria(
1635 p.getName(), p.getProperties(), criteria);
1636 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1637 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001638 }
1639
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001641 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001642 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001643 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001644 boolean isEnabled = p.isEnabled();
1645 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001646 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001648 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001649 // If any provider has been disabled, clear all last locations for all providers.
1650 // This is to be on the safe side in case a provider has location derived from
1651 // this disabled provider.
1652 mLastLocation.clear();
1653 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001654 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001656 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001657 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001659 }
1660 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001661 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1662 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001663 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1664 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 }
1666 }
1667
Amith Yamasanib27528d2014-06-05 15:02:10 -07001668 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001669 int listeners = 0;
1670
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001671 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001672 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673
1674 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001675
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1677 if (records != null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001678 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001679 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001680 // Sends a notification message to the receiver
1681 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1682 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001683 deadReceivers = new ArrayList<>();
Victoria Leaseb711d572012-10-02 13:14:11 -07001684 }
1685 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001687 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690 }
1691
1692 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001693 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 removeUpdatesLocked(deadReceivers.get(i));
1695 }
1696 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001697
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001698 if (enabled) {
1699 p.enable();
1700 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001701 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001702 }
1703 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001704 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001705 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001706 }
1707
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001708 private void applyRequirementsLocked(String provider) {
1709 LocationProviderInterface p = mProvidersByName.get(provider);
1710 if (p == null) return;
1711
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001713 WorkSource worksource = new WorkSource();
1714 ProviderRequest providerRequest = new ProviderRequest();
1715
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001716 ContentResolver resolver = mContext.getContentResolver();
1717 long backgroundThrottleInterval = Settings.Global.getLong(
1718 resolver,
1719 Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS,
1720 DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS);
1721
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001723 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001724 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
David Christieb870dbf2015-06-22 12:42:53 -07001725 if (checkLocationAccess(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001726 record.mReceiver.mIdentity.mPid,
1727 record.mReceiver.mIdentity.mUid,
1728 record.mReceiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001729 record.mReceiver.mAllowedResolutionLevel)) {
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001730 LocationRequest locationRequest = record.mRealRequest;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001731 long interval = locationRequest.getInterval();
1732
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001733 if (!isThrottlingExemptLocked(record.mReceiver.mIdentity)) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001734 if (!record.mIsForegroundUid) {
1735 interval = Math.max(interval, backgroundThrottleInterval);
1736 }
1737 if (interval != locationRequest.getInterval()) {
1738 locationRequest = new LocationRequest(locationRequest);
1739 locationRequest.setInterval(interval);
1740 }
1741 }
1742
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001743 record.mRequest = locationRequest;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001744 providerRequest.locationRequests.add(locationRequest);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001745 if (interval < providerRequest.interval) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001746 providerRequest.reportLocation = true;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001747 providerRequest.interval = interval;
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001748 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001749 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001750 }
1751 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001752
1753 if (providerRequest.reportLocation) {
1754 // calculate who to blame for power
1755 // This is somewhat arbitrary. We pick a threshold interval
1756 // that is slightly higher that the minimum interval, and
1757 // spread the blame across all applications with a request
1758 // under that threshold.
1759 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1760 for (UpdateRecord record : records) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001761 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mIdentity.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001762 LocationRequest locationRequest = record.mRequest;
Svet Ganove998c732016-06-10 00:12:38 -07001763
1764 // Don't assign battery blame for update records whose
1765 // client has no permission to receive location data.
1766 if (!providerRequest.locationRequests.contains(locationRequest)) {
1767 continue;
1768 }
1769
Victoria Leaseb711d572012-10-02 13:14:11 -07001770 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001771 if (record.mReceiver.mWorkSource != null
1772 && record.mReceiver.mWorkSource.size() > 0
1773 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001774 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001775 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001776 worksource.add(record.mReceiver.mWorkSource);
1777 } else {
1778 // Assign blame to caller.
1779 worksource.add(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001780 record.mReceiver.mIdentity.mUid,
1781 record.mReceiver.mIdentity.mPackageName);
David Christie82edc9b2013-07-19 11:31:42 -07001782 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001783 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001784 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001785 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001786 }
1787 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001788
1789 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1790 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 }
1792
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001793 @Override
1794 public String[] getBackgroundThrottlingWhitelist() {
1795 synchronized (mLock) {
1796 return mBackgroundThrottlePackageWhitelist.toArray(
1797 new String[mBackgroundThrottlePackageWhitelist.size()]);
1798 }
1799 }
1800
1801 private void updateBackgroundThrottlingWhitelistLocked() {
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08001802 String setting = Settings.Global.getString(
1803 mContext.getContentResolver(),
1804 Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST);
1805 if (setting == null) {
1806 setting = "";
1807 }
1808
1809 mBackgroundThrottlePackageWhitelist.clear();
1810 mBackgroundThrottlePackageWhitelist.addAll(
1811 SystemConfig.getInstance().getAllowUnthrottledLocation());
1812 mBackgroundThrottlePackageWhitelist.addAll(
1813 Arrays.asList(setting.split(",")));
1814 }
1815
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001816 private boolean isThrottlingExemptLocked(Identity identity) {
1817 if (identity.mUid == Process.SYSTEM_UID) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001818 return true;
1819 }
1820
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001821 if (mBackgroundThrottlePackageWhitelist.contains(identity.mPackageName)) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001822 return true;
1823 }
1824
1825 for (LocationProviderProxy provider : mProxyProviders) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001826 if (identity.mPackageName.equals(provider.getConnectedPackageName())) {
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001827 return true;
1828 }
1829 }
1830
Soonil Nagarkar2f1f7e82017-01-24 12:52:10 -08001831 return false;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001832 }
1833
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 private class UpdateRecord {
1835 final String mProvider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001836 final LocationRequest mRealRequest; // original request from client
1837 LocationRequest mRequest; // possibly throttled version of the request
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001838 final Receiver mReceiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001839 boolean mIsForegroundUid;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001840 Location mLastFixBroadcast;
1841 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842
1843 /**
1844 * Note: must be constructed with lock held.
1845 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001846 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 mProvider = provider;
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001848 mRealRequest = request;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001849 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 mReceiver = receiver;
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001851 mIsForegroundUid = isImportanceForeground(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001852 mActivityManager.getPackageImportance(mReceiver.mIdentity.mPackageName));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853
1854 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1855 if (records == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001856 records = new ArrayList<>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 mRecordsByProvider.put(provider, records);
1858 }
1859 if (!records.contains(this)) {
1860 records.add(this);
1861 }
David Christie2ff96af2014-01-30 16:09:37 -08001862
1863 // Update statistics for historical location requests by package/provider
1864 mRequestStatistics.startRequesting(
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001865 mReceiver.mIdentity.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
1867
1868 /**
David Christie2ff96af2014-01-30 16:09:37 -08001869 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001871 void disposeLocked(boolean removeReceiver) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001872 mRequestStatistics.stopRequesting(mReceiver.mIdentity.mPackageName, mProvider);
David Christie2ff96af2014-01-30 16:09:37 -08001873
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001874 // remove from mRecordsByProvider
1875 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1876 if (globalRecords != null) {
1877 globalRecords.remove(this);
1878 }
1879
1880 if (!removeReceiver) return; // the caller will handle the rest
1881
1882 // remove from Receiver#mUpdateRecords
1883 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1884 if (receiverRecords != null) {
1885 receiverRecords.remove(this.mProvider);
1886
1887 // and also remove the Receiver if it has no more update records
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08001888 if (receiverRecords.size() == 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001889 removeUpdatesLocked(mReceiver);
1890 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
1893
1894 @Override
1895 public String toString() {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08001896 return "UpdateRecord[" + mProvider + " " + mReceiver.mIdentity.mPackageName
1897 + "(" + mReceiver.mIdentity.mUid + (mIsForegroundUid ? " foreground" : " background")
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07001898 + ")" + " " + mRealRequest + "]";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
1901
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001902 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001903 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001904 IBinder binder = listener.asBinder();
1905 Receiver receiver = mReceivers.get(binder);
1906 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001907 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1908 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001909 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001910 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001911 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001912 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001913 return null;
1914 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001915 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001916 }
1917 return receiver;
1918 }
1919
David Christie82edc9b2013-07-19 11:31:42 -07001920 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001921 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001922 Receiver receiver = mReceivers.get(intent);
1923 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001924 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1925 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001926 mReceivers.put(intent, receiver);
1927 }
1928 return receiver;
1929 }
1930
Victoria Lease37425c32012-10-16 16:08:48 -07001931 /**
1932 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1933 * and consistency requirements.
1934 *
1935 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001936 * @return a version of request that meets the given resolution and consistency requirements
1937 * @hide
1938 */
1939 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1940 LocationRequest sanitizedRequest = new LocationRequest(request);
1941 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1942 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001943 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001944 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001945 break;
1946 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001947 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001948 break;
1949 }
1950 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001951 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1952 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001953 }
Victoria Lease37425c32012-10-16 16:08:48 -07001954 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1955 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001956 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001957 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001958 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001959 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001960 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001961 }
Victoria Lease37425c32012-10-16 16:08:48 -07001962 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001963 }
1964
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001965 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001966 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001967 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001968 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001969 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001970 String[] packages = mPackageManager.getPackagesForUid(uid);
1971 if (packages == null) {
1972 throw new SecurityException("invalid UID " + uid);
1973 }
1974 for (String pkg : packages) {
1975 if (packageName.equals(pkg)) return;
1976 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001977 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001978 }
1979
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001980 private void checkPendingIntent(PendingIntent intent) {
1981 if (intent == null) {
1982 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001983 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001984 }
1985
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001986 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001987 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001988 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001989 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001990 } else if (intent != null && listener != null) {
1991 throw new IllegalArgumentException("cannot register both listener and intent");
1992 } else if (intent != null) {
1993 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001994 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001995 } else {
David Christie40e57822013-07-30 11:36:48 -07001996 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001997 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001998 }
1999
Nick Pellye0fd6932012-07-11 10:26:13 -07002000 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002001 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
2002 PendingIntent intent, String packageName) {
2003 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2004 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002005 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2006 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2007 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07002008 WorkSource workSource = request.getWorkSource();
2009 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07002010 checkDeviceStatsAllowed();
2011 }
2012 boolean hideFromAppOps = request.getHideFromAppOps();
2013 if (hideFromAppOps) {
2014 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07002015 }
Victoria Lease37425c32012-10-16 16:08:48 -07002016 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002017
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002018 final int pid = Binder.getCallingPid();
2019 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002020 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002021 long identity = Binder.clearCallingIdentity();
2022 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002023 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
2024 // a location.
David Christieb870dbf2015-06-22 12:42:53 -07002025 checkLocationAccess(pid, uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002026
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002027 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002028 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07002029 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07002030 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04002031 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002032 } finally {
2033 Binder.restoreCallingIdentity(identity);
2034 }
2035 }
2036
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002037 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
2038 int pid, int uid, String packageName) {
2039 // Figure out the provider. Either its explicitly request (legacy use cases), or
2040 // use the fused provider
2041 if (request == null) request = DEFAULT_LOCATION_REQUEST;
2042 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07002043 if (name == null) {
2044 throw new IllegalArgumentException("provider name must not be null");
2045 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07002046
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002047 LocationProviderInterface provider = mProvidersByName.get(name);
2048 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07002049 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002050 }
2051
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002052 UpdateRecord record = new UpdateRecord(name, request, receiver);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002053 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
2054 + " " + name + " " + request + " from " + packageName + "(" + uid + " "
2055 + (record.mIsForegroundUid ? "foreground" : "background")
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002056 + (isThrottlingExemptLocked(receiver.mIdentity)
2057 ? " [whitelisted]" : "") + ")");
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002058
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002059 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
2060 if (oldRecord != null) {
2061 oldRecord.disposeLocked(false);
2062 }
2063
Victoria Lease09eeaec2013-02-05 11:34:13 -08002064 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002065 if (isProviderEnabled) {
2066 applyRequirementsLocked(name);
2067 } else {
2068 // Notify the listener that updates are currently disabled
2069 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002070 }
David Christie0b837452013-07-29 16:02:13 -07002071 // Update the monitoring here just in case multiple location requests were added to the
2072 // same receiver (this request may be high power and the initial might not have been).
2073 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002074 }
2075
Nick Pellye0fd6932012-07-11 10:26:13 -07002076 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002077 public void removeUpdates(ILocationListener listener, PendingIntent intent,
2078 String packageName) {
2079 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002080
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002081 final int pid = Binder.getCallingPid();
2082 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002083
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002084 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07002085 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07002086 boolean hideFromAppOps = false;
2087 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
2088 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002089
2090 // providers may use public location API's, need to clear identity
2091 long identity = Binder.clearCallingIdentity();
2092 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002093 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07002094 } finally {
2095 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002096 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097 }
2098 }
2099
2100 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08002101 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002102
2103 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
2104 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
2105 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07002106 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002108 }
2109
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07002110 receiver.updateMonitoring(false);
2111
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002112 // Record which providers were associated with this listener
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002113 HashSet<String> providers = new HashSet<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002114 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
2115 if (oldRecords != null) {
2116 // Call dispose() on the obsolete update records.
2117 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08002118 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002119 record.disposeLocked(false);
2120 }
2121 // Accumulate providers
2122 providers.addAll(oldRecords.keySet());
2123 }
2124
2125 // update provider
2126 for (String provider : providers) {
2127 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08002128 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002129 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002130 }
2131
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002132 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002133 }
2134 }
2135
Dianne Hackbornc2293022013-02-06 23:14:49 -08002136 private void applyAllProviderRequirementsLocked() {
2137 for (LocationProviderInterface p : mProviders) {
2138 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08002139 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08002140 continue;
2141 }
2142
2143 applyRequirementsLocked(p.getName());
2144 }
2145 }
2146
Nick Pellye0fd6932012-07-11 10:26:13 -07002147 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07002148 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002149 if (D) Log.d(TAG, "getLastLocation: " + request);
2150 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002151 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07002152 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002153 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2154 request.getProvider());
2155 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07002156
David Christieb870dbf2015-06-22 12:42:53 -07002157 final int pid = Binder.getCallingPid();
Dianne Hackborna06de0f2012-12-11 16:34:47 -08002158 final int uid = Binder.getCallingUid();
2159 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002160 try {
2161 if (mBlacklist.isBlacklisted(packageName)) {
2162 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
2163 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07002164 return null;
2165 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002166
David Christieb870dbf2015-06-22 12:42:53 -07002167 if (!reportLocationAccessNoThrow(pid, uid, packageName, allowedResolutionLevel)) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002168 if (D) Log.d(TAG, "not returning last loc for no op app: " +
2169 packageName);
2170 return null;
2171 }
2172
Victoria Leaseb711d572012-10-02 13:14:11 -07002173 synchronized (mLock) {
2174 // Figure out the provider. Either its explicitly request (deprecated API's),
2175 // or use the fused provider
2176 String name = request.getProvider();
2177 if (name == null) name = LocationManager.FUSED_PROVIDER;
2178 LocationProviderInterface provider = mProvidersByName.get(name);
2179 if (provider == null) return null;
2180
Victoria Lease09eeaec2013-02-05 11:34:13 -08002181 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07002182
David Christie1b9b7b12013-04-15 15:31:11 -07002183 Location location;
2184 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2185 // Make sure that an app with coarse permissions can't get frequent location
2186 // updates by calling LocationManager.getLastKnownLocation repeatedly.
2187 location = mLastLocationCoarseInterval.get(name);
2188 } else {
2189 location = mLastLocation.get(name);
2190 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002191 if (location == null) {
2192 return null;
2193 }
Victoria Lease37425c32012-10-16 16:08:48 -07002194 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002195 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2196 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002197 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07002198 }
Victoria Lease37425c32012-10-16 16:08:48 -07002199 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08002200 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07002201 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002202 }
Victoria Leaseb711d572012-10-02 13:14:11 -07002203 return null;
2204 } finally {
2205 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002206 }
2207 }
2208
2209 @Override
2210 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
2211 String packageName) {
2212 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07002213 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
2214 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002215 checkPendingIntent(intent);
2216 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07002217 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
2218 request.getProvider());
2219 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002220
Victoria Lease37425c32012-10-16 16:08:48 -07002221 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002222
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002223 // geo-fence manager uses the public location API, need to clear identity
2224 int uid = Binder.getCallingUid();
Xiaohui Chena4490622015-09-22 15:29:31 -07002225 // TODO: http://b/23822629
2226 if (UserHandle.getUserId(uid) != UserHandle.USER_SYSTEM) {
Victoria Lease56e675b2012-11-05 19:25:06 -08002227 // temporary measure until geofences work for secondary users
2228 Log.w(TAG, "proximity alerts are currently available only to the primary user");
2229 return;
2230 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002231 long identity = Binder.clearCallingIdentity();
2232 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002233 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
2234 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002235 } finally {
2236 Binder.restoreCallingIdentity(identity);
2237 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002238 }
2239
2240 @Override
2241 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002242 checkPendingIntent(intent);
2243 checkPackageName(packageName);
2244
2245 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
2246
Nick Pelly2b7a0d02012-08-17 15:09:44 -07002247 // geo-fence manager uses the public location API, need to clear identity
2248 long identity = Binder.clearCallingIdentity();
2249 try {
2250 mGeofenceManager.removeFence(geofence, intent);
2251 } finally {
2252 Binder.restoreCallingIdentity(identity);
2253 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002254 }
2255
2256
2257 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002258 public boolean registerGnssStatusCallback(IGnssStatusListener callback, String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002259 if (!hasGnssPermissions(packageName) || mGnssStatusProvider == null) {
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09002260 return false;
2261 }
2262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002263 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002264 mGnssStatusProvider.registerGnssStatusCallback(callback);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002265 } catch (RemoteException e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002266 Slog.e(TAG, "mGpsStatusProvider.registerGnssStatusCallback failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002267 return false;
2268 }
2269 return true;
2270 }
2271
Nick Pellye0fd6932012-07-11 10:26:13 -07002272 @Override
Lifu Tang30f95a72016-01-07 23:20:38 -08002273 public void unregisterGnssStatusCallback(IGnssStatusListener callback) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002274 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002275 try {
Lifu Tang30f95a72016-01-07 23:20:38 -08002276 mGnssStatusProvider.unregisterGnssStatusCallback(callback);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002277 } catch (Exception e) {
Lifu Tang30f95a72016-01-07 23:20:38 -08002278 Slog.e(TAG, "mGpsStatusProvider.unregisterGnssStatusCallback failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04002279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
2281 }
2282
Nick Pellye0fd6932012-07-11 10:26:13 -07002283 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002284 public boolean addGnssMeasurementsListener(
2285 IGnssMeasurementsListener listener,
destradaaea8a8a62014-06-23 18:19:03 -07002286 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002287 if (!hasGnssPermissions(packageName) || mGnssMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07002288 return false;
2289 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002290
2291 synchronized (mLock) {
2292 Identity callerIdentity
2293 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
2294 mGnssMeasurementsListeners.put(listener, callerIdentity);
2295 long identity = Binder.clearCallingIdentity();
2296 try {
2297 if (isThrottlingExemptLocked(callerIdentity)
2298 || isImportanceForeground(
2299 mActivityManager.getPackageImportance(packageName))) {
2300 return mGnssMeasurementsProvider.addListener(listener);
2301 }
2302 } finally {
2303 Binder.restoreCallingIdentity(identity);
2304 }
2305
2306 return true;
2307 }
destradaaea8a8a62014-06-23 18:19:03 -07002308 }
2309
2310 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002311 public void removeGnssMeasurementsListener(IGnssMeasurementsListener listener) {
2312 if (mGnssMeasurementsProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002313 synchronized (mLock) {
2314 mGnssMeasurementsListeners.remove(listener);
2315 mGnssMeasurementsProvider.removeListener(listener);
2316 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002317 }
destradaaea8a8a62014-06-23 18:19:03 -07002318 }
2319
2320 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002321 public boolean addGnssNavigationMessageListener(
2322 IGnssNavigationMessageListener listener,
destradaa4b3e3932014-07-21 18:01:47 -07002323 String packageName) {
Wyatt Rileycf879db2017-01-12 13:57:38 -08002324 if (!hasGnssPermissions(packageName) || mGnssNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07002325 return false;
2326 }
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002327
2328 synchronized (mLock) {
2329 Identity callerIdentity
2330 = new Identity(Binder.getCallingUid(), Binder.getCallingPid(), packageName);
2331 mGnssNavigationMessageListeners.put(listener, callerIdentity);
2332 long identity = Binder.clearCallingIdentity();
2333 try {
2334 if (isThrottlingExemptLocked(callerIdentity)
2335 || isImportanceForeground(
2336 mActivityManager.getPackageImportance(packageName))) {
2337 return mGnssNavigationMessageProvider.addListener(listener);
2338 }
2339 } finally {
2340 Binder.restoreCallingIdentity(identity);
2341 }
2342
2343 return true;
2344 }
destradaa4b3e3932014-07-21 18:01:47 -07002345 }
2346
2347 @Override
Lifu Tang818aa2c2016-02-01 01:52:00 -08002348 public void removeGnssNavigationMessageListener(IGnssNavigationMessageListener listener) {
2349 if (mGnssNavigationMessageProvider != null) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002350 synchronized (mLock) {
2351 mGnssNavigationMessageListeners.remove(listener);
2352 mGnssNavigationMessageProvider.removeListener(listener);
2353 }
Wei Liu5241a4c2015-05-11 14:00:36 -07002354 }
destradaa4b3e3932014-07-21 18:01:47 -07002355 }
2356
2357 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002359 if (provider == null) {
2360 // throw NullPointerException to remain compatible with previous implementation
2361 throw new NullPointerException();
2362 }
Victoria Lease37425c32012-10-16 16:08:48 -07002363 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2364 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04002365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04002367 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002368 != PackageManager.PERMISSION_GRANTED)) {
2369 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
2370 }
2371
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002372 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002373 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002374 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07002375
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002376 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 }
2378 }
2379
Nick Pellye0fd6932012-07-11 10:26:13 -07002380 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002381 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07002382 if (Binder.getCallingUid() != Process.myUid()) {
2383 throw new SecurityException(
2384 "calling sendNiResponse from outside of the system is not allowed");
2385 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04002386 try {
2387 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002388 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002389 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04002390 return false;
2391 }
2392 }
2393
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002395 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11002396 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002397 * accessed by the caller
2398 */
Nick Pellye0fd6932012-07-11 10:26:13 -07002399 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002400 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07002401 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08002402 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07002403 }
2404
Victoria Lease37425c32012-10-16 16:08:48 -07002405 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
2406 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002407
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002408 LocationProviderInterface p;
2409 synchronized (mLock) {
2410 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002411 }
2412
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002413 if (p == null) return null;
2414 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002415 }
2416
Jason Monkb71218a2015-06-17 14:44:39 -04002417 /**
2418 * @return null if the provider does not exist
2419 * @throws SecurityException if the provider is not allowed to be
2420 * accessed by the caller
2421 */
2422 @Override
2423 public String getNetworkProviderPackage() {
2424 LocationProviderInterface p;
2425 synchronized (mLock) {
2426 if (mProvidersByName.get(LocationManager.NETWORK_PROVIDER) == null) {
2427 return null;
2428 }
2429 p = mProvidersByName.get(LocationManager.NETWORK_PROVIDER);
2430 }
2431
2432 if (p instanceof LocationProviderProxy) {
2433 return ((LocationProviderProxy) p).getConnectedPackageName();
2434 }
2435 return null;
2436 }
2437
Nick Pellye0fd6932012-07-11 10:26:13 -07002438 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07002440 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
2441 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002442 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
2443
Victoria Lease09eeaec2013-02-05 11:34:13 -08002444 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07002445 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07002446 try {
2447 synchronized (mLock) {
2448 LocationProviderInterface p = mProvidersByName.get(provider);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002449 return p != null && isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07002450 }
2451 } finally {
2452 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002453 }
2454 }
2455
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002456 /**
2457 * Returns "true" if the UID belongs to a bound location provider.
2458 *
2459 * @param uid the uid
2460 * @return true if uid belongs to a bound location provider
2461 */
2462 private boolean isUidALocationProvider(int uid) {
2463 if (uid == Process.SYSTEM_UID) {
2464 return true;
2465 }
2466 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07002467 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002468 }
2469 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07002470 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002471 }
2472 return false;
2473 }
2474
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002475 private void checkCallerIsProvider() {
2476 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
2477 == PackageManager.PERMISSION_GRANTED) {
2478 return;
2479 }
2480
2481 // Previously we only used the INSTALL_LOCATION_PROVIDER
2482 // check. But that is system or signature
2483 // protection level which is not flexible enough for
2484 // providers installed oustide the system image. So
2485 // also allow providers with a UID matching the
2486 // currently bound package name
2487
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002488 if (isUidALocationProvider(Binder.getCallingUid())) {
2489 return;
2490 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002491
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002492 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2493 "or UID of a currently bound location provider");
2494 }
2495
David Christie1f141c12014-05-14 15:11:15 -07002496 /**
2497 * Returns true if the given package belongs to the given uid.
2498 */
2499 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002500 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002501 return false;
2502 }
David Christie1f141c12014-05-14 15:11:15 -07002503 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2504 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002505 return false;
2506 }
David Christie1f141c12014-05-14 15:11:15 -07002507 for (String name : packageNames) {
2508 if (packageName.equals(name)) {
2509 return true;
2510 }
2511 }
2512 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514
Nick Pellye0fd6932012-07-11 10:26:13 -07002515 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002516 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002517 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002518
Nick Pelly2eeeec22012-07-18 13:13:37 -07002519 if (!location.isComplete()) {
2520 Log.w(TAG, "Dropping incomplete location: " + location);
2521 return;
2522 }
2523
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002524 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2525 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002526 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002527 mLocationHandler.sendMessageAtFrontOfQueue(m);
2528 }
2529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530
Laurent Tu75defb62012-11-01 16:21:52 -07002531 private static boolean shouldBroadcastSafe(
2532 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002533 // Always broadcast the first update
2534 if (lastLoc == null) {
2535 return true;
2536 }
2537
Nick Pellyf1be6862012-05-15 10:53:42 -07002538 // Check whether sufficient time has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002539 long minTime = record.mRealRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002540 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2541 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002542 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 return false;
2544 }
2545
2546 // Check whether sufficient distance has been traveled
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002547 double minDistance = record.mRealRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002548 if (minDistance > 0.0) {
2549 if (loc.distanceTo(lastLoc) <= minDistance) {
2550 return false;
2551 }
2552 }
2553
Laurent Tu75defb62012-11-01 16:21:52 -07002554 // Check whether sufficient number of udpates is left
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002555 if (record.mRealRequest.getNumUpdates() <= 0) {
Laurent Tu75defb62012-11-01 16:21:52 -07002556 return false;
2557 }
2558
2559 // Check whether the expiry date has passed
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002560 return record.mRealRequest.getExpireAt() >= now;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
2562
Mike Lockwooda4903f22010-02-17 06:42:23 -05002563 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002564 if (D) Log.d(TAG, "incoming location: " + location);
2565
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002566 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002567 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002568
Laurent Tu60ec50a2012-10-04 17:00:10 -07002569 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002570 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002571 if (p == null) return;
2572
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002573 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002574 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002575 Location lastNoGPSLocation;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002576 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002577 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002578 lastLocation = new Location(provider);
2579 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002580 } else {
2581 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2582 if (noGPSLocation == null && lastNoGPSLocation != null) {
2583 // New location has no no-GPS location: adopt last no-GPS location. This is set
2584 // directly into location because we do not want to notify COARSE clients.
2585 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2586 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002587 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002588 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002589
David Christie1b9b7b12013-04-15 15:31:11 -07002590 // Update last known coarse interval location if enough time has passed.
2591 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2592 if (lastLocationCoarseInterval == null) {
2593 lastLocationCoarseInterval = new Location(location);
2594 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2595 }
2596 long timeDiffNanos = location.getElapsedRealtimeNanos()
2597 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2598 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2599 lastLocationCoarseInterval.set(location);
2600 }
2601 // Don't ever return a coarse location that is more recent than the allowed update
2602 // interval (i.e. don't allow an app to keep registering and unregistering for
2603 // location updates to overcome the minimum interval).
2604 noGPSLocation =
2605 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2606
Laurent Tu60ec50a2012-10-04 17:00:10 -07002607 // Skip if there are no UpdateRecords for this provider.
2608 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2609 if (records == null || records.size() == 0) return;
2610
Victoria Lease09016ab2012-09-16 12:33:15 -07002611 // Fetch coarse location
2612 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002613 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002614 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2615 }
2616
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002617 // Fetch latest status update time
2618 long newStatusUpdateTime = p.getStatusUpdateTime();
2619
David Christie2ff96af2014-01-30 16:09:37 -08002620 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002621 Bundle extras = new Bundle();
2622 int status = p.getStatus(extras);
2623
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002625 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002626
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002627 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002628 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002630 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002631
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002632 int receiverUserId = UserHandle.getUserId(receiver.mIdentity.mUid);
2633 if (!isCurrentProfile(receiverUserId)
2634 && !isUidALocationProvider(receiver.mIdentity.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002635 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002636 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002637 " (current user: " + mCurrentUserId + ", app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002638 receiver.mIdentity.mPackageName + ")");
Victoria Leaseb711d572012-10-02 13:14:11 -07002639 }
2640 continue;
2641 }
2642
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002643 if (mBlacklist.isBlacklisted(receiver.mIdentity.mPackageName)) {
Nick Pelly4035f5a2012-08-17 14:43:49 -07002644 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002645 receiver.mIdentity.mPackageName);
Nick Pelly4035f5a2012-08-17 14:43:49 -07002646 continue;
2647 }
2648
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002649 if (!reportLocationAccessNoThrow(
2650 receiver.mIdentity.mPid,
2651 receiver.mIdentity.mUid,
2652 receiver.mIdentity.mPackageName,
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002653 receiver.mAllowedResolutionLevel)) {
2654 if (D) Log.d(TAG, "skipping loc update for no op app: " +
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002655 receiver.mIdentity.mPackageName);
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002656 continue;
2657 }
2658
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002659 Location notifyLocation;
Victoria Lease37425c32012-10-16 16:08:48 -07002660 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2661 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002662 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002663 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002664 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002665 if (notifyLocation != null) {
2666 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002667 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002668 if (lastLoc == null) {
2669 lastLoc = new Location(notifyLocation);
2670 r.mLastFixBroadcast = lastLoc;
2671 } else {
2672 lastLoc.set(notifyLocation);
2673 }
2674 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2675 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2676 receiverDead = true;
2677 }
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002678 r.mRealRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002679 }
2680 }
2681
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002682 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002684 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002685
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002686 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002687 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002688 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002689 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002690 }
2691 }
2692
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002693 // track expired records
Soonil Nagarkard4def0c2017-05-23 15:54:55 -07002694 if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002695 if (deadUpdateRecords == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002696 deadUpdateRecords = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002697 }
2698 deadUpdateRecords.add(r);
2699 }
2700 // track dead receivers
2701 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002702 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002703 deadReceivers = new ArrayList<>();
Mike Lockwood03ca2162010-04-01 08:10:09 -07002704 }
2705 if (!deadReceivers.contains(receiver)) {
2706 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002707 }
2708 }
2709 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002710
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002711 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002712 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002713 for (Receiver receiver : deadReceivers) {
2714 removeUpdatesLocked(receiver);
2715 }
2716 }
2717 if (deadUpdateRecords != null) {
2718 for (UpdateRecord r : deadUpdateRecords) {
2719 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002720 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002721 applyRequirementsLocked(provider);
2722 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002723 }
2724
2725 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002726 public LocationWorkerHandler(Looper looper) {
2727 super(looper, null, true);
2728 }
2729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002730 @Override
2731 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002732 switch (msg.what) {
2733 case MSG_LOCATION_CHANGED:
2734 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2735 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 }
2737 }
2738 }
2739
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002740 private boolean isMockProvider(String provider) {
2741 synchronized (mLock) {
2742 return mMockProviders.containsKey(provider);
2743 }
2744 }
2745
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002746 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002747 // create a working copy of the incoming Location so that the service can modify it without
2748 // disturbing the caller's copy
2749 Location myLocation = new Location(location);
2750 String provider = myLocation.getProvider();
2751
2752 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2753 // bit if location did not come from a mock provider because passive/fused providers can
2754 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2755 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2756 myLocation.setIsFromMockProvider(true);
2757 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002758
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002759 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002760 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2761 if (!passive) {
2762 // notify passive provider of the new location
2763 mPassiveProvider.updateLocation(myLocation);
2764 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002765 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002767 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769
Mike Lockwoode97ae402010-09-29 15:23:46 -04002770 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2771 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002772 public void onPackageDisappeared(String packageName, int reason) {
2773 // remove all receivers associated with this package name
2774 synchronized (mLock) {
2775 ArrayList<Receiver> deadReceivers = null;
2776
2777 for (Receiver receiver : mReceivers.values()) {
Soonil Nagarkar681d7112017-02-23 17:14:16 -08002778 if (receiver.mIdentity.mPackageName.equals(packageName)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002779 if (deadReceivers == null) {
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08002780 deadReceivers = new ArrayList<>();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002781 }
2782 deadReceivers.add(receiver);
2783 }
2784 }
2785
2786 // perform removal outside of mReceivers loop
2787 if (deadReceivers != null) {
2788 for (Receiver receiver : deadReceivers) {
2789 removeUpdatesLocked(receiver);
2790 }
2791 }
2792 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002793 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002794 };
2795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 // Geocoder
2797
Nick Pellye0fd6932012-07-11 10:26:13 -07002798 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002799 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002800 return mGeocodeProvider != null;
2801 }
2802
Nick Pellye0fd6932012-07-11 10:26:13 -07002803 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002805 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002806 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002807 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2808 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002809 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002810 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002811 }
2812
Mike Lockwooda55c3212009-04-15 11:10:11 -04002813
Nick Pellye0fd6932012-07-11 10:26:13 -07002814 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002816 double lowerLeftLatitude, double lowerLeftLongitude,
2817 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002818 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002819
2820 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002821 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2822 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2823 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002824 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002825 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002826 }
2827
2828 // Mock Providers
2829
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002830 private boolean canCallerAccessMockLocation(String opPackageName) {
2831 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
2832 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 }
2834
Nick Pellye0fd6932012-07-11 10:26:13 -07002835 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002836 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
2837 if (!canCallerAccessMockLocation(opPackageName)) {
2838 return;
2839 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002840
Mike Lockwooda4903f22010-02-17 06:42:23 -05002841 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2842 throw new IllegalArgumentException("Cannot mock the passive location provider");
2843 }
2844
Mike Lockwood86328a92009-10-23 08:38:25 -04002845 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002846 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002847 // remove the real provider if we are replacing GPS or network provider
2848 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002849 || LocationManager.NETWORK_PROVIDER.equals(name)
2850 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002851 LocationProviderInterface p = mProvidersByName.get(name);
2852 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002853 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002854 }
2855 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002856 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 updateProvidersLocked();
2858 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002859 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
2861
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002862 private void addTestProviderLocked(String name, ProviderProperties properties) {
2863 if (mProvidersByName.get(name) != null) {
2864 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2865 }
2866 MockProvider provider = new MockProvider(name, this, properties);
2867 addProviderLocked(provider);
2868 mMockProviders.put(name, provider);
2869 mLastLocation.put(name, null);
2870 mLastLocationCoarseInterval.put(name, null);
2871 }
2872
Nick Pellye0fd6932012-07-11 10:26:13 -07002873 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002874 public void removeTestProvider(String provider, String opPackageName) {
2875 if (!canCallerAccessMockLocation(opPackageName)) {
2876 return;
2877 }
2878
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002879 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002880
2881 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002882 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002883 clearTestProviderEnabled(provider, opPackageName);
2884 clearTestProviderLocation(provider, opPackageName);
2885 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002886
You Kima6d0b6f2012-10-28 03:58:44 +09002887 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002888 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2890 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002891 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002892 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002893
2894 // reinstate real provider if available
2895 LocationProviderInterface realProvider = mRealProviders.get(provider);
2896 if (realProvider != null) {
2897 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002898 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002899 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002900 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002901 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002902 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002903 }
2904 }
2905
Nick Pellye0fd6932012-07-11 10:26:13 -07002906 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002907 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
2908 if (!canCallerAccessMockLocation(opPackageName)) {
2909 return;
2910 }
2911
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002912 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002913 MockProvider mockProvider = mMockProviders.get(provider);
2914 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002915 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2916 }
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002917
2918 // Ensure that the location is marked as being mock. There's some logic to do this in
2919 // handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
2920 Location mock = new Location(loc);
2921 mock.setIsFromMockProvider(true);
2922
2923 if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
2924 // The location has an explicit provider that is different from the mock provider
2925 // name. The caller may be trying to fool us via bug 33091107.
2926 EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
2927 provider + "!=" + loc.getProvider());
2928 }
2929
Mike Lockwood95427cd2009-05-07 13:27:54 -04002930 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2931 long identity = Binder.clearCallingIdentity();
Tom O'Neilla206a0f2016-12-15 10:26:28 -08002932 mockProvider.setLocation(mock);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002933 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002934 }
2935 }
2936
Nick Pellye0fd6932012-07-11 10:26:13 -07002937 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002938 public void clearTestProviderLocation(String provider, String opPackageName) {
2939 if (!canCallerAccessMockLocation(opPackageName)) {
2940 return;
2941 }
2942
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002943 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002944 MockProvider mockProvider = mMockProviders.get(provider);
2945 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002946 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2947 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002948 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002949 }
2950 }
2951
Nick Pellye0fd6932012-07-11 10:26:13 -07002952 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002953 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
2954 if (!canCallerAccessMockLocation(opPackageName)) {
2955 return;
2956 }
2957
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002958 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002959 MockProvider mockProvider = mMockProviders.get(provider);
2960 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002961 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2962 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002963 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002964 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002965 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002966 mEnabledProviders.add(provider);
2967 mDisabledProviders.remove(provider);
2968 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002969 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 mEnabledProviders.remove(provider);
2971 mDisabledProviders.add(provider);
2972 }
2973 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002974 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975 }
2976 }
2977
Nick Pellye0fd6932012-07-11 10:26:13 -07002978 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002979 public void clearTestProviderEnabled(String provider, String opPackageName) {
2980 if (!canCallerAccessMockLocation(opPackageName)) {
2981 return;
2982 }
2983
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002984 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002985 MockProvider mockProvider = mMockProviders.get(provider);
2986 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2988 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002989 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 mEnabledProviders.remove(provider);
2991 mDisabledProviders.remove(provider);
2992 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002993 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002994 }
2995 }
2996
Nick Pellye0fd6932012-07-11 10:26:13 -07002997 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002998 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
2999 String opPackageName) {
3000 if (!canCallerAccessMockLocation(opPackageName)) {
3001 return;
3002 }
3003
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003004 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003005 MockProvider mockProvider = mMockProviders.get(provider);
3006 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003007 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3008 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003009 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 }
3011 }
3012
Nick Pellye0fd6932012-07-11 10:26:13 -07003013 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07003014 public void clearTestProviderStatus(String provider, String opPackageName) {
3015 if (!canCallerAccessMockLocation(opPackageName)) {
3016 return;
3017 }
3018
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003019 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003020 MockProvider mockProvider = mMockProviders.get(provider);
3021 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003022 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
3023 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003024 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003025 }
3026 }
3027
3028 private void log(String log) {
3029 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08003030 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003031 }
3032 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003033
3034 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003036 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Nick Pellye0fd6932012-07-11 10:26:13 -07003037
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04003038 synchronized (mLock) {
Siddharth Raybb608c82017-03-16 11:33:34 -07003039 if (args.length > 0 && args[0].equals("--gnssmetrics")) {
3040 if (mGnssMetricsProvider != null) {
3041 pw.append(mGnssMetricsProvider.getGnssMetricsAsProtoString());
3042 }
3043 return;
3044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003045 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003047 for (Receiver receiver : mReceivers.values()) {
3048 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 }
David Christie2ff96af2014-01-30 16:09:37 -08003050 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003051 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
3052 pw.println(" " + entry.getKey() + ":");
3053 for (UpdateRecord record : entry.getValue()) {
3054 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003055 }
3056 }
Soonil Nagarkar7decfb62017-01-18 12:18:49 -08003057 pw.println(" Overlay Provider Packages:");
3058 for (LocationProviderInterface provider : mProviders) {
3059 if (provider instanceof LocationProviderProxy) {
3060 pw.println(" " + provider.getName() + ": "
3061 + ((LocationProviderProxy) provider).getConnectedPackageName());
3062 }
3063 }
David Christie2ff96af2014-01-30 16:09:37 -08003064 pw.println(" Historical Records by Provider:");
3065 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
3066 : mRequestStatistics.statistics.entrySet()) {
3067 PackageProviderKey key = entry.getKey();
3068 PackageStatistics stats = entry.getValue();
3069 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
3070 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003072 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
3073 String provider = entry.getKey();
3074 Location location = entry.getValue();
3075 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003076 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003077
David Christie1b9b7b12013-04-15 15:31:11 -07003078 pw.println(" Last Known Locations Coarse Intervals:");
3079 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
3080 String provider = entry.getKey();
3081 Location location = entry.getValue();
3082 pw.println(" " + provider + ": " + location);
3083 }
3084
Nick Pellye0fd6932012-07-11 10:26:13 -07003085 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003086
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 if (mEnabledProviders.size() > 0) {
3088 pw.println(" Enabled Providers:");
3089 for (String i : mEnabledProviders) {
3090 pw.println(" " + i);
3091 }
Nick Pellye0fd6932012-07-11 10:26:13 -07003092
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
3094 if (mDisabledProviders.size() > 0) {
3095 pw.println(" Disabled Providers:");
3096 for (String i : mDisabledProviders) {
3097 pw.println(" " + i);
3098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003099 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07003100 pw.append(" ");
3101 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 if (mMockProviders.size() > 0) {
3103 pw.println(" Mock Providers:");
3104 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07003105 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106 }
3107 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003108
Soonil Nagarkar2b565df2017-02-14 13:33:23 -08003109 if (!mBackgroundThrottlePackageWhitelist.isEmpty()) {
3110 pw.println(" Throttling Whitelisted Packages:");
3111 for (String packageName : mBackgroundThrottlePackageWhitelist) {
3112 pw.println(" " + packageName);
3113 }
3114 }
3115
Nick Pelly74fa7ea2012-08-13 19:36:38 -07003116 pw.append(" fudger: ");
3117 mLocationFudger.dump(fd, pw, args);
3118
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003119 if (args.length > 0 && "short".equals(args[0])) {
3120 return;
3121 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003122 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003123 pw.print(provider.getName() + " Internal State");
3124 if (provider instanceof LocationProviderProxy) {
3125 LocationProviderProxy proxy = (LocationProviderProxy) provider;
3126 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003127 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07003128 pw.println(":");
3129 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06003130 }
Wyatt Rileycf879db2017-01-12 13:57:38 -08003131 if (mGnssBatchingInProgress) {
3132 pw.println(" GNSS batching in progress");
3133 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 }
3135 }
3136}