blob: be83b9b26fd03a666959c25fbd38cb975429f92d [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
destradaaea8a8a62014-06-23 18:19:03 -070019import com.android.internal.content.PackageMonitor;
20import com.android.internal.location.ProviderProperties;
21import com.android.internal.location.ProviderRequest;
22import com.android.internal.os.BackgroundThread;
destradaaa4fa3b52014-07-09 10:46:39 -070023import com.android.server.location.ActivityRecognitionProxy;
destradaaea8a8a62014-06-23 18:19:03 -070024import com.android.server.location.FlpHardwareProvider;
25import com.android.server.location.FusedProxy;
26import com.android.server.location.GeocoderProxy;
27import com.android.server.location.GeofenceManager;
28import com.android.server.location.GeofenceProxy;
29import com.android.server.location.GpsLocationProvider;
30import com.android.server.location.GpsMeasurementsProvider;
destradaa4b3e3932014-07-21 18:01:47 -070031import com.android.server.location.GpsNavigationMessageProvider;
destradaaea8a8a62014-06-23 18:19:03 -070032import com.android.server.location.LocationBlacklist;
33import com.android.server.location.LocationFudger;
34import com.android.server.location.LocationProviderInterface;
35import com.android.server.location.LocationProviderProxy;
36import com.android.server.location.LocationRequestStatistics;
37import com.android.server.location.LocationRequestStatistics.PackageProviderKey;
38import com.android.server.location.LocationRequestStatistics.PackageStatistics;
39import com.android.server.location.MockProvider;
40import com.android.server.location.PassiveProvider;
41
Dianne Hackborna06de0f2012-12-11 16:34:47 -080042import android.app.AppOpsManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.app.PendingIntent;
Victoria Lease38389b62012-09-30 11:44:22 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Victoria Lease38389b62012-09-30 11:44:22 -070048import android.content.IntentFilter;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070049import android.content.pm.ApplicationInfo;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050050import android.content.pm.PackageInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.PackageManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070052import android.content.pm.PackageManager.NameNotFoundException;
Jeff Hamiltonfbadb692012-10-05 14:21:58 -050053import android.content.pm.ResolveInfo;
54import android.content.pm.Signature;
Amith Yamasanib27528d2014-06-05 15:02:10 -070055import android.content.pm.UserInfo;
Mike Lockwood628fd6d2010-01-25 22:46:13 -050056import android.content.res.Resources;
Brian Muramatsubb95cb92012-08-29 10:43:21 -070057import android.database.ContentObserver;
destradaaa4fa3b52014-07-09 10:46:39 -070058import android.hardware.location.ActivityRecognitionHardware;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.location.Address;
Mike Lockwood03ca2162010-04-01 08:10:09 -070060import android.location.Criteria;
Mike Lockwood34901402010-01-04 12:14:21 -050061import android.location.GeocoderParams;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070062import android.location.Geofence;
destradaa6568d702014-10-27 12:47:41 -070063import android.location.GpsMeasurementsEvent;
64import android.location.GpsNavigationMessageEvent;
destradaaea8a8a62014-06-23 18:19:03 -070065import android.location.IGpsMeasurementsListener;
destradaa4b3e3932014-07-21 18:01:47 -070066import android.location.IGpsNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.location.IGpsStatusListener;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -040068import android.location.IGpsStatusProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import android.location.ILocationListener;
70import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040071import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.location.Location;
73import android.location.LocationManager;
74import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070075import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Binder;
77import android.os.Bundle;
78import android.os.Handler;
79import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070080import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Message;
82import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070083import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070085import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070086import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070087import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070088import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080091import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070092
Mike Lockwood43e33f22010-03-26 10:41:48 -040093import java.io.FileDescriptor;
94import java.io.PrintWriter;
95import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070096import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040097import java.util.HashMap;
98import java.util.HashSet;
99import java.util.List;
100import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400101import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102
103/**
104 * The service class that manages LocationProviders and issues location
105 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800107public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800109 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700110
111 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Victoria Lease37425c32012-10-16 16:08:48 -0700113 // Location resolution level: no location data whatsoever
114 private static final int RESOLUTION_LEVEL_NONE = 0;
115 // Location resolution level: coarse location data only
116 private static final int RESOLUTION_LEVEL_COARSE = 1;
117 // Location resolution level: fine location data
118 private static final int RESOLUTION_LEVEL_FINE = 2;
119
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700121 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700123 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400124 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700125 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
126
127 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700128 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700129 private static final String FUSED_LOCATION_SERVICE_ACTION =
130 "com.android.location.service.FusedLocationProvider";
131
132 private static final int MSG_LOCATION_CHANGED = 1;
133
David Christie1b9b7b12013-04-15 15:31:11 -0700134 private static final long NANOS_PER_MILLI = 1000000L;
135
David Christie0b837452013-07-29 16:02:13 -0700136 // The maximum interval a location request can have and still be considered "high power".
137 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
138
Nick Pellyf1be6862012-05-15 10:53:42 -0700139 // Location Providers may sometimes deliver location updates
140 // slightly faster that requested - provide grace period so
141 // we don't unnecessarily filter events that are otherwise on
142 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700143 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700144
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700145 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
146
147 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800148 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700149
150 // used internally for synchronization
151 private final Object mLock = new Object();
152
Victoria Lease5cd731a2012-12-19 15:04:21 -0800153 // --- fields below are final after systemReady() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700154 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700155 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700156 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700157 private PowerManager mPowerManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700158 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700159 private GeocoderProxy mGeocodeProvider;
160 private IGpsStatusProvider mGpsStatusProvider;
161 private INetInitiatedListener mNetInitiatedListener;
162 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700163 private PassiveProvider mPassiveProvider; // track passive provider for special cases
164 private LocationBlacklist mBlacklist;
destradaaea8a8a62014-06-23 18:19:03 -0700165 private GpsMeasurementsProvider mGpsMeasurementsProvider;
destradaa4b3e3932014-07-21 18:01:47 -0700166 private GpsNavigationMessageProvider mGpsNavigationMessageProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700167
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700168 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169 // Set of providers that are explicitly enabled
170 private final Set<String> mEnabledProviders = new HashSet<String>();
171
172 // Set of providers that are explicitly disabled
173 private final Set<String> mDisabledProviders = new HashSet<String>();
174
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700175 // Mock (test) providers
176 private final HashMap<String, MockProvider> mMockProviders =
177 new HashMap<String, MockProvider>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800178
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700179 // all receivers
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400180 private final HashMap<Object, Receiver> mReceivers = new HashMap<Object, Receiver>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700182 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500183 private final ArrayList<LocationProviderInterface> mProviders =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700184 new ArrayList<LocationProviderInterface>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400185
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700186 // real providers, saved here when mocked out
187 private final HashMap<String, LocationProviderInterface> mRealProviders =
188 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700190 // mapping from provider name to provider
191 private final HashMap<String, LocationProviderInterface> mProvidersByName =
192 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700194 // mapping from provider name to all its UpdateRecords
195 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
196 new HashMap<String, ArrayList<UpdateRecord>>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700197
David Christie2ff96af2014-01-30 16:09:37 -0800198 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
199
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700200 // mapping from provider name to last known location
201 private final HashMap<String, Location> mLastLocation = new HashMap<String, Location>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
David Christie1b9b7b12013-04-15 15:31:11 -0700203 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
204 // locations stored here are not fudged for coarse permissions.
205 private final HashMap<String, Location> mLastLocationCoarseInterval =
206 new HashMap<String, Location>();
207
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700208 // all providers that operate over proxy, for authorizing incoming location
209 private final ArrayList<LocationProviderProxy> mProxyProviders =
210 new ArrayList<LocationProviderProxy>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
Victoria Lease38389b62012-09-30 11:44:22 -0700212 // current active user on the device - other users are denied location data
213 private int mCurrentUserId = UserHandle.USER_OWNER;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700214 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_OWNER };
Victoria Lease38389b62012-09-30 11:44:22 -0700215
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700216 public LocationManagerService(Context context) {
217 super();
218 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800219 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800220
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700221 if (D) Log.d(TAG, "Constructed");
222
223 // most startup is deferred until systemReady()
224 }
225
Svetoslav Ganova0027152013-06-25 14:59:53 -0700226 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700227 synchronized (mLock) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800228 if (D) Log.d(TAG, "systemReady()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700229
Victoria Lease5cd731a2012-12-19 15:04:21 -0800230 // fetch package manager
231 mPackageManager = mContext.getPackageManager();
232
Victoria Lease0aa28602013-05-29 15:28:26 -0700233 // fetch power manager
234 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800235
236 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700237 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800238
239 // prepare mLocationHandler's dependents
240 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
241 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
242 mBlacklist.init();
243 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
244
Dianne Hackbornc2293022013-02-06 23:14:49 -0800245 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700246 AppOpsManager.OnOpChangedListener callback
247 = new AppOpsManager.OnOpChangedInternalListener() {
248 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800249 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700250 for (Receiver receiver : mReceivers.values()) {
251 receiver.updateMonitoring(true);
252 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800253 applyAllProviderRequirementsLocked();
254 }
255 }
256 };
257 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
258
Amith Yamasanib27528d2014-06-05 15:02:10 -0700259 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
260 updateUserProfiles(mCurrentUserId);
261
Victoria Lease5cd731a2012-12-19 15:04:21 -0800262 // prepare providers
263 loadProvidersLocked();
264 updateProvidersLocked();
265 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700266
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700267 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700268 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700269 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700270 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800271 @Override
272 public void onChange(boolean selfChange) {
273 synchronized (mLock) {
274 updateProvidersLocked();
275 }
276 }
277 }, UserHandle.USER_ALL);
278 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700279
Victoria Lease38389b62012-09-30 11:44:22 -0700280 // listen for user change
281 IntentFilter intentFilter = new IntentFilter();
282 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700283 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
284 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Victoria Lease38389b62012-09-30 11:44:22 -0700285
286 mContext.registerReceiverAsUser(new BroadcastReceiver() {
287 @Override
288 public void onReceive(Context context, Intent intent) {
289 String action = intent.getAction();
290 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
291 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700292 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
293 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
294 updateUserProfiles(mCurrentUserId);
Victoria Lease38389b62012-09-30 11:44:22 -0700295 }
296 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800297 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700298 }
299
Amith Yamasanib27528d2014-06-05 15:02:10 -0700300 /**
301 * Makes a list of userids that are related to the current user. This is
302 * relevant when using managed profiles. Otherwise the list only contains
303 * the current user.
304 *
305 * @param currentUserId the current user, who might have an alter-ego.
306 */
307 void updateUserProfiles(int currentUserId) {
308 List<UserInfo> profiles = mUserManager.getProfiles(currentUserId);
309 synchronized (mLock) {
310 mCurrentUserProfiles = new int[profiles.size()];
311 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
312 mCurrentUserProfiles[i] = profiles.get(i).id;
313 }
314 }
315 }
316
317 /**
318 * Checks if the specified userId matches any of the current foreground
319 * users stored in mCurrentUserProfiles.
320 */
321 private boolean isCurrentProfile(int userId) {
322 synchronized (mLock) {
323 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
324 if (mCurrentUserProfiles[i] == userId) {
325 return true;
326 }
327 }
328 return false;
329 }
330 }
331
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500332 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
333 PackageManager pm = mContext.getPackageManager();
334 String systemPackageName = mContext.getPackageName();
335 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
336
337 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
338 new Intent(FUSED_LOCATION_SERVICE_ACTION),
339 PackageManager.GET_META_DATA, mCurrentUserId);
340 for (ResolveInfo rInfo : rInfos) {
341 String packageName = rInfo.serviceInfo.packageName;
342
343 // Check that the signature is in the list of supported sigs. If it's not in
344 // this list the standard provider binding logic won't bind to it.
345 try {
346 PackageInfo pInfo;
347 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
348 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
349 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
350 ", but has wrong signature, ignoring");
351 continue;
352 }
353 } catch (NameNotFoundException e) {
354 Log.e(TAG, "missing package: " + packageName);
355 continue;
356 }
357
358 // Get the version info
359 if (rInfo.serviceInfo.metaData == null) {
360 Log.w(TAG, "Found fused provider without metadata: " + packageName);
361 continue;
362 }
363
364 int version = rInfo.serviceInfo.metaData.getInt(
365 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
366 if (version == 0) {
367 // This should be the fallback fused location provider.
368
369 // Make sure it's in the system partition.
370 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
371 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
372 continue;
373 }
374
375 // Check that the fallback is signed the same as the OS
376 // as a proxy for coreApp="true"
377 if (pm.checkSignatures(systemPackageName, packageName)
378 != PackageManager.SIGNATURE_MATCH) {
379 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
380 + packageName);
381 continue;
382 }
383
384 // Found a valid fallback.
385 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
386 return;
387 } else {
388 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
389 }
390 }
391
392 throw new IllegalStateException("Unable to find a fused location provider that is in the "
393 + "system partition with version 0 and signed with the platform certificate. "
394 + "Such a package is needed to provide a default fused location provider in the "
395 + "event that no other fused location provider has been installed or is currently "
396 + "available. For example, coreOnly boot mode when decrypting the data "
397 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
398 }
399
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700400 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700401 // create a passive location provider, which is always enabled
402 PassiveProvider passiveProvider = new PassiveProvider(this);
403 addProviderLocked(passiveProvider);
404 mEnabledProviders.add(passiveProvider.getName());
405 mPassiveProvider = passiveProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700406 // Create a gps location provider
407 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
408 mLocationHandler.getLooper());
Victoria Lease5c24fd02012-10-01 11:00:50 -0700409
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700410 if (GpsLocationProvider.isSupported()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700411 mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
412 mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
413 addProviderLocked(gpsProvider);
414 mRealProviders.put(LocationManager.GPS_PROVIDER, gpsProvider);
415 }
destradaaea8a8a62014-06-23 18:19:03 -0700416 mGpsMeasurementsProvider = gpsProvider.getGpsMeasurementsProvider();
destradaa4b3e3932014-07-21 18:01:47 -0700417 mGpsNavigationMessageProvider = gpsProvider.getGpsNavigationMessageProvider();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700418
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700419 /*
420 Load package name(s) containing location provider support.
421 These packages can contain services implementing location providers:
422 Geocoder Provider, Network Location Provider, and
423 Fused Location Provider. They will each be searched for
424 service components implementing these providers.
425 The location framework also has support for installation
426 of new location providers at run-time. The new package does not
427 have to be explicitly listed here, however it must have a signature
428 that matches the signature of at least one package on this list.
429 */
430 Resources resources = mContext.getResources();
431 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500432 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700433 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500434 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
435 Arrays.toString(pkgs));
436 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
437
438 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700439
440 // bind to network provider
441 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
442 mContext,
443 LocationManager.NETWORK_PROVIDER,
444 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700445 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
446 com.android.internal.R.string.config_networkLocationProviderPackageName,
447 com.android.internal.R.array.config_locationProviderPackageNames,
448 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700449 if (networkProvider != null) {
450 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
451 mProxyProviders.add(networkProvider);
452 addProviderLocked(networkProvider);
453 } else {
454 Slog.w(TAG, "no network location provider found");
455 }
456
457 // bind to fused provider
458 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
459 mContext,
460 LocationManager.FUSED_PROVIDER,
461 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700462 com.android.internal.R.bool.config_enableFusedLocationOverlay,
463 com.android.internal.R.string.config_fusedLocationProviderPackageName,
464 com.android.internal.R.array.config_locationProviderPackageNames,
465 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700466 if (fusedLocationProvider != null) {
467 addProviderLocked(fusedLocationProvider);
468 mProxyProviders.add(fusedLocationProvider);
469 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700470 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700471 } else {
472 Slog.e(TAG, "no fused location provider found",
473 new IllegalStateException("Location service needs a fused location provider"));
474 }
475
476 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700477 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
478 com.android.internal.R.bool.config_enableGeocoderOverlay,
479 com.android.internal.R.string.config_geocoderProviderPackageName,
480 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800481 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700482 if (mGeocodeProvider == null) {
483 Slog.e(TAG, "no geocoder provider found");
484 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700485
destradaaa4fa3b52014-07-09 10:46:39 -0700486 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700487 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
488 // exception, so make sure we only do that when supported
489 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700490 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700491 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700492 FusedProxy fusedProxy = FusedProxy.createAndBind(
493 mContext,
494 mLocationHandler,
495 flpHardwareProvider.getLocationHardware(),
496 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
497 com.android.internal.R.string.config_hardwareFlpPackageName,
498 com.android.internal.R.array.config_locationProviderPackageNames);
499 if (fusedProxy == null) {
500 Slog.e(TAG, "Unable to bind FusedProxy.");
501 }
destradaacfbdcd22014-04-30 11:29:11 -0700502 } else {
destradaabeea4422014-07-30 18:17:21 -0700503 flpHardwareProvider = null;
destradaaf9a274c2014-07-25 15:11:56 -0700504 Slog.e(TAG, "FLP HAL not supported");
505 }
506
507 // bind to geofence provider
508 GeofenceProxy provider = GeofenceProxy.createAndBind(
509 mContext,com.android.internal.R.bool.config_enableGeofenceOverlay,
510 com.android.internal.R.string.config_geofenceProviderPackageName,
511 com.android.internal.R.array.config_locationProviderPackageNames,
512 mLocationHandler,
513 gpsProvider.getGpsGeofenceProxy(),
destradaabeea4422014-07-30 18:17:21 -0700514 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700515 if (provider == null) {
516 Slog.e(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700517 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900518
destradaaa4fa3b52014-07-09 10:46:39 -0700519 // bind to the hardware activity recognition if supported
520 if (ActivityRecognitionHardware.isSupported()) {
521 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
522 mContext,
523 mLocationHandler,
524 ActivityRecognitionHardware.getInstance(mContext),
525 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
526 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
527 com.android.internal.R.array.config_locationProviderPackageNames);
528
529 if (proxy == null) {
530 Slog.e(TAG, "Unable to bind ActivityRecognitionProxy.");
531 }
532 } else {
533 Slog.e(TAG, "Hardware Activity-Recognition not supported.");
534 }
535
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900536 String[] testProviderStrings = resources.getStringArray(
537 com.android.internal.R.array.config_testLocationProviders);
538 for (String testProviderString : testProviderStrings) {
539 String fragments[] = testProviderString.split(",");
540 String name = fragments[0].trim();
541 if (mProvidersByName.get(name) != null) {
542 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
543 }
544 ProviderProperties properties = new ProviderProperties(
545 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
546 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
547 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
548 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
549 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
550 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
551 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
552 Integer.parseInt(fragments[8]) /* powerRequirement */,
553 Integer.parseInt(fragments[9]) /* accuracy */);
554 addTestProviderLocked(name, properties);
555 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700556 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800558 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700559 * Called when the device's active user changes.
560 * @param userId the new active user's UserId
561 */
562 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800563 if (mCurrentUserId == userId) {
564 return;
565 }
Victoria Lease83762d22012-10-03 13:51:17 -0700566 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800567 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700568 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700569 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700570 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700571 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700572 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700573 }
Victoria Lease38389b62012-09-30 11:44:22 -0700574 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700575 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700576 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700577 }
578 }
579
580 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800581 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
582 * location updates.
583 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700584 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700585 final int mUid; // uid of receiver
586 final int mPid; // pid of receiver
587 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700588 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700589
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800590 final ILocationListener mListener;
591 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700592 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700593 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700595
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400596 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700597
David Christie0b837452013-07-29 16:02:13 -0700598 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700599 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700600 // True if app ops has started monitoring this receiver for high power (gps) locations.
601 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700602 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700603 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800604
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700605 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700606 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800607 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700609 if (listener != null) {
610 mKey = listener.asBinder();
611 } else {
612 mKey = intent;
613 }
Victoria Lease37425c32012-10-16 16:08:48 -0700614 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700615 mUid = uid;
616 mPid = pid;
617 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700618 if (workSource != null && workSource.size() <= 0) {
619 workSource = null;
620 }
621 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700622 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700623
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700624 updateMonitoring(true);
625
Victoria Lease0aa28602013-05-29 15:28:26 -0700626 // construct/configure wakelock
627 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700628 if (workSource == null) {
629 workSource = new WorkSource(mUid, mPackageName);
630 }
631 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633
634 @Override
635 public boolean equals(Object otherObj) {
636 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700637 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800638 }
639 return false;
640 }
641
642 @Override
643 public int hashCode() {
644 return mKey.hashCode();
645 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800647 @Override
648 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700649 StringBuilder s = new StringBuilder();
650 s.append("Reciever[");
651 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800652 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700653 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800654 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700655 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700657 for (String p : mUpdateRecords.keySet()) {
658 s.append(" ").append(mUpdateRecords.get(p).toString());
659 }
660 s.append("]");
661 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800662 }
663
David Christie15b31912013-08-13 15:54:32 -0700664 /**
665 * Update AppOp monitoring for this receiver.
666 *
667 * @param allow If true receiver is currently active, if false it's been removed.
668 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700669 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700670 if (mHideFromAppOps) {
671 return;
672 }
673
David Christie15b31912013-08-13 15:54:32 -0700674 boolean requestingLocation = false;
675 boolean requestingHighPowerLocation = false;
676 if (allow) {
677 // See if receiver has any enabled update records. Also note if any update records
678 // are high power (has a high power provider with an interval under a threshold).
679 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
680 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
681 requestingLocation = true;
682 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800683 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700684 ProviderProperties properties = locationProvider != null
685 ? locationProvider.getProperties() : null;
686 if (properties != null
687 && properties.mPowerRequirement == Criteria.POWER_HIGH
688 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
689 requestingHighPowerLocation = true;
690 break;
691 }
692 }
693 }
694 }
695
David Christie0b837452013-07-29 16:02:13 -0700696 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700697 mOpMonitoring = updateMonitoring(
698 requestingLocation,
699 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700700 AppOpsManager.OP_MONITOR_LOCATION);
701
702 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700703 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700704 mOpHighPowerMonitoring = updateMonitoring(
705 requestingHighPowerLocation,
706 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700707 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700708 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700709 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700710 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
711 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
712 }
David Christie0b837452013-07-29 16:02:13 -0700713 }
714
715 /**
716 * Update AppOps monitoring for a single location request and op type.
717 *
718 * @param allowMonitoring True if monitoring is allowed for this request/op.
719 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
720 * @param op AppOps code for the op to update.
721 * @return True if monitoring is on for this request/op after updating.
722 */
723 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
724 int op) {
725 if (!currentlyMonitoring) {
726 if (allowMonitoring) {
727 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
728 == AppOpsManager.MODE_ALLOWED;
729 }
730 } else {
731 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
732 != AppOpsManager.MODE_ALLOWED) {
733 mAppOps.finishOp(op, mUid, mPackageName);
734 return false;
735 }
736 }
737
738 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700739 }
740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800741 public boolean isListener() {
742 return mListener != null;
743 }
744
745 public boolean isPendingIntent() {
746 return mPendingIntent != null;
747 }
748
749 public ILocationListener getListener() {
750 if (mListener != null) {
751 return mListener;
752 }
753 throw new IllegalStateException("Request for non-existent listener");
754 }
755
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800756 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
757 if (mListener != null) {
758 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700759 synchronized (this) {
760 // synchronize to ensure incrementPendingBroadcastsLocked()
761 // is called before decrementPendingBroadcasts()
762 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700763 // call this after broadcasting so we do not increment
764 // if we throw an exeption.
765 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700766 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 } catch (RemoteException e) {
768 return false;
769 }
770 } else {
771 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800772 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800773 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
774 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700775 synchronized (this) {
776 // synchronize to ensure incrementPendingBroadcastsLocked()
777 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700778 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700779 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700780 // call this after broadcasting so we do not increment
781 // if we throw an exeption.
782 incrementPendingBroadcastsLocked();
783 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 } catch (PendingIntent.CanceledException e) {
785 return false;
786 }
787 }
788 return true;
789 }
790
791 public boolean callLocationChangedLocked(Location location) {
792 if (mListener != null) {
793 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700794 synchronized (this) {
795 // synchronize to ensure incrementPendingBroadcastsLocked()
796 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800797 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700798 // call this after broadcasting so we do not increment
799 // if we throw an exeption.
800 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700801 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 } catch (RemoteException e) {
803 return false;
804 }
805 } else {
806 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800807 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800808 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700809 synchronized (this) {
810 // synchronize to ensure incrementPendingBroadcastsLocked()
811 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700812 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700813 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700814 // call this after broadcasting so we do not increment
815 // if we throw an exeption.
816 incrementPendingBroadcastsLocked();
817 }
818 } catch (PendingIntent.CanceledException e) {
819 return false;
820 }
821 }
822 return true;
823 }
824
825 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700826 // First update AppOp monitoring.
827 // An app may get/lose location access as providers are enabled/disabled.
828 updateMonitoring(true);
829
Mike Lockwood48f17512009-04-23 09:12:08 -0700830 if (mListener != null) {
831 try {
832 synchronized (this) {
833 // synchronize to ensure incrementPendingBroadcastsLocked()
834 // is called before decrementPendingBroadcasts()
835 if (enabled) {
836 mListener.onProviderEnabled(provider);
837 } else {
838 mListener.onProviderDisabled(provider);
839 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700840 // call this after broadcasting so we do not increment
841 // if we throw an exeption.
842 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700843 }
844 } catch (RemoteException e) {
845 return false;
846 }
847 } else {
848 Intent providerIntent = new Intent();
849 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
850 try {
851 synchronized (this) {
852 // synchronize to ensure incrementPendingBroadcastsLocked()
853 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700854 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700855 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700856 // call this after broadcasting so we do not increment
857 // if we throw an exeption.
858 incrementPendingBroadcastsLocked();
859 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800860 } catch (PendingIntent.CanceledException e) {
861 return false;
862 }
863 }
864 return true;
865 }
866
Nick Pellyf1be6862012-05-15 10:53:42 -0700867 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700869 if (D) Log.d(TAG, "Location listener died");
870
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400871 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 removeUpdatesLocked(this);
873 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700874 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700875 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700876 }
877 }
878
Nick Pellye0fd6932012-07-11 10:26:13 -0700879 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700880 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
881 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400882 synchronized (this) {
883 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700884 }
885 }
886
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400887 // this must be called while synchronized by caller in a synchronized block
888 // containing the sending of the broadcaset
889 private void incrementPendingBroadcastsLocked() {
890 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700891 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400892 }
893 }
894
895 private void decrementPendingBroadcastsLocked() {
896 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700897 if (mWakeLock.isHeld()) {
898 mWakeLock.release();
899 }
900 }
901 }
902
903 public void clearPendingBroadcastsLocked() {
904 if (mPendingBroadcasts > 0) {
905 mPendingBroadcasts = 0;
906 if (mWakeLock.isHeld()) {
907 mWakeLock.release();
908 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700909 }
910 }
911 }
912
Nick Pellye0fd6932012-07-11 10:26:13 -0700913 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700914 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700915 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -0400916 //the receiver list if it is not found. If it is not found then the
917 //LocationListener was removed when it had a pending broadcast and should
918 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700919 synchronized (mLock) {
920 IBinder binder = listener.asBinder();
921 Receiver receiver = mReceivers.get(binder);
922 if (receiver != null) {
923 synchronized (receiver) {
924 // so wakelock calls will succeed
925 long identity = Binder.clearCallingIdentity();
926 receiver.decrementPendingBroadcastsLocked();
927 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -0800928 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700929 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 }
931 }
932
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700933 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400934 mProviders.add(provider);
935 mProvidersByName.put(provider.getName(), provider);
936 }
937
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700938 private void removeProviderLocked(LocationProviderInterface provider) {
939 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400940 mProviders.remove(provider);
941 mProvidersByName.remove(provider.getName());
942 }
943
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800944 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800945 * Returns "true" if access to the specified location provider is allowed by the current
946 * user's settings. Access to all location providers is forbidden to non-location-provider
947 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800948 *
949 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800950 * @return
951 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800952 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 if (mEnabledProviders.contains(provider)) {
954 return true;
955 }
956 if (mDisabledProviders.contains(provider)) {
957 return false;
958 }
959 // Use system settings
960 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961
Victoria Leaseb711d572012-10-02 13:14:11 -0700962 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800963 }
964
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700965 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800966 * Returns "true" if access to the specified location provider is allowed by the specified
967 * user's settings. Access to all location providers is forbidden to non-location-provider
968 * processes belonging to background users.
969 *
970 * @param provider the name of the location provider
971 * @param uid the requestor's UID
972 * @return
973 */
974 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700975 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800976 return false;
977 }
978 return isAllowedByCurrentUserSettingsLocked(provider);
979 }
980
981 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700982 * Returns the permission string associated with the specified resolution level.
983 *
984 * @param resolutionLevel the resolution level
985 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700986 */
Victoria Lease37425c32012-10-16 16:08:48 -0700987 private String getResolutionPermission(int resolutionLevel) {
988 switch (resolutionLevel) {
989 case RESOLUTION_LEVEL_FINE:
990 return android.Manifest.permission.ACCESS_FINE_LOCATION;
991 case RESOLUTION_LEVEL_COARSE:
992 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
993 default:
994 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700996 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700997
Victoria Leaseda479c52012-10-15 15:24:16 -0700998 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700999 * Returns the resolution level allowed to the given PID/UID pair.
1000 *
1001 * @param pid the PID
1002 * @param uid the UID
1003 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001004 */
Victoria Lease37425c32012-10-16 16:08:48 -07001005 private int getAllowedResolutionLevel(int pid, int uid) {
1006 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1007 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1008 return RESOLUTION_LEVEL_FINE;
1009 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1010 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1011 return RESOLUTION_LEVEL_COARSE;
1012 } else {
1013 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001014 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001015 }
1016
1017 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001018 * Returns the resolution level allowed to the caller
1019 *
1020 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001021 */
Victoria Lease37425c32012-10-16 16:08:48 -07001022 private int getCallerAllowedResolutionLevel() {
1023 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1024 }
1025
1026 /**
1027 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1028 *
1029 * @param allowedResolutionLevel resolution level allowed to caller
1030 */
1031 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1032 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001033 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1034 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001035 }
1036
Victoria Lease37425c32012-10-16 16:08:48 -07001037 /**
1038 * Return the minimum resolution level required to use the specified location provider.
1039 *
1040 * @param provider the name of the location provider
1041 * @return minimum resolution level required for provider
1042 */
1043 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001044 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1045 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1046 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001047 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001048 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1049 LocationManager.FUSED_PROVIDER.equals(provider)) {
1050 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001051 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001052 } else {
1053 // mock providers
1054 LocationProviderInterface lp = mMockProviders.get(provider);
1055 if (lp != null) {
1056 ProviderProperties properties = lp.getProperties();
1057 if (properties != null) {
1058 if (properties.mRequiresSatellite) {
1059 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001060 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001061 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1062 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001063 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001064 }
1065 }
1066 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001067 }
Victoria Lease37425c32012-10-16 16:08:48 -07001068 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001069 }
1070
Victoria Lease37425c32012-10-16 16:08:48 -07001071 /**
1072 * Throw SecurityException if specified resolution level is insufficient to use the named
1073 * location provider.
1074 *
1075 * @param allowedResolutionLevel resolution level allowed to caller
1076 * @param providerName the name of the location provider
1077 */
1078 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1079 String providerName) {
1080 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1081 if (allowedResolutionLevel < requiredResolutionLevel) {
1082 switch (requiredResolutionLevel) {
1083 case RESOLUTION_LEVEL_FINE:
1084 throw new SecurityException("\"" + providerName + "\" location provider " +
1085 "requires ACCESS_FINE_LOCATION permission.");
1086 case RESOLUTION_LEVEL_COARSE:
1087 throw new SecurityException("\"" + providerName + "\" location provider " +
1088 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1089 default:
1090 throw new SecurityException("Insufficient permission for \"" + providerName +
1091 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001092 }
1093 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001094 }
1095
David Christie82edc9b2013-07-19 11:31:42 -07001096 /**
1097 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1098 * for battery).
1099 */
David Christie40e57822013-07-30 11:36:48 -07001100 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001101 mContext.enforceCallingOrSelfPermission(
1102 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1103 }
1104
David Christie40e57822013-07-30 11:36:48 -07001105 private void checkUpdateAppOpsAllowed() {
1106 mContext.enforceCallingOrSelfPermission(
1107 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1108 }
1109
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001110 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001111 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1112 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001113 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001114 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001115 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001116 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001117 }
1118 return -1;
1119 }
1120
1121 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
1122 int op = resolutionLevelToOp(allowedResolutionLevel);
1123 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001124 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1125 return false;
1126 }
1127 }
1128 return true;
1129 }
1130
1131 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001132 int op = resolutionLevelToOp(allowedResolutionLevel);
1133 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001134 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1135 return false;
1136 }
1137 }
1138 return true;
1139 }
1140
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001141 /**
1142 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001143 * fused, also including ones that are not permitted to
1144 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001145 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001146 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001148 ArrayList<String> out;
1149 synchronized (mLock) {
1150 out = new ArrayList<String>(mProviders.size());
1151 for (LocationProviderInterface provider : mProviders) {
1152 String name = provider.getName();
1153 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001154 continue;
1155 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 out.add(name);
1157 }
1158 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001159
1160 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 return out;
1162 }
1163
Mike Lockwood03ca2162010-04-01 08:10:09 -07001164 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001165 * Return all providers by name, that match criteria and are optionally
1166 * enabled.
1167 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001168 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001169 @Override
1170 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001171 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001172 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001173 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -07001174 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001175 try {
1176 synchronized (mLock) {
1177 out = new ArrayList<String>(mProviders.size());
1178 for (LocationProviderInterface provider : mProviders) {
1179 String name = provider.getName();
1180 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001181 continue;
1182 }
Victoria Lease37425c32012-10-16 16:08:48 -07001183 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001184 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001185 continue;
1186 }
1187 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1188 name, provider.getProperties(), criteria)) {
1189 continue;
1190 }
1191 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001192 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001193 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001194 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001195 } finally {
1196 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001197 }
1198
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001199 if (D) Log.d(TAG, "getProviders()=" + out);
1200 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001201 }
1202
1203 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001204 * Return the name of the best provider given a Criteria object.
1205 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001206 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001207 * has been deprecated as well. So this method now uses
1208 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001209 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001210 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001211 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001212 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001213
1214 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001215 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001216 result = pickBest(providers);
1217 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1218 return result;
1219 }
1220 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001221 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001222 result = pickBest(providers);
1223 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1224 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001225 }
1226
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001227 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001228 return null;
1229 }
1230
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001231 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001232 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001233 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001234 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1235 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001236 } else {
1237 return providers.get(0);
1238 }
1239 }
1240
Nick Pellye0fd6932012-07-11 10:26:13 -07001241 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001242 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1243 LocationProviderInterface p = mProvidersByName.get(provider);
1244 if (p == null) {
1245 throw new IllegalArgumentException("provider=" + provider);
1246 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001247
1248 boolean result = LocationProvider.propertiesMeetCriteria(
1249 p.getName(), p.getProperties(), criteria);
1250 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1251 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001252 }
1253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001255 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001256 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001257 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 boolean isEnabled = p.isEnabled();
1259 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001260 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001262 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001263 // If any provider has been disabled, clear all last locations for all providers.
1264 // This is to be on the safe side in case a provider has location derived from
1265 // this disabled provider.
1266 mLastLocation.clear();
1267 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001268 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001270 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001271 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001273 }
1274 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001275 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1276 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001277 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1278 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001279 }
1280 }
1281
Amith Yamasanib27528d2014-06-05 15:02:10 -07001282 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 int listeners = 0;
1284
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001285 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001286 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287
1288 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001289
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1291 if (records != null) {
1292 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001293 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 UpdateRecord record = records.get(i);
Amith Yamasanib27528d2014-06-05 15:02:10 -07001295 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001296 // Sends a notification message to the receiver
1297 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1298 if (deadReceivers == null) {
1299 deadReceivers = new ArrayList<Receiver>();
1300 }
1301 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001303 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
1306 }
1307
1308 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001309 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 removeUpdatesLocked(deadReceivers.get(i));
1311 }
1312 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 if (enabled) {
1315 p.enable();
1316 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001317 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 }
1319 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001320 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
1323
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001324 private void applyRequirementsLocked(String provider) {
1325 LocationProviderInterface p = mProvidersByName.get(provider);
1326 if (p == null) return;
1327
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001329 WorkSource worksource = new WorkSource();
1330 ProviderRequest providerRequest = new ProviderRequest();
1331
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001333 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001334 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001335 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1336 record.mReceiver.mAllowedResolutionLevel)) {
1337 LocationRequest locationRequest = record.mRequest;
1338 providerRequest.locationRequests.add(locationRequest);
1339 if (locationRequest.getInterval() < providerRequest.interval) {
1340 providerRequest.reportLocation = true;
1341 providerRequest.interval = locationRequest.getInterval();
1342 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001343 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001344 }
1345 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001346
1347 if (providerRequest.reportLocation) {
1348 // calculate who to blame for power
1349 // This is somewhat arbitrary. We pick a threshold interval
1350 // that is slightly higher that the minimum interval, and
1351 // spread the blame across all applications with a request
1352 // under that threshold.
1353 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1354 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001355 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001356 LocationRequest locationRequest = record.mRequest;
1357 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001358 if (record.mReceiver.mWorkSource != null
1359 && record.mReceiver.mWorkSource.size() > 0
1360 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001361 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001362 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001363 worksource.add(record.mReceiver.mWorkSource);
1364 } else {
1365 // Assign blame to caller.
1366 worksource.add(
1367 record.mReceiver.mUid,
1368 record.mReceiver.mPackageName);
1369 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001370 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001371 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001372 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001375
1376 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1377 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
1380 private class UpdateRecord {
1381 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001382 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001384 Location mLastFixBroadcast;
1385 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386
1387 /**
1388 * Note: must be constructed with lock held.
1389 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001390 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001392 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394
1395 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1396 if (records == null) {
1397 records = new ArrayList<UpdateRecord>();
1398 mRecordsByProvider.put(provider, records);
1399 }
1400 if (!records.contains(this)) {
1401 records.add(this);
1402 }
David Christie2ff96af2014-01-30 16:09:37 -08001403
1404 // Update statistics for historical location requests by package/provider
1405 mRequestStatistics.startRequesting(
1406 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
1408
1409 /**
David Christie2ff96af2014-01-30 16:09:37 -08001410 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001412 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001413 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1414
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001415 // remove from mRecordsByProvider
1416 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1417 if (globalRecords != null) {
1418 globalRecords.remove(this);
1419 }
1420
1421 if (!removeReceiver) return; // the caller will handle the rest
1422
1423 // remove from Receiver#mUpdateRecords
1424 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1425 if (receiverRecords != null) {
1426 receiverRecords.remove(this.mProvider);
1427
1428 // and also remove the Receiver if it has no more update records
1429 if (removeReceiver && receiverRecords.size() == 0) {
1430 removeUpdatesLocked(mReceiver);
1431 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001432 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 }
1434
1435 @Override
1436 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001437 StringBuilder s = new StringBuilder();
1438 s.append("UpdateRecord[");
1439 s.append(mProvider);
1440 s.append(' ').append(mReceiver.mPackageName).append('(');
1441 s.append(mReceiver.mUid).append(')');
1442 s.append(' ').append(mRequest);
1443 s.append(']');
1444 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001448 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001449 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001450 IBinder binder = listener.asBinder();
1451 Receiver receiver = mReceivers.get(binder);
1452 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001453 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1454 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001455 mReceivers.put(binder, receiver);
1456
1457 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001458 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001459 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001460 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001461 return null;
1462 }
1463 }
1464 return receiver;
1465 }
1466
David Christie82edc9b2013-07-19 11:31:42 -07001467 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001468 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001469 Receiver receiver = mReceivers.get(intent);
1470 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001471 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1472 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001473 mReceivers.put(intent, receiver);
1474 }
1475 return receiver;
1476 }
1477
Victoria Lease37425c32012-10-16 16:08:48 -07001478 /**
1479 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1480 * and consistency requirements.
1481 *
1482 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001483 * @return a version of request that meets the given resolution and consistency requirements
1484 * @hide
1485 */
1486 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1487 LocationRequest sanitizedRequest = new LocationRequest(request);
1488 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1489 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001490 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001491 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001492 break;
1493 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001494 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001495 break;
1496 }
1497 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001498 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1499 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001500 }
Victoria Lease37425c32012-10-16 16:08:48 -07001501 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1502 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001503 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001504 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001505 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001506 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001507 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001508 }
Victoria Lease37425c32012-10-16 16:08:48 -07001509 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001510 }
1511
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001512 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001513 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001514 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001515 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001516 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001517 String[] packages = mPackageManager.getPackagesForUid(uid);
1518 if (packages == null) {
1519 throw new SecurityException("invalid UID " + uid);
1520 }
1521 for (String pkg : packages) {
1522 if (packageName.equals(pkg)) return;
1523 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001524 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001525 }
1526
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001527 private void checkPendingIntent(PendingIntent intent) {
1528 if (intent == null) {
1529 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001530 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001531 }
1532
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001533 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001534 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001535 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001536 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001537 } else if (intent != null && listener != null) {
1538 throw new IllegalArgumentException("cannot register both listener and intent");
1539 } else if (intent != null) {
1540 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001541 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001542 } else {
David Christie40e57822013-07-30 11:36:48 -07001543 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001544 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001545 }
1546
Nick Pellye0fd6932012-07-11 10:26:13 -07001547 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001548 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1549 PendingIntent intent, String packageName) {
1550 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1551 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001552 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1553 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1554 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07001555 WorkSource workSource = request.getWorkSource();
1556 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07001557 checkDeviceStatsAllowed();
1558 }
1559 boolean hideFromAppOps = request.getHideFromAppOps();
1560 if (hideFromAppOps) {
1561 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07001562 }
Victoria Lease37425c32012-10-16 16:08:48 -07001563 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001565 final int pid = Binder.getCallingPid();
1566 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001567 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 long identity = Binder.clearCallingIdentity();
1569 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001570 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1571 // a location.
Dianne Hackborn35654b62013-01-14 17:38:02 -08001572 checkLocationAccess(uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001573
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001574 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001575 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07001576 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07001577 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001579 } finally {
1580 Binder.restoreCallingIdentity(identity);
1581 }
1582 }
1583
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001584 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1585 int pid, int uid, String packageName) {
1586 // Figure out the provider. Either its explicitly request (legacy use cases), or
1587 // use the fused provider
1588 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1589 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001590 if (name == null) {
1591 throw new IllegalArgumentException("provider name must not be null");
1592 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001593
1594 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1595 + " " + name + " " + request + " from " + packageName + "(" + uid + ")");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001596 LocationProviderInterface provider = mProvidersByName.get(name);
1597 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07001598 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001599 }
1600
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001601 UpdateRecord record = new UpdateRecord(name, request, receiver);
1602 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1603 if (oldRecord != null) {
1604 oldRecord.disposeLocked(false);
1605 }
1606
Victoria Lease09eeaec2013-02-05 11:34:13 -08001607 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001608 if (isProviderEnabled) {
1609 applyRequirementsLocked(name);
1610 } else {
1611 // Notify the listener that updates are currently disabled
1612 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
David Christie0b837452013-07-29 16:02:13 -07001614 // Update the monitoring here just in case multiple location requests were added to the
1615 // same receiver (this request may be high power and the initial might not have been).
1616 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001617 }
1618
Nick Pellye0fd6932012-07-11 10:26:13 -07001619 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001620 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1621 String packageName) {
1622 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001623
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001624 final int pid = Binder.getCallingPid();
1625 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001626
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001627 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07001628 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07001629 boolean hideFromAppOps = false;
1630 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
1631 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001632
1633 // providers may use public location API's, need to clear identity
1634 long identity = Binder.clearCallingIdentity();
1635 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001636 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001637 } finally {
1638 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001640 }
1641 }
1642
1643 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001644 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001645
1646 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1647 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1648 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001649 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001651 }
1652
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07001653 receiver.updateMonitoring(false);
1654
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001655 // Record which providers were associated with this listener
1656 HashSet<String> providers = new HashSet<String>();
1657 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1658 if (oldRecords != null) {
1659 // Call dispose() on the obsolete update records.
1660 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08001661 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001662 record.disposeLocked(false);
1663 }
1664 // Accumulate providers
1665 providers.addAll(oldRecords.keySet());
1666 }
1667
1668 // update provider
1669 for (String provider : providers) {
1670 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001671 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001672 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 }
1674
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001675 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 }
1677 }
1678
Dianne Hackbornc2293022013-02-06 23:14:49 -08001679 private void applyAllProviderRequirementsLocked() {
1680 for (LocationProviderInterface p : mProviders) {
1681 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001682 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001683 continue;
1684 }
1685
1686 applyRequirementsLocked(p.getName());
1687 }
1688 }
1689
Nick Pellye0fd6932012-07-11 10:26:13 -07001690 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001691 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001692 if (D) Log.d(TAG, "getLastLocation: " + request);
1693 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001694 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001695 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001696 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1697 request.getProvider());
1698 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001699
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001700 final int uid = Binder.getCallingUid();
1701 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001702 try {
1703 if (mBlacklist.isBlacklisted(packageName)) {
1704 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1705 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001706 return null;
1707 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001708
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001709 if (!reportLocationAccessNoThrow(uid, packageName, allowedResolutionLevel)) {
1710 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1711 packageName);
1712 return null;
1713 }
1714
Victoria Leaseb711d572012-10-02 13:14:11 -07001715 synchronized (mLock) {
1716 // Figure out the provider. Either its explicitly request (deprecated API's),
1717 // or use the fused provider
1718 String name = request.getProvider();
1719 if (name == null) name = LocationManager.FUSED_PROVIDER;
1720 LocationProviderInterface provider = mProvidersByName.get(name);
1721 if (provider == null) return null;
1722
Victoria Lease09eeaec2013-02-05 11:34:13 -08001723 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001724
David Christie1b9b7b12013-04-15 15:31:11 -07001725 Location location;
1726 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1727 // Make sure that an app with coarse permissions can't get frequent location
1728 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1729 location = mLastLocationCoarseInterval.get(name);
1730 } else {
1731 location = mLastLocation.get(name);
1732 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001733 if (location == null) {
1734 return null;
1735 }
Victoria Lease37425c32012-10-16 16:08:48 -07001736 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001737 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1738 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001739 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001740 }
Victoria Lease37425c32012-10-16 16:08:48 -07001741 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001742 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001743 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001744 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001745 return null;
1746 } finally {
1747 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001748 }
1749 }
1750
1751 @Override
1752 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1753 String packageName) {
1754 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001755 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1756 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001757 checkPendingIntent(intent);
1758 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001759 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1760 request.getProvider());
1761 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001762
Victoria Lease37425c32012-10-16 16:08:48 -07001763 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001764
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001765 // geo-fence manager uses the public location API, need to clear identity
1766 int uid = Binder.getCallingUid();
Victoria Lease56e675b2012-11-05 19:25:06 -08001767 if (UserHandle.getUserId(uid) != UserHandle.USER_OWNER) {
1768 // temporary measure until geofences work for secondary users
1769 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1770 return;
1771 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001772 long identity = Binder.clearCallingIdentity();
1773 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001774 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1775 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001776 } finally {
1777 Binder.restoreCallingIdentity(identity);
1778 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001779 }
1780
1781 @Override
1782 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Victoria Lease37425c32012-10-16 16:08:48 -07001783 checkResolutionLevelIsSufficientForGeofenceUse(getCallerAllowedResolutionLevel());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001784 checkPendingIntent(intent);
1785 checkPackageName(packageName);
1786
1787 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1788
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001789 // geo-fence manager uses the public location API, need to clear identity
1790 long identity = Binder.clearCallingIdentity();
1791 try {
1792 mGeofenceManager.removeFence(geofence, intent);
1793 } finally {
1794 Binder.restoreCallingIdentity(identity);
1795 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001796 }
1797
1798
1799 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001800 public boolean addGpsStatusListener(IGpsStatusListener listener, String packageName) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001801 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1802 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001803 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001804
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001805 final int uid = Binder.getCallingUid();
1806 final long ident = Binder.clearCallingIdentity();
1807 try {
Victoria Lease3d5173d2013-02-05 16:07:32 -08001808 if (!checkLocationAccess(uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001809 return false;
1810 }
1811 } finally {
1812 Binder.restoreCallingIdentity(ident);
1813 }
1814
Takayuki Hoshib254ab6a2014-10-23 16:46:02 +09001815 if (mGpsStatusProvider == null) {
1816 return false;
1817 }
1818
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 try {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001820 mGpsStatusProvider.addGpsStatusListener(listener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001822 Slog.e(TAG, "mGpsStatusProvider.addGpsStatusListener failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001823 return false;
1824 }
1825 return true;
1826 }
1827
Nick Pellye0fd6932012-07-11 10:26:13 -07001828 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 public void removeGpsStatusListener(IGpsStatusListener listener) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001830 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001831 try {
1832 mGpsStatusProvider.removeGpsStatusListener(listener);
1833 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001834 Slog.e(TAG, "mGpsStatusProvider.removeGpsStatusListener failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 }
1837 }
1838
Nick Pellye0fd6932012-07-11 10:26:13 -07001839 @Override
destradaaea8a8a62014-06-23 18:19:03 -07001840 public boolean addGpsMeasurementsListener(
1841 IGpsMeasurementsListener listener,
1842 String packageName) {
1843 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1844 checkResolutionLevelIsSufficientForProviderUse(
1845 allowedResolutionLevel,
1846 LocationManager.GPS_PROVIDER);
1847
1848 int uid = Binder.getCallingUid();
1849 long identity = Binder.clearCallingIdentity();
1850 boolean hasLocationAccess;
1851 try {
1852 hasLocationAccess = checkLocationAccess(uid, packageName, allowedResolutionLevel);
1853 } finally {
1854 Binder.restoreCallingIdentity(identity);
1855 }
1856
1857 if (!hasLocationAccess) {
1858 return false;
1859 }
destradaaea8a8a62014-06-23 18:19:03 -07001860 return mGpsMeasurementsProvider.addListener(listener);
1861 }
1862
1863 @Override
destradaa6568d702014-10-27 12:47:41 -07001864 public void removeGpsMeasurementsListener(IGpsMeasurementsListener listener) {
1865 mGpsMeasurementsProvider.removeListener(listener);
destradaaea8a8a62014-06-23 18:19:03 -07001866 }
1867
1868 @Override
destradaa4b3e3932014-07-21 18:01:47 -07001869 public boolean addGpsNavigationMessageListener(
1870 IGpsNavigationMessageListener listener,
1871 String packageName) {
1872 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1873 checkResolutionLevelIsSufficientForProviderUse(
1874 allowedResolutionLevel,
1875 LocationManager.GPS_PROVIDER);
1876
1877 int uid = Binder.getCallingUid();
1878 long identity = Binder.clearCallingIdentity();
1879 boolean hasLocationAccess;
1880 try {
1881 hasLocationAccess = checkLocationAccess(uid, packageName, allowedResolutionLevel);
1882 } finally {
1883 Binder.restoreCallingIdentity(identity);
1884 }
1885
1886 if (!hasLocationAccess) {
1887 return false;
1888 }
1889 return mGpsNavigationMessageProvider.addListener(listener);
1890 }
1891
1892 @Override
destradaa6568d702014-10-27 12:47:41 -07001893 public void removeGpsNavigationMessageListener(IGpsNavigationMessageListener listener) {
1894 mGpsNavigationMessageProvider.removeListener(listener);
destradaa4b3e3932014-07-21 18:01:47 -07001895 }
1896
1897 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001899 if (provider == null) {
1900 // throw NullPointerException to remain compatible with previous implementation
1901 throw new NullPointerException();
1902 }
Victoria Lease37425c32012-10-16 16:08:48 -07001903 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1904 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001906 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001907 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 != PackageManager.PERMISSION_GRANTED)) {
1909 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1910 }
1911
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001912 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001913 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001914 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001915
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001916 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001917 }
1918 }
1919
Nick Pellye0fd6932012-07-11 10:26:13 -07001920 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001921 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001922 if (Binder.getCallingUid() != Process.myUid()) {
1923 throw new SecurityException(
1924 "calling sendNiResponse from outside of the system is not allowed");
1925 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001926 try {
1927 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001928 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001929 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001930 return false;
1931 }
1932 }
1933
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001934 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001935 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001936 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001937 * accessed by the caller
1938 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001939 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001940 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001941 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08001942 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07001943 }
1944
Victoria Lease37425c32012-10-16 16:08:48 -07001945 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1946 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001948 LocationProviderInterface p;
1949 synchronized (mLock) {
1950 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 }
1952
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001953 if (p == null) return null;
1954 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956
Nick Pellye0fd6932012-07-11 10:26:13 -07001957 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001958 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07001959 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
1960 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001961 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1962
Victoria Lease09eeaec2013-02-05 11:34:13 -08001963 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001964 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001965 try {
1966 synchronized (mLock) {
1967 LocationProviderInterface p = mProvidersByName.get(provider);
1968 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001969
Victoria Lease09eeaec2013-02-05 11:34:13 -08001970 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001971 }
1972 } finally {
1973 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001974 }
1975 }
1976
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001977 /**
1978 * Returns "true" if the UID belongs to a bound location provider.
1979 *
1980 * @param uid the uid
1981 * @return true if uid belongs to a bound location provider
1982 */
1983 private boolean isUidALocationProvider(int uid) {
1984 if (uid == Process.SYSTEM_UID) {
1985 return true;
1986 }
1987 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07001988 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001989 }
1990 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07001991 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001992 }
1993 return false;
1994 }
1995
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001996 private void checkCallerIsProvider() {
1997 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
1998 == PackageManager.PERMISSION_GRANTED) {
1999 return;
2000 }
2001
2002 // Previously we only used the INSTALL_LOCATION_PROVIDER
2003 // check. But that is system or signature
2004 // protection level which is not flexible enough for
2005 // providers installed oustide the system image. So
2006 // also allow providers with a UID matching the
2007 // currently bound package name
2008
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002009 if (isUidALocationProvider(Binder.getCallingUid())) {
2010 return;
2011 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002012
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002013 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2014 "or UID of a currently bound location provider");
2015 }
2016
David Christie1f141c12014-05-14 15:11:15 -07002017 /**
2018 * Returns true if the given package belongs to the given uid.
2019 */
2020 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002021 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002022 return false;
2023 }
David Christie1f141c12014-05-14 15:11:15 -07002024 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2025 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002026 return false;
2027 }
David Christie1f141c12014-05-14 15:11:15 -07002028 for (String name : packageNames) {
2029 if (packageName.equals(name)) {
2030 return true;
2031 }
2032 }
2033 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002034 }
2035
Nick Pellye0fd6932012-07-11 10:26:13 -07002036 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002037 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002038 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002039
Nick Pelly2eeeec22012-07-18 13:13:37 -07002040 if (!location.isComplete()) {
2041 Log.w(TAG, "Dropping incomplete location: " + location);
2042 return;
2043 }
2044
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002045 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2046 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002047 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002048 mLocationHandler.sendMessageAtFrontOfQueue(m);
2049 }
2050
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051
Laurent Tu75defb62012-11-01 16:21:52 -07002052 private static boolean shouldBroadcastSafe(
2053 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002054 // Always broadcast the first update
2055 if (lastLoc == null) {
2056 return true;
2057 }
2058
Nick Pellyf1be6862012-05-15 10:53:42 -07002059 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002060 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002061 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2062 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002063 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 return false;
2065 }
2066
2067 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002068 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 if (minDistance > 0.0) {
2070 if (loc.distanceTo(lastLoc) <= minDistance) {
2071 return false;
2072 }
2073 }
2074
Laurent Tu75defb62012-11-01 16:21:52 -07002075 // Check whether sufficient number of udpates is left
2076 if (record.mRequest.getNumUpdates() <= 0) {
2077 return false;
2078 }
2079
2080 // Check whether the expiry date has passed
2081 if (record.mRequest.getExpireAt() < now) {
2082 return false;
2083 }
2084
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002085 return true;
2086 }
2087
Mike Lockwooda4903f22010-02-17 06:42:23 -05002088 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002089 if (D) Log.d(TAG, "incoming location: " + location);
2090
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002091 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002092 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093
Laurent Tu60ec50a2012-10-04 17:00:10 -07002094 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002095 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002096 if (p == null) return;
2097
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002098 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002099 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2100 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002101 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002102 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002103 lastLocation = new Location(provider);
2104 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002105 } else {
2106 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2107 if (noGPSLocation == null && lastNoGPSLocation != null) {
2108 // New location has no no-GPS location: adopt last no-GPS location. This is set
2109 // directly into location because we do not want to notify COARSE clients.
2110 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2111 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002112 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002113 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002114
David Christie1b9b7b12013-04-15 15:31:11 -07002115 // Update last known coarse interval location if enough time has passed.
2116 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2117 if (lastLocationCoarseInterval == null) {
2118 lastLocationCoarseInterval = new Location(location);
2119 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2120 }
2121 long timeDiffNanos = location.getElapsedRealtimeNanos()
2122 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2123 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2124 lastLocationCoarseInterval.set(location);
2125 }
2126 // Don't ever return a coarse location that is more recent than the allowed update
2127 // interval (i.e. don't allow an app to keep registering and unregistering for
2128 // location updates to overcome the minimum interval).
2129 noGPSLocation =
2130 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2131
Laurent Tu60ec50a2012-10-04 17:00:10 -07002132 // Skip if there are no UpdateRecords for this provider.
2133 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2134 if (records == null || records.size() == 0) return;
2135
Victoria Lease09016ab2012-09-16 12:33:15 -07002136 // Fetch coarse location
2137 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002138 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002139 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2140 }
2141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 // Fetch latest status update time
2143 long newStatusUpdateTime = p.getStatusUpdateTime();
2144
David Christie2ff96af2014-01-30 16:09:37 -08002145 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 Bundle extras = new Bundle();
2147 int status = p.getStatus(extras);
2148
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002150 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002151
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002153 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002154 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002155 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002156
Victoria Lease269518e2012-10-29 08:25:39 -07002157 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002158 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002159 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002160 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002161 " (current user: " + mCurrentUserId + ", app: " +
2162 receiver.mPackageName + ")");
2163 }
2164 continue;
2165 }
2166
Nick Pelly4035f5a2012-08-17 14:43:49 -07002167 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2168 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2169 receiver.mPackageName);
2170 continue;
2171 }
2172
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002173 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
2174 receiver.mAllowedResolutionLevel)) {
2175 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2176 receiver.mPackageName);
2177 continue;
2178 }
2179
Victoria Lease09016ab2012-09-16 12:33:15 -07002180 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07002181 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2182 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002183 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002184 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002185 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002186 if (notifyLocation != null) {
2187 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002188 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002189 if (lastLoc == null) {
2190 lastLoc = new Location(notifyLocation);
2191 r.mLastFixBroadcast = lastLoc;
2192 } else {
2193 lastLoc.set(notifyLocation);
2194 }
2195 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2196 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2197 receiverDead = true;
2198 }
Laurent Tu75defb62012-11-01 16:21:52 -07002199 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201 }
2202
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002203 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002205 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002206
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002207 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002209 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002210 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002211 }
2212 }
2213
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002214 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002215 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002216 if (deadUpdateRecords == null) {
2217 deadUpdateRecords = new ArrayList<UpdateRecord>();
2218 }
2219 deadUpdateRecords.add(r);
2220 }
2221 // track dead receivers
2222 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002223 if (deadReceivers == null) {
2224 deadReceivers = new ArrayList<Receiver>();
2225 }
2226 if (!deadReceivers.contains(receiver)) {
2227 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002228 }
2229 }
2230 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002231
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002232 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002233 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002234 for (Receiver receiver : deadReceivers) {
2235 removeUpdatesLocked(receiver);
2236 }
2237 }
2238 if (deadUpdateRecords != null) {
2239 for (UpdateRecord r : deadUpdateRecords) {
2240 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002241 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002242 applyRequirementsLocked(provider);
2243 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 }
2245
2246 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002247 public LocationWorkerHandler(Looper looper) {
2248 super(looper, null, true);
2249 }
2250
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002251 @Override
2252 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002253 switch (msg.what) {
2254 case MSG_LOCATION_CHANGED:
2255 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2256 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002257 }
2258 }
2259 }
2260
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002261 private boolean isMockProvider(String provider) {
2262 synchronized (mLock) {
2263 return mMockProviders.containsKey(provider);
2264 }
2265 }
2266
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002267 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002268 // create a working copy of the incoming Location so that the service can modify it without
2269 // disturbing the caller's copy
2270 Location myLocation = new Location(location);
2271 String provider = myLocation.getProvider();
2272
2273 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2274 // bit if location did not come from a mock provider because passive/fused providers can
2275 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2276 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2277 myLocation.setIsFromMockProvider(true);
2278 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002279
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002280 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002281 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2282 if (!passive) {
2283 // notify passive provider of the new location
2284 mPassiveProvider.updateLocation(myLocation);
2285 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002286 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002287 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002288 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002289 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002290
Mike Lockwoode97ae402010-09-29 15:23:46 -04002291 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2292 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002293 public void onPackageDisappeared(String packageName, int reason) {
2294 // remove all receivers associated with this package name
2295 synchronized (mLock) {
2296 ArrayList<Receiver> deadReceivers = null;
2297
2298 for (Receiver receiver : mReceivers.values()) {
2299 if (receiver.mPackageName.equals(packageName)) {
2300 if (deadReceivers == null) {
2301 deadReceivers = new ArrayList<Receiver>();
2302 }
2303 deadReceivers.add(receiver);
2304 }
2305 }
2306
2307 // perform removal outside of mReceivers loop
2308 if (deadReceivers != null) {
2309 for (Receiver receiver : deadReceivers) {
2310 removeUpdatesLocked(receiver);
2311 }
2312 }
2313 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002314 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002315 };
2316
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002317 // Geocoder
2318
Nick Pellye0fd6932012-07-11 10:26:13 -07002319 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002320 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002321 return mGeocodeProvider != null;
2322 }
2323
Nick Pellye0fd6932012-07-11 10:26:13 -07002324 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002326 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002327 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002328 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2329 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002330 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002331 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002332 }
2333
Mike Lockwooda55c3212009-04-15 11:10:11 -04002334
Nick Pellye0fd6932012-07-11 10:26:13 -07002335 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002337 double lowerLeftLatitude, double lowerLeftLongitude,
2338 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002339 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002340
2341 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002342 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2343 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2344 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002345 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002346 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002347 }
2348
2349 // Mock Providers
2350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 private void checkMockPermissionsSafe() {
2352 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2353 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2354 if (!allowMocks) {
2355 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2356 }
2357
2358 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
David Christie2ff96af2014-01-30 16:09:37 -08002359 PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002360 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
Nick Pellye0fd6932012-07-11 10:26:13 -07002361 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002362 }
2363
Nick Pellye0fd6932012-07-11 10:26:13 -07002364 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002365 public void addTestProvider(String name, ProviderProperties properties) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002366 checkMockPermissionsSafe();
2367
Mike Lockwooda4903f22010-02-17 06:42:23 -05002368 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2369 throw new IllegalArgumentException("Cannot mock the passive location provider");
2370 }
2371
Mike Lockwood86328a92009-10-23 08:38:25 -04002372 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002373 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002374 // remove the real provider if we are replacing GPS or network provider
2375 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002376 || LocationManager.NETWORK_PROVIDER.equals(name)
2377 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002378 LocationProviderInterface p = mProvidersByName.get(name);
2379 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002380 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002381 }
2382 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002383 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002384 updateProvidersLocked();
2385 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002386 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002387 }
2388
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002389 private void addTestProviderLocked(String name, ProviderProperties properties) {
2390 if (mProvidersByName.get(name) != null) {
2391 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2392 }
2393 MockProvider provider = new MockProvider(name, this, properties);
2394 addProviderLocked(provider);
2395 mMockProviders.put(name, provider);
2396 mLastLocation.put(name, null);
2397 mLastLocationCoarseInterval.put(name, null);
2398 }
2399
Nick Pellye0fd6932012-07-11 10:26:13 -07002400 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002401 public void removeTestProvider(String provider) {
2402 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002403 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002404
2405 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002406 // we don't leave anything dangling.
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002407 clearTestProviderEnabled(provider);
2408 clearTestProviderLocation(provider);
2409 clearTestProviderStatus(provider);
2410
You Kima6d0b6f2012-10-28 03:58:44 +09002411 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002412 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002413 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2414 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002415 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002416 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002417
2418 // reinstate real provider if available
2419 LocationProviderInterface realProvider = mRealProviders.get(provider);
2420 if (realProvider != null) {
2421 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002422 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002423 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002424 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002425 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002426 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002427 }
2428 }
2429
Nick Pellye0fd6932012-07-11 10:26:13 -07002430 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002431 public void setTestProviderLocation(String provider, Location loc) {
2432 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002433 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002434 MockProvider mockProvider = mMockProviders.get(provider);
2435 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002436 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2437 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002438 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2439 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002440 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002441 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002442 }
2443 }
2444
Nick Pellye0fd6932012-07-11 10:26:13 -07002445 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 public void clearTestProviderLocation(String provider) {
2447 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002448 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002449 MockProvider mockProvider = mMockProviders.get(provider);
2450 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2452 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002453 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002454 }
2455 }
2456
Nick Pellye0fd6932012-07-11 10:26:13 -07002457 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 public void setTestProviderEnabled(String provider, boolean enabled) {
2459 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002460 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002461 MockProvider mockProvider = mMockProviders.get(provider);
2462 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002463 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2464 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002465 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002466 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002467 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002468 mEnabledProviders.add(provider);
2469 mDisabledProviders.remove(provider);
2470 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002471 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002472 mEnabledProviders.remove(provider);
2473 mDisabledProviders.add(provider);
2474 }
2475 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002476 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002477 }
2478 }
2479
Nick Pellye0fd6932012-07-11 10:26:13 -07002480 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002481 public void clearTestProviderEnabled(String provider) {
2482 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002483 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002484 MockProvider mockProvider = mMockProviders.get(provider);
2485 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2487 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002488 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002489 mEnabledProviders.remove(provider);
2490 mDisabledProviders.remove(provider);
2491 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002492 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002493 }
2494 }
2495
Nick Pellye0fd6932012-07-11 10:26:13 -07002496 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002497 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2498 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002499 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002500 MockProvider mockProvider = mMockProviders.get(provider);
2501 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2503 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002504 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 }
2506 }
2507
Nick Pellye0fd6932012-07-11 10:26:13 -07002508 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 public void clearTestProviderStatus(String provider) {
2510 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002511 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002512 MockProvider mockProvider = mMockProviders.get(provider);
2513 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002514 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2515 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002516 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518 }
2519
2520 private void log(String log) {
2521 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002522 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002523 }
2524 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002525
2526 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2528 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2529 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002530 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 + Binder.getCallingPid()
2532 + ", uid=" + Binder.getCallingUid());
2533 return;
2534 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002535
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002536 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002538 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002539 for (Receiver receiver : mReceivers.values()) {
2540 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002541 }
David Christie2ff96af2014-01-30 16:09:37 -08002542 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002543 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2544 pw.println(" " + entry.getKey() + ":");
2545 for (UpdateRecord record : entry.getValue()) {
2546 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 }
2548 }
David Christie2ff96af2014-01-30 16:09:37 -08002549 pw.println(" Historical Records by Provider:");
2550 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2551 : mRequestStatistics.statistics.entrySet()) {
2552 PackageProviderKey key = entry.getKey();
2553 PackageStatistics stats = entry.getValue();
2554 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2555 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002556 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002557 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2558 String provider = entry.getKey();
2559 Location location = entry.getValue();
2560 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002562
David Christie1b9b7b12013-04-15 15:31:11 -07002563 pw.println(" Last Known Locations Coarse Intervals:");
2564 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2565 String provider = entry.getKey();
2566 Location location = entry.getValue();
2567 pw.println(" " + provider + ": " + location);
2568 }
2569
Nick Pellye0fd6932012-07-11 10:26:13 -07002570 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002571
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002572 if (mEnabledProviders.size() > 0) {
2573 pw.println(" Enabled Providers:");
2574 for (String i : mEnabledProviders) {
2575 pw.println(" " + i);
2576 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002577
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579 if (mDisabledProviders.size() > 0) {
2580 pw.println(" Disabled Providers:");
2581 for (String i : mDisabledProviders) {
2582 pw.println(" " + i);
2583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002585 pw.append(" ");
2586 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002587 if (mMockProviders.size() > 0) {
2588 pw.println(" Mock Providers:");
2589 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002590 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002591 }
2592 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002593
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002594 pw.append(" fudger: ");
2595 mLocationFudger.dump(fd, pw, args);
2596
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002597 if (args.length > 0 && "short".equals(args[0])) {
2598 return;
2599 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002600 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002601 pw.print(provider.getName() + " Internal State");
2602 if (provider instanceof LocationProviderProxy) {
2603 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2604 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002605 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002606 pw.println(":");
2607 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002609 }
2610 }
2611}