blob: c76fc1c2a123634ddc5e20558658dde209ff4235 [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;
Wei Liu5241a4c2015-05-11 14:00:36 -070063import android.location.IGpsGeofenceHardware;
destradaaea8a8a62014-06-23 18:19:03 -070064import android.location.IGpsMeasurementsListener;
destradaa4b3e3932014-07-21 18:01:47 -070065import android.location.IGpsNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.location.IGpsStatusListener;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -040067import android.location.IGpsStatusProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.location.ILocationListener;
69import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040070import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.location.Location;
72import android.location.LocationManager;
73import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070074import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
76import android.os.Bundle;
77import android.os.Handler;
78import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070079import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Message;
81import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070082import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070084import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070085import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070086import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070087import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080090import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070091
Mike Lockwood43e33f22010-03-26 10:41:48 -040092import java.io.FileDescriptor;
93import java.io.PrintWriter;
94import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070095import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040096import java.util.HashMap;
97import java.util.HashSet;
98import java.util.List;
99import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -0400100import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101
102/**
103 * The service class that manages LocationProviders and issues location
104 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800106public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800108 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700109
110 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Victoria Lease37425c32012-10-16 16:08:48 -0700112 // Location resolution level: no location data whatsoever
113 private static final int RESOLUTION_LEVEL_NONE = 0;
114 // Location resolution level: coarse location data only
115 private static final int RESOLUTION_LEVEL_COARSE = 1;
116 // Location resolution level: fine location data
117 private static final int RESOLUTION_LEVEL_FINE = 2;
118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700120 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700122 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400123 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700124 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
125
126 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700127 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700128 private static final String FUSED_LOCATION_SERVICE_ACTION =
129 "com.android.location.service.FusedLocationProvider";
130
131 private static final int MSG_LOCATION_CHANGED = 1;
132
David Christie1b9b7b12013-04-15 15:31:11 -0700133 private static final long NANOS_PER_MILLI = 1000000L;
134
David Christie0b837452013-07-29 16:02:13 -0700135 // The maximum interval a location request can have and still be considered "high power".
136 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
137
Nick Pellyf1be6862012-05-15 10:53:42 -0700138 // Location Providers may sometimes deliver location updates
139 // slightly faster that requested - provide grace period so
140 // we don't unnecessarily filter events that are otherwise on
141 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700142 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700143
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700144 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
145
146 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800147 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700148
149 // used internally for synchronization
150 private final Object mLock = new Object();
151
Victoria Lease5cd731a2012-12-19 15:04:21 -0800152 // --- fields below are final after systemReady() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700153 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700154 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700155 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700156 private PowerManager mPowerManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700157 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700158 private GeocoderProxy mGeocodeProvider;
159 private IGpsStatusProvider mGpsStatusProvider;
160 private INetInitiatedListener mNetInitiatedListener;
161 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700162 private PassiveProvider mPassiveProvider; // track passive provider for special cases
163 private LocationBlacklist mBlacklist;
destradaaea8a8a62014-06-23 18:19:03 -0700164 private GpsMeasurementsProvider mGpsMeasurementsProvider;
destradaa4b3e3932014-07-21 18:01:47 -0700165 private GpsNavigationMessageProvider mGpsNavigationMessageProvider;
Wei Liu5241a4c2015-05-11 14:00:36 -0700166 private IGpsGeofenceHardware mGpsGeofenceProxy;
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;
406
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700407 if (GpsLocationProvider.isSupported()) {
Wei Liu5241a4c2015-05-11 14:00:36 -0700408 // Create a gps location provider
409 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
410 mLocationHandler.getLooper());
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);
Wei Liu5241a4c2015-05-11 14:00:36 -0700415 mGpsMeasurementsProvider = gpsProvider.getGpsMeasurementsProvider();
416 mGpsNavigationMessageProvider = gpsProvider.getGpsNavigationMessageProvider();
417 mGpsGeofenceProxy = gpsProvider.getGpsGeofenceProxy();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700418 }
419
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700420 /*
421 Load package name(s) containing location provider support.
422 These packages can contain services implementing location providers:
423 Geocoder Provider, Network Location Provider, and
424 Fused Location Provider. They will each be searched for
425 service components implementing these providers.
426 The location framework also has support for installation
427 of new location providers at run-time. The new package does not
428 have to be explicitly listed here, however it must have a signature
429 that matches the signature of at least one package on this list.
430 */
431 Resources resources = mContext.getResources();
432 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500433 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700434 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500435 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
436 Arrays.toString(pkgs));
437 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
438
439 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700440
441 // bind to network provider
442 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
443 mContext,
444 LocationManager.NETWORK_PROVIDER,
445 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700446 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
447 com.android.internal.R.string.config_networkLocationProviderPackageName,
448 com.android.internal.R.array.config_locationProviderPackageNames,
449 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700450 if (networkProvider != null) {
451 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
452 mProxyProviders.add(networkProvider);
453 addProviderLocked(networkProvider);
454 } else {
455 Slog.w(TAG, "no network location provider found");
456 }
457
458 // bind to fused provider
459 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
460 mContext,
461 LocationManager.FUSED_PROVIDER,
462 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700463 com.android.internal.R.bool.config_enableFusedLocationOverlay,
464 com.android.internal.R.string.config_fusedLocationProviderPackageName,
465 com.android.internal.R.array.config_locationProviderPackageNames,
466 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700467 if (fusedLocationProvider != null) {
468 addProviderLocked(fusedLocationProvider);
469 mProxyProviders.add(fusedLocationProvider);
470 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700471 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700472 } else {
473 Slog.e(TAG, "no fused location provider found",
474 new IllegalStateException("Location service needs a fused location provider"));
475 }
476
477 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700478 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
479 com.android.internal.R.bool.config_enableGeocoderOverlay,
480 com.android.internal.R.string.config_geocoderProviderPackageName,
481 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800482 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700483 if (mGeocodeProvider == null) {
484 Slog.e(TAG, "no geocoder provider found");
485 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700486
destradaaa4fa3b52014-07-09 10:46:39 -0700487 // bind to fused hardware provider if supported
destradaabeea4422014-07-30 18:17:21 -0700488 // in devices without support, requesting an instance of FlpHardwareProvider will raise an
489 // exception, so make sure we only do that when supported
490 FlpHardwareProvider flpHardwareProvider;
destradaa5ce66d82014-05-28 18:24:08 -0700491 if (FlpHardwareProvider.isSupported()) {
destradaabeea4422014-07-30 18:17:21 -0700492 flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaaf9a274c2014-07-25 15:11:56 -0700493 FusedProxy fusedProxy = FusedProxy.createAndBind(
494 mContext,
495 mLocationHandler,
496 flpHardwareProvider.getLocationHardware(),
497 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
498 com.android.internal.R.string.config_hardwareFlpPackageName,
499 com.android.internal.R.array.config_locationProviderPackageNames);
500 if (fusedProxy == null) {
501 Slog.e(TAG, "Unable to bind FusedProxy.");
502 }
destradaacfbdcd22014-04-30 11:29:11 -0700503 } else {
destradaabeea4422014-07-30 18:17:21 -0700504 flpHardwareProvider = null;
destradaaf9a274c2014-07-25 15:11:56 -0700505 Slog.e(TAG, "FLP HAL not supported");
506 }
507
508 // bind to geofence provider
509 GeofenceProxy provider = GeofenceProxy.createAndBind(
510 mContext,com.android.internal.R.bool.config_enableGeofenceOverlay,
511 com.android.internal.R.string.config_geofenceProviderPackageName,
512 com.android.internal.R.array.config_locationProviderPackageNames,
513 mLocationHandler,
Wei Liu5241a4c2015-05-11 14:00:36 -0700514 mGpsGeofenceProxy,
destradaabeea4422014-07-30 18:17:21 -0700515 flpHardwareProvider != null ? flpHardwareProvider.getGeofenceHardware() : null);
destradaaf9a274c2014-07-25 15:11:56 -0700516 if (provider == null) {
517 Slog.e(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700518 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900519
destradaaa4fa3b52014-07-09 10:46:39 -0700520 // bind to the hardware activity recognition if supported
521 if (ActivityRecognitionHardware.isSupported()) {
522 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
523 mContext,
524 mLocationHandler,
525 ActivityRecognitionHardware.getInstance(mContext),
526 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
527 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
528 com.android.internal.R.array.config_locationProviderPackageNames);
529
530 if (proxy == null) {
531 Slog.e(TAG, "Unable to bind ActivityRecognitionProxy.");
532 }
533 } else {
534 Slog.e(TAG, "Hardware Activity-Recognition not supported.");
535 }
536
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900537 String[] testProviderStrings = resources.getStringArray(
538 com.android.internal.R.array.config_testLocationProviders);
539 for (String testProviderString : testProviderStrings) {
540 String fragments[] = testProviderString.split(",");
541 String name = fragments[0].trim();
542 if (mProvidersByName.get(name) != null) {
543 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
544 }
545 ProviderProperties properties = new ProviderProperties(
546 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
547 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
548 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
549 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
550 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
551 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
552 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
553 Integer.parseInt(fragments[8]) /* powerRequirement */,
554 Integer.parseInt(fragments[9]) /* accuracy */);
555 addTestProviderLocked(name, properties);
556 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700557 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700558
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800559 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700560 * Called when the device's active user changes.
561 * @param userId the new active user's UserId
562 */
563 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800564 if (mCurrentUserId == userId) {
565 return;
566 }
Victoria Lease83762d22012-10-03 13:51:17 -0700567 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800568 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700569 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700570 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700571 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700572 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700573 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700574 }
Victoria Lease38389b62012-09-30 11:44:22 -0700575 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700576 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700577 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700578 }
579 }
580
581 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800582 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
583 * location updates.
584 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700585 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700586 final int mUid; // uid of receiver
587 final int mPid; // pid of receiver
588 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700589 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700590
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591 final ILocationListener mListener;
592 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700593 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700594 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700596
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400597 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700598
David Christie0b837452013-07-29 16:02:13 -0700599 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700600 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700601 // True if app ops has started monitoring this receiver for high power (gps) locations.
602 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700603 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700604 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800605
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700606 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700607 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800608 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800609 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700610 if (listener != null) {
611 mKey = listener.asBinder();
612 } else {
613 mKey = intent;
614 }
Victoria Lease37425c32012-10-16 16:08:48 -0700615 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700616 mUid = uid;
617 mPid = pid;
618 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700619 if (workSource != null && workSource.size() <= 0) {
620 workSource = null;
621 }
622 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700623 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700624
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700625 updateMonitoring(true);
626
Victoria Lease0aa28602013-05-29 15:28:26 -0700627 // construct/configure wakelock
628 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700629 if (workSource == null) {
630 workSource = new WorkSource(mUid, mPackageName);
631 }
632 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800633 }
634
635 @Override
636 public boolean equals(Object otherObj) {
637 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700638 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 }
640 return false;
641 }
642
643 @Override
644 public int hashCode() {
645 return mKey.hashCode();
646 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400647
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 @Override
649 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700650 StringBuilder s = new StringBuilder();
651 s.append("Reciever[");
652 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700654 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800655 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700656 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700658 for (String p : mUpdateRecords.keySet()) {
659 s.append(" ").append(mUpdateRecords.get(p).toString());
660 }
661 s.append("]");
662 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800663 }
664
David Christie15b31912013-08-13 15:54:32 -0700665 /**
666 * Update AppOp monitoring for this receiver.
667 *
668 * @param allow If true receiver is currently active, if false it's been removed.
669 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700670 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700671 if (mHideFromAppOps) {
672 return;
673 }
674
David Christie15b31912013-08-13 15:54:32 -0700675 boolean requestingLocation = false;
676 boolean requestingHighPowerLocation = false;
677 if (allow) {
678 // See if receiver has any enabled update records. Also note if any update records
679 // are high power (has a high power provider with an interval under a threshold).
680 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
681 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
682 requestingLocation = true;
683 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800684 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700685 ProviderProperties properties = locationProvider != null
686 ? locationProvider.getProperties() : null;
687 if (properties != null
688 && properties.mPowerRequirement == Criteria.POWER_HIGH
689 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
690 requestingHighPowerLocation = true;
691 break;
692 }
693 }
694 }
695 }
696
David Christie0b837452013-07-29 16:02:13 -0700697 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700698 mOpMonitoring = updateMonitoring(
699 requestingLocation,
700 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700701 AppOpsManager.OP_MONITOR_LOCATION);
702
703 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700704 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700705 mOpHighPowerMonitoring = updateMonitoring(
706 requestingHighPowerLocation,
707 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700708 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700709 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700710 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700711 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
712 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
713 }
David Christie0b837452013-07-29 16:02:13 -0700714 }
715
716 /**
717 * Update AppOps monitoring for a single location request and op type.
718 *
719 * @param allowMonitoring True if monitoring is allowed for this request/op.
720 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
721 * @param op AppOps code for the op to update.
722 * @return True if monitoring is on for this request/op after updating.
723 */
724 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
725 int op) {
726 if (!currentlyMonitoring) {
727 if (allowMonitoring) {
728 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
729 == AppOpsManager.MODE_ALLOWED;
730 }
731 } else {
732 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
733 != AppOpsManager.MODE_ALLOWED) {
734 mAppOps.finishOp(op, mUid, mPackageName);
735 return false;
736 }
737 }
738
739 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700740 }
741
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800742 public boolean isListener() {
743 return mListener != null;
744 }
745
746 public boolean isPendingIntent() {
747 return mPendingIntent != null;
748 }
749
750 public ILocationListener getListener() {
751 if (mListener != null) {
752 return mListener;
753 }
754 throw new IllegalStateException("Request for non-existent listener");
755 }
756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
758 if (mListener != null) {
759 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700760 synchronized (this) {
761 // synchronize to ensure incrementPendingBroadcastsLocked()
762 // is called before decrementPendingBroadcasts()
763 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700764 // call this after broadcasting so we do not increment
765 // if we throw an exeption.
766 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700767 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800768 } catch (RemoteException e) {
769 return false;
770 }
771 } else {
772 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800773 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800774 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
775 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700776 synchronized (this) {
777 // synchronize to ensure incrementPendingBroadcastsLocked()
778 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700779 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700780 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700781 // call this after broadcasting so we do not increment
782 // if we throw an exeption.
783 incrementPendingBroadcastsLocked();
784 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800785 } catch (PendingIntent.CanceledException e) {
786 return false;
787 }
788 }
789 return true;
790 }
791
792 public boolean callLocationChangedLocked(Location location) {
793 if (mListener != null) {
794 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700795 synchronized (this) {
796 // synchronize to ensure incrementPendingBroadcastsLocked()
797 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800798 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700799 // call this after broadcasting so we do not increment
800 // if we throw an exeption.
801 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800803 } catch (RemoteException e) {
804 return false;
805 }
806 } else {
807 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800808 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700810 synchronized (this) {
811 // synchronize to ensure incrementPendingBroadcastsLocked()
812 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700813 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700814 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700815 // call this after broadcasting so we do not increment
816 // if we throw an exeption.
817 incrementPendingBroadcastsLocked();
818 }
819 } catch (PendingIntent.CanceledException e) {
820 return false;
821 }
822 }
823 return true;
824 }
825
826 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700827 // First update AppOp monitoring.
828 // An app may get/lose location access as providers are enabled/disabled.
829 updateMonitoring(true);
830
Mike Lockwood48f17512009-04-23 09:12:08 -0700831 if (mListener != null) {
832 try {
833 synchronized (this) {
834 // synchronize to ensure incrementPendingBroadcastsLocked()
835 // is called before decrementPendingBroadcasts()
836 if (enabled) {
837 mListener.onProviderEnabled(provider);
838 } else {
839 mListener.onProviderDisabled(provider);
840 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700841 // call this after broadcasting so we do not increment
842 // if we throw an exeption.
843 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700844 }
845 } catch (RemoteException e) {
846 return false;
847 }
848 } else {
849 Intent providerIntent = new Intent();
850 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
851 try {
852 synchronized (this) {
853 // synchronize to ensure incrementPendingBroadcastsLocked()
854 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700855 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700856 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700857 // call this after broadcasting so we do not increment
858 // if we throw an exeption.
859 incrementPendingBroadcastsLocked();
860 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 } catch (PendingIntent.CanceledException e) {
862 return false;
863 }
864 }
865 return true;
866 }
867
Nick Pellyf1be6862012-05-15 10:53:42 -0700868 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700870 if (D) Log.d(TAG, "Location listener died");
871
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400872 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 removeUpdatesLocked(this);
874 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700875 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700876 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700877 }
878 }
879
Nick Pellye0fd6932012-07-11 10:26:13 -0700880 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700881 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
882 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400883 synchronized (this) {
884 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700885 }
886 }
887
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400888 // this must be called while synchronized by caller in a synchronized block
889 // containing the sending of the broadcaset
890 private void incrementPendingBroadcastsLocked() {
891 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700892 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400893 }
894 }
895
896 private void decrementPendingBroadcastsLocked() {
897 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700898 if (mWakeLock.isHeld()) {
899 mWakeLock.release();
900 }
901 }
902 }
903
904 public void clearPendingBroadcastsLocked() {
905 if (mPendingBroadcasts > 0) {
906 mPendingBroadcasts = 0;
907 if (mWakeLock.isHeld()) {
908 mWakeLock.release();
909 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700910 }
911 }
912 }
913
Nick Pellye0fd6932012-07-11 10:26:13 -0700914 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700915 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700916 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -0400917 //the receiver list if it is not found. If it is not found then the
918 //LocationListener was removed when it had a pending broadcast and should
919 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700920 synchronized (mLock) {
921 IBinder binder = listener.asBinder();
922 Receiver receiver = mReceivers.get(binder);
923 if (receiver != null) {
924 synchronized (receiver) {
925 // so wakelock calls will succeed
926 long identity = Binder.clearCallingIdentity();
927 receiver.decrementPendingBroadcastsLocked();
928 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -0800929 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700930 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 }
932 }
933
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700934 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400935 mProviders.add(provider);
936 mProvidersByName.put(provider.getName(), provider);
937 }
938
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700939 private void removeProviderLocked(LocationProviderInterface provider) {
940 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400941 mProviders.remove(provider);
942 mProvidersByName.remove(provider.getName());
943 }
944
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800945 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800946 * Returns "true" if access to the specified location provider is allowed by the current
947 * user's settings. Access to all location providers is forbidden to non-location-provider
948 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800949 *
950 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800951 * @return
952 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800953 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 if (mEnabledProviders.contains(provider)) {
955 return true;
956 }
957 if (mDisabledProviders.contains(provider)) {
958 return false;
959 }
960 // Use system settings
961 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800962
Victoria Leaseb711d572012-10-02 13:14:11 -0700963 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800964 }
965
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700966 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800967 * Returns "true" if access to the specified location provider is allowed by the specified
968 * user's settings. Access to all location providers is forbidden to non-location-provider
969 * processes belonging to background users.
970 *
971 * @param provider the name of the location provider
972 * @param uid the requestor's UID
973 * @return
974 */
975 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700976 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800977 return false;
978 }
979 return isAllowedByCurrentUserSettingsLocked(provider);
980 }
981
982 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700983 * Returns the permission string associated with the specified resolution level.
984 *
985 * @param resolutionLevel the resolution level
986 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700987 */
Victoria Lease37425c32012-10-16 16:08:48 -0700988 private String getResolutionPermission(int resolutionLevel) {
989 switch (resolutionLevel) {
990 case RESOLUTION_LEVEL_FINE:
991 return android.Manifest.permission.ACCESS_FINE_LOCATION;
992 case RESOLUTION_LEVEL_COARSE:
993 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
994 default:
995 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700997 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700998
Victoria Leaseda479c52012-10-15 15:24:16 -0700999 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001000 * Returns the resolution level allowed to the given PID/UID pair.
1001 *
1002 * @param pid the PID
1003 * @param uid the UID
1004 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -07001005 */
Victoria Lease37425c32012-10-16 16:08:48 -07001006 private int getAllowedResolutionLevel(int pid, int uid) {
1007 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1008 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1009 return RESOLUTION_LEVEL_FINE;
1010 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1011 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1012 return RESOLUTION_LEVEL_COARSE;
1013 } else {
1014 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001015 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001016 }
1017
1018 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001019 * Returns the resolution level allowed to the caller
1020 *
1021 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001022 */
Victoria Lease37425c32012-10-16 16:08:48 -07001023 private int getCallerAllowedResolutionLevel() {
1024 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1025 }
1026
1027 /**
1028 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1029 *
1030 * @param allowedResolutionLevel resolution level allowed to caller
1031 */
1032 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1033 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001034 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1035 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 }
1037
Victoria Lease37425c32012-10-16 16:08:48 -07001038 /**
1039 * Return the minimum resolution level required to use the specified location provider.
1040 *
1041 * @param provider the name of the location provider
1042 * @return minimum resolution level required for provider
1043 */
1044 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001045 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1046 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1047 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001048 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001049 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1050 LocationManager.FUSED_PROVIDER.equals(provider)) {
1051 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001052 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001053 } else {
1054 // mock providers
1055 LocationProviderInterface lp = mMockProviders.get(provider);
1056 if (lp != null) {
1057 ProviderProperties properties = lp.getProperties();
1058 if (properties != null) {
1059 if (properties.mRequiresSatellite) {
1060 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001061 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001062 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1063 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001064 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001065 }
1066 }
1067 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001068 }
Victoria Lease37425c32012-10-16 16:08:48 -07001069 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001070 }
1071
Victoria Lease37425c32012-10-16 16:08:48 -07001072 /**
1073 * Throw SecurityException if specified resolution level is insufficient to use the named
1074 * location provider.
1075 *
1076 * @param allowedResolutionLevel resolution level allowed to caller
1077 * @param providerName the name of the location provider
1078 */
1079 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1080 String providerName) {
1081 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1082 if (allowedResolutionLevel < requiredResolutionLevel) {
1083 switch (requiredResolutionLevel) {
1084 case RESOLUTION_LEVEL_FINE:
1085 throw new SecurityException("\"" + providerName + "\" location provider " +
1086 "requires ACCESS_FINE_LOCATION permission.");
1087 case RESOLUTION_LEVEL_COARSE:
1088 throw new SecurityException("\"" + providerName + "\" location provider " +
1089 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1090 default:
1091 throw new SecurityException("Insufficient permission for \"" + providerName +
1092 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001093 }
1094 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001095 }
1096
David Christie82edc9b2013-07-19 11:31:42 -07001097 /**
1098 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1099 * for battery).
1100 */
David Christie40e57822013-07-30 11:36:48 -07001101 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001102 mContext.enforceCallingOrSelfPermission(
1103 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1104 }
1105
David Christie40e57822013-07-30 11:36:48 -07001106 private void checkUpdateAppOpsAllowed() {
1107 mContext.enforceCallingOrSelfPermission(
1108 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1109 }
1110
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001111 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001112 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1113 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001114 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001115 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001116 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001117 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001118 }
1119 return -1;
1120 }
1121
1122 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
1123 int op = resolutionLevelToOp(allowedResolutionLevel);
1124 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001125 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1126 return false;
1127 }
1128 }
1129 return true;
1130 }
1131
1132 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001133 int op = resolutionLevelToOp(allowedResolutionLevel);
1134 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001135 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1136 return false;
1137 }
1138 }
1139 return true;
1140 }
1141
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001142 /**
1143 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001144 * fused, also including ones that are not permitted to
1145 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001146 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001147 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001148 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001149 ArrayList<String> out;
1150 synchronized (mLock) {
1151 out = new ArrayList<String>(mProviders.size());
1152 for (LocationProviderInterface provider : mProviders) {
1153 String name = provider.getName();
1154 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001155 continue;
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 out.add(name);
1158 }
1159 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001160
1161 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 return out;
1163 }
1164
Mike Lockwood03ca2162010-04-01 08:10:09 -07001165 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001166 * Return all providers by name, that match criteria and are optionally
1167 * enabled.
1168 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001169 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001170 @Override
1171 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001172 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001173 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001174 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -07001175 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001176 try {
1177 synchronized (mLock) {
1178 out = new ArrayList<String>(mProviders.size());
1179 for (LocationProviderInterface provider : mProviders) {
1180 String name = provider.getName();
1181 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001182 continue;
1183 }
Victoria Lease37425c32012-10-16 16:08:48 -07001184 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001185 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001186 continue;
1187 }
1188 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1189 name, provider.getProperties(), criteria)) {
1190 continue;
1191 }
1192 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001193 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001194 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001195 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001196 } finally {
1197 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001198 }
1199
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001200 if (D) Log.d(TAG, "getProviders()=" + out);
1201 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001202 }
1203
1204 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001205 * Return the name of the best provider given a Criteria object.
1206 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001207 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001208 * has been deprecated as well. So this method now uses
1209 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001210 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001211 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001212 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001213 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001214
1215 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001216 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001217 result = pickBest(providers);
1218 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1219 return result;
1220 }
1221 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001222 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001223 result = pickBest(providers);
1224 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1225 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001226 }
1227
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001228 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001229 return null;
1230 }
1231
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001232 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001233 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001234 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001235 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1236 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001237 } else {
1238 return providers.get(0);
1239 }
1240 }
1241
Nick Pellye0fd6932012-07-11 10:26:13 -07001242 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001243 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1244 LocationProviderInterface p = mProvidersByName.get(provider);
1245 if (p == null) {
1246 throw new IllegalArgumentException("provider=" + provider);
1247 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001248
1249 boolean result = LocationProvider.propertiesMeetCriteria(
1250 p.getName(), p.getProperties(), criteria);
1251 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1252 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001253 }
1254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001256 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001257 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001258 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001259 boolean isEnabled = p.isEnabled();
1260 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001261 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001263 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001264 // If any provider has been disabled, clear all last locations for all providers.
1265 // This is to be on the safe side in case a provider has location derived from
1266 // this disabled provider.
1267 mLastLocation.clear();
1268 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001269 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001270 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001271 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001272 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001274 }
1275 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001276 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1277 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001278 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1279 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 }
1281 }
1282
Amith Yamasanib27528d2014-06-05 15:02:10 -07001283 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 int listeners = 0;
1285
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001286 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001287 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288
1289 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001291 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1292 if (records != null) {
1293 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001294 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 UpdateRecord record = records.get(i);
Amith Yamasanib27528d2014-06-05 15:02:10 -07001296 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001297 // Sends a notification message to the receiver
1298 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1299 if (deadReceivers == null) {
1300 deadReceivers = new ArrayList<Receiver>();
1301 }
1302 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001304 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 }
1307 }
1308
1309 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001310 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 removeUpdatesLocked(deadReceivers.get(i));
1312 }
1313 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001314
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 if (enabled) {
1316 p.enable();
1317 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001318 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 }
1324
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001325 private void applyRequirementsLocked(String provider) {
1326 LocationProviderInterface p = mProvidersByName.get(provider);
1327 if (p == null) return;
1328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001330 WorkSource worksource = new WorkSource();
1331 ProviderRequest providerRequest = new ProviderRequest();
1332
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001334 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001335 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001336 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1337 record.mReceiver.mAllowedResolutionLevel)) {
1338 LocationRequest locationRequest = record.mRequest;
1339 providerRequest.locationRequests.add(locationRequest);
1340 if (locationRequest.getInterval() < providerRequest.interval) {
1341 providerRequest.reportLocation = true;
1342 providerRequest.interval = locationRequest.getInterval();
1343 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001344 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001345 }
1346 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001347
1348 if (providerRequest.reportLocation) {
1349 // calculate who to blame for power
1350 // This is somewhat arbitrary. We pick a threshold interval
1351 // that is slightly higher that the minimum interval, and
1352 // spread the blame across all applications with a request
1353 // under that threshold.
1354 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1355 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001356 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001357 LocationRequest locationRequest = record.mRequest;
1358 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001359 if (record.mReceiver.mWorkSource != null
1360 && record.mReceiver.mWorkSource.size() > 0
1361 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001362 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001363 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001364 worksource.add(record.mReceiver.mWorkSource);
1365 } else {
1366 // Assign blame to caller.
1367 worksource.add(
1368 record.mReceiver.mUid,
1369 record.mReceiver.mPackageName);
1370 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001371 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001372 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001373 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001376
1377 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1378 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 }
1380
1381 private class UpdateRecord {
1382 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001383 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001385 Location mLastFixBroadcast;
1386 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387
1388 /**
1389 * Note: must be constructed with lock held.
1390 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001391 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001393 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395
1396 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1397 if (records == null) {
1398 records = new ArrayList<UpdateRecord>();
1399 mRecordsByProvider.put(provider, records);
1400 }
1401 if (!records.contains(this)) {
1402 records.add(this);
1403 }
David Christie2ff96af2014-01-30 16:09:37 -08001404
1405 // Update statistics for historical location requests by package/provider
1406 mRequestStatistics.startRequesting(
1407 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 }
1409
1410 /**
David Christie2ff96af2014-01-30 16:09:37 -08001411 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001412 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001413 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001414 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1415
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001416 // remove from mRecordsByProvider
1417 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1418 if (globalRecords != null) {
1419 globalRecords.remove(this);
1420 }
1421
1422 if (!removeReceiver) return; // the caller will handle the rest
1423
1424 // remove from Receiver#mUpdateRecords
1425 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1426 if (receiverRecords != null) {
1427 receiverRecords.remove(this.mProvider);
1428
1429 // and also remove the Receiver if it has no more update records
1430 if (removeReceiver && receiverRecords.size() == 0) {
1431 removeUpdatesLocked(mReceiver);
1432 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001433 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435
1436 @Override
1437 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001438 StringBuilder s = new StringBuilder();
1439 s.append("UpdateRecord[");
1440 s.append(mProvider);
1441 s.append(' ').append(mReceiver.mPackageName).append('(');
1442 s.append(mReceiver.mUid).append(')');
1443 s.append(' ').append(mRequest);
1444 s.append(']');
1445 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001449 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001450 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001451 IBinder binder = listener.asBinder();
1452 Receiver receiver = mReceivers.get(binder);
1453 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001454 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1455 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001456 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001457 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001458 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001459 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001460 return null;
1461 }
Wen Jingcb3ab222014-03-27 13:42:59 +08001462 mReceivers.put(binder, receiver);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001463 }
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
Wei Liu5241a4c2015-05-11 14:00:36 -07001857 if (!hasLocationAccess || mGpsMeasurementsProvider == null) {
destradaaea8a8a62014-06-23 18:19:03 -07001858 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) {
Wei Liu5241a4c2015-05-11 14:00:36 -07001865 if (mGpsMeasurementsProvider != null) {
1866 mGpsMeasurementsProvider.removeListener(listener);
1867 }
destradaaea8a8a62014-06-23 18:19:03 -07001868 }
1869
1870 @Override
destradaa4b3e3932014-07-21 18:01:47 -07001871 public boolean addGpsNavigationMessageListener(
1872 IGpsNavigationMessageListener listener,
1873 String packageName) {
1874 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1875 checkResolutionLevelIsSufficientForProviderUse(
1876 allowedResolutionLevel,
1877 LocationManager.GPS_PROVIDER);
1878
1879 int uid = Binder.getCallingUid();
1880 long identity = Binder.clearCallingIdentity();
1881 boolean hasLocationAccess;
1882 try {
1883 hasLocationAccess = checkLocationAccess(uid, packageName, allowedResolutionLevel);
1884 } finally {
1885 Binder.restoreCallingIdentity(identity);
1886 }
1887
Wei Liu5241a4c2015-05-11 14:00:36 -07001888 if (!hasLocationAccess || mGpsNavigationMessageProvider == null) {
destradaa4b3e3932014-07-21 18:01:47 -07001889 return false;
1890 }
1891 return mGpsNavigationMessageProvider.addListener(listener);
1892 }
1893
1894 @Override
destradaa6568d702014-10-27 12:47:41 -07001895 public void removeGpsNavigationMessageListener(IGpsNavigationMessageListener listener) {
Wei Liu5241a4c2015-05-11 14:00:36 -07001896 if (mGpsNavigationMessageProvider != null) {
1897 mGpsNavigationMessageProvider.removeListener(listener);
1898 }
destradaa4b3e3932014-07-21 18:01:47 -07001899 }
1900
1901 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001903 if (provider == null) {
1904 // throw NullPointerException to remain compatible with previous implementation
1905 throw new NullPointerException();
1906 }
Victoria Lease37425c32012-10-16 16:08:48 -07001907 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1908 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001909
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001911 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001912 != PackageManager.PERMISSION_GRANTED)) {
1913 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1914 }
1915
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001916 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001917 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001918 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001919
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001920 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001921 }
1922 }
1923
Nick Pellye0fd6932012-07-11 10:26:13 -07001924 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001925 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001926 if (Binder.getCallingUid() != Process.myUid()) {
1927 throw new SecurityException(
1928 "calling sendNiResponse from outside of the system is not allowed");
1929 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001930 try {
1931 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001932 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001933 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001934 return false;
1935 }
1936 }
1937
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001938 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001939 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001940 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001941 * accessed by the caller
1942 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001943 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001944 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001945 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08001946 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07001947 }
1948
Victoria Lease37425c32012-10-16 16:08:48 -07001949 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1950 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001952 LocationProviderInterface p;
1953 synchronized (mLock) {
1954 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
1956
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001957 if (p == null) return null;
1958 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001959 }
1960
Nick Pellye0fd6932012-07-11 10:26:13 -07001961 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001962 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07001963 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
1964 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001965 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1966
Victoria Lease09eeaec2013-02-05 11:34:13 -08001967 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001968 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001969 try {
1970 synchronized (mLock) {
1971 LocationProviderInterface p = mProvidersByName.get(provider);
1972 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001973
Victoria Lease09eeaec2013-02-05 11:34:13 -08001974 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001975 }
1976 } finally {
1977 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001978 }
1979 }
1980
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001981 /**
1982 * Returns "true" if the UID belongs to a bound location provider.
1983 *
1984 * @param uid the uid
1985 * @return true if uid belongs to a bound location provider
1986 */
1987 private boolean isUidALocationProvider(int uid) {
1988 if (uid == Process.SYSTEM_UID) {
1989 return true;
1990 }
1991 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07001992 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001993 }
1994 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07001995 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001996 }
1997 return false;
1998 }
1999
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002000 private void checkCallerIsProvider() {
2001 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
2002 == PackageManager.PERMISSION_GRANTED) {
2003 return;
2004 }
2005
2006 // Previously we only used the INSTALL_LOCATION_PROVIDER
2007 // check. But that is system or signature
2008 // protection level which is not flexible enough for
2009 // providers installed oustide the system image. So
2010 // also allow providers with a UID matching the
2011 // currently bound package name
2012
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002013 if (isUidALocationProvider(Binder.getCallingUid())) {
2014 return;
2015 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002016
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002017 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2018 "or UID of a currently bound location provider");
2019 }
2020
David Christie1f141c12014-05-14 15:11:15 -07002021 /**
2022 * Returns true if the given package belongs to the given uid.
2023 */
2024 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002025 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002026 return false;
2027 }
David Christie1f141c12014-05-14 15:11:15 -07002028 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2029 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002030 return false;
2031 }
David Christie1f141c12014-05-14 15:11:15 -07002032 for (String name : packageNames) {
2033 if (packageName.equals(name)) {
2034 return true;
2035 }
2036 }
2037 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002038 }
2039
Nick Pellye0fd6932012-07-11 10:26:13 -07002040 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002041 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002042 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002043
Nick Pelly2eeeec22012-07-18 13:13:37 -07002044 if (!location.isComplete()) {
2045 Log.w(TAG, "Dropping incomplete location: " + location);
2046 return;
2047 }
2048
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002049 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2050 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002051 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002052 mLocationHandler.sendMessageAtFrontOfQueue(m);
2053 }
2054
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002055
Laurent Tu75defb62012-11-01 16:21:52 -07002056 private static boolean shouldBroadcastSafe(
2057 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002058 // Always broadcast the first update
2059 if (lastLoc == null) {
2060 return true;
2061 }
2062
Nick Pellyf1be6862012-05-15 10:53:42 -07002063 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002064 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002065 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2066 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002067 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002068 return false;
2069 }
2070
2071 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002072 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002073 if (minDistance > 0.0) {
2074 if (loc.distanceTo(lastLoc) <= minDistance) {
2075 return false;
2076 }
2077 }
2078
Laurent Tu75defb62012-11-01 16:21:52 -07002079 // Check whether sufficient number of udpates is left
2080 if (record.mRequest.getNumUpdates() <= 0) {
2081 return false;
2082 }
2083
2084 // Check whether the expiry date has passed
2085 if (record.mRequest.getExpireAt() < now) {
2086 return false;
2087 }
2088
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002089 return true;
2090 }
2091
Mike Lockwooda4903f22010-02-17 06:42:23 -05002092 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002093 if (D) Log.d(TAG, "incoming location: " + location);
2094
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002095 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002096 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002097
Laurent Tu60ec50a2012-10-04 17:00:10 -07002098 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002099 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002100 if (p == null) return;
2101
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002102 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002103 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2104 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002105 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002106 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002107 lastLocation = new Location(provider);
2108 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002109 } else {
2110 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2111 if (noGPSLocation == null && lastNoGPSLocation != null) {
2112 // New location has no no-GPS location: adopt last no-GPS location. This is set
2113 // directly into location because we do not want to notify COARSE clients.
2114 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2115 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002116 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002117 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002118
David Christie1b9b7b12013-04-15 15:31:11 -07002119 // Update last known coarse interval location if enough time has passed.
2120 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2121 if (lastLocationCoarseInterval == null) {
2122 lastLocationCoarseInterval = new Location(location);
2123 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2124 }
2125 long timeDiffNanos = location.getElapsedRealtimeNanos()
2126 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2127 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2128 lastLocationCoarseInterval.set(location);
2129 }
2130 // Don't ever return a coarse location that is more recent than the allowed update
2131 // interval (i.e. don't allow an app to keep registering and unregistering for
2132 // location updates to overcome the minimum interval).
2133 noGPSLocation =
2134 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2135
Laurent Tu60ec50a2012-10-04 17:00:10 -07002136 // Skip if there are no UpdateRecords for this provider.
2137 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2138 if (records == null || records.size() == 0) return;
2139
Victoria Lease09016ab2012-09-16 12:33:15 -07002140 // Fetch coarse location
2141 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002142 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002143 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2144 }
2145
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002146 // Fetch latest status update time
2147 long newStatusUpdateTime = p.getStatusUpdateTime();
2148
David Christie2ff96af2014-01-30 16:09:37 -08002149 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002150 Bundle extras = new Bundle();
2151 int status = p.getStatus(extras);
2152
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002153 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002154 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002155
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002156 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002157 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002158 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002159 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002160
Victoria Lease269518e2012-10-29 08:25:39 -07002161 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002162 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002163 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002164 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002165 " (current user: " + mCurrentUserId + ", app: " +
2166 receiver.mPackageName + ")");
2167 }
2168 continue;
2169 }
2170
Nick Pelly4035f5a2012-08-17 14:43:49 -07002171 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2172 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2173 receiver.mPackageName);
2174 continue;
2175 }
2176
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002177 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
2178 receiver.mAllowedResolutionLevel)) {
2179 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2180 receiver.mPackageName);
2181 continue;
2182 }
2183
Victoria Lease09016ab2012-09-16 12:33:15 -07002184 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07002185 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2186 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002187 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002188 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002189 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002190 if (notifyLocation != null) {
2191 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002192 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002193 if (lastLoc == null) {
2194 lastLoc = new Location(notifyLocation);
2195 r.mLastFixBroadcast = lastLoc;
2196 } else {
2197 lastLoc.set(notifyLocation);
2198 }
2199 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2200 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2201 receiverDead = true;
2202 }
Laurent Tu75defb62012-11-01 16:21:52 -07002203 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
2205 }
2206
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002207 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002208 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002209 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002210
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002211 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002212 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002213 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002214 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002215 }
2216 }
2217
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002218 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002219 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002220 if (deadUpdateRecords == null) {
2221 deadUpdateRecords = new ArrayList<UpdateRecord>();
2222 }
2223 deadUpdateRecords.add(r);
2224 }
2225 // track dead receivers
2226 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002227 if (deadReceivers == null) {
2228 deadReceivers = new ArrayList<Receiver>();
2229 }
2230 if (!deadReceivers.contains(receiver)) {
2231 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002232 }
2233 }
2234 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002235
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002236 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002238 for (Receiver receiver : deadReceivers) {
2239 removeUpdatesLocked(receiver);
2240 }
2241 }
2242 if (deadUpdateRecords != null) {
2243 for (UpdateRecord r : deadUpdateRecords) {
2244 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002245 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002246 applyRequirementsLocked(provider);
2247 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002248 }
2249
2250 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002251 public LocationWorkerHandler(Looper looper) {
2252 super(looper, null, true);
2253 }
2254
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002255 @Override
2256 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002257 switch (msg.what) {
2258 case MSG_LOCATION_CHANGED:
2259 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2260 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002261 }
2262 }
2263 }
2264
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002265 private boolean isMockProvider(String provider) {
2266 synchronized (mLock) {
2267 return mMockProviders.containsKey(provider);
2268 }
2269 }
2270
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002271 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002272 // create a working copy of the incoming Location so that the service can modify it without
2273 // disturbing the caller's copy
2274 Location myLocation = new Location(location);
2275 String provider = myLocation.getProvider();
2276
2277 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2278 // bit if location did not come from a mock provider because passive/fused providers can
2279 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2280 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2281 myLocation.setIsFromMockProvider(true);
2282 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002283
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002284 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002285 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2286 if (!passive) {
2287 // notify passive provider of the new location
2288 mPassiveProvider.updateLocation(myLocation);
2289 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002290 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002291 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002292 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002294
Mike Lockwoode97ae402010-09-29 15:23:46 -04002295 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2296 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002297 public void onPackageDisappeared(String packageName, int reason) {
2298 // remove all receivers associated with this package name
2299 synchronized (mLock) {
2300 ArrayList<Receiver> deadReceivers = null;
2301
2302 for (Receiver receiver : mReceivers.values()) {
2303 if (receiver.mPackageName.equals(packageName)) {
2304 if (deadReceivers == null) {
2305 deadReceivers = new ArrayList<Receiver>();
2306 }
2307 deadReceivers.add(receiver);
2308 }
2309 }
2310
2311 // perform removal outside of mReceivers loop
2312 if (deadReceivers != null) {
2313 for (Receiver receiver : deadReceivers) {
2314 removeUpdatesLocked(receiver);
2315 }
2316 }
2317 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002318 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002319 };
2320
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002321 // Geocoder
2322
Nick Pellye0fd6932012-07-11 10:26:13 -07002323 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002324 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002325 return mGeocodeProvider != null;
2326 }
2327
Nick Pellye0fd6932012-07-11 10:26:13 -07002328 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002330 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002331 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002332 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2333 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002334 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002335 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002336 }
2337
Mike Lockwooda55c3212009-04-15 11:10:11 -04002338
Nick Pellye0fd6932012-07-11 10:26:13 -07002339 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002341 double lowerLeftLatitude, double lowerLeftLongitude,
2342 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002343 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002344
2345 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002346 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2347 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2348 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002349 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002350 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002351 }
2352
2353 // Mock Providers
2354
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002355 private boolean canCallerAccessMockLocation(String opPackageName) {
2356 return mAppOps.noteOp(AppOpsManager.OP_MOCK_LOCATION, Binder.getCallingUid(),
2357 opPackageName) == AppOpsManager.MODE_ALLOWED;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002358 }
2359
Nick Pellye0fd6932012-07-11 10:26:13 -07002360 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002361 public void addTestProvider(String name, ProviderProperties properties, String opPackageName) {
2362 if (!canCallerAccessMockLocation(opPackageName)) {
2363 return;
2364 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002365
Mike Lockwooda4903f22010-02-17 06:42:23 -05002366 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2367 throw new IllegalArgumentException("Cannot mock the passive location provider");
2368 }
2369
Mike Lockwood86328a92009-10-23 08:38:25 -04002370 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002371 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002372 // remove the real provider if we are replacing GPS or network provider
2373 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002374 || LocationManager.NETWORK_PROVIDER.equals(name)
2375 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002376 LocationProviderInterface p = mProvidersByName.get(name);
2377 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002378 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002379 }
2380 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002381 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002382 updateProvidersLocked();
2383 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002384 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002385 }
2386
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002387 private void addTestProviderLocked(String name, ProviderProperties properties) {
2388 if (mProvidersByName.get(name) != null) {
2389 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2390 }
2391 MockProvider provider = new MockProvider(name, this, properties);
2392 addProviderLocked(provider);
2393 mMockProviders.put(name, provider);
2394 mLastLocation.put(name, null);
2395 mLastLocationCoarseInterval.put(name, null);
2396 }
2397
Nick Pellye0fd6932012-07-11 10:26:13 -07002398 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002399 public void removeTestProvider(String provider, String opPackageName) {
2400 if (!canCallerAccessMockLocation(opPackageName)) {
2401 return;
2402 }
2403
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002404 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002405
2406 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002407 // we don't leave anything dangling.
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002408 clearTestProviderEnabled(provider, opPackageName);
2409 clearTestProviderLocation(provider, opPackageName);
2410 clearTestProviderStatus(provider, opPackageName);
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002411
You Kima6d0b6f2012-10-28 03:58:44 +09002412 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002413 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002414 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2415 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002416 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002417 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002418
2419 // reinstate real provider if available
2420 LocationProviderInterface realProvider = mRealProviders.get(provider);
2421 if (realProvider != null) {
2422 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002423 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002424 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002425 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002426 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002427 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002428 }
2429 }
2430
Nick Pellye0fd6932012-07-11 10:26:13 -07002431 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002432 public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
2433 if (!canCallerAccessMockLocation(opPackageName)) {
2434 return;
2435 }
2436
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002437 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002438 MockProvider mockProvider = mMockProviders.get(provider);
2439 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002440 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2441 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002442 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2443 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002444 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002445 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002446 }
2447 }
2448
Nick Pellye0fd6932012-07-11 10:26:13 -07002449 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002450 public void clearTestProviderLocation(String provider, String opPackageName) {
2451 if (!canCallerAccessMockLocation(opPackageName)) {
2452 return;
2453 }
2454
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002455 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002456 MockProvider mockProvider = mMockProviders.get(provider);
2457 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002458 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2459 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002460 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 }
2462 }
2463
Nick Pellye0fd6932012-07-11 10:26:13 -07002464 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002465 public void setTestProviderEnabled(String provider, boolean enabled, String opPackageName) {
2466 if (!canCallerAccessMockLocation(opPackageName)) {
2467 return;
2468 }
2469
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002470 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002471 MockProvider mockProvider = mMockProviders.get(provider);
2472 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002473 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2474 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002475 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002476 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002477 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002478 mEnabledProviders.add(provider);
2479 mDisabledProviders.remove(provider);
2480 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002481 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 mEnabledProviders.remove(provider);
2483 mDisabledProviders.add(provider);
2484 }
2485 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002486 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002487 }
2488 }
2489
Nick Pellye0fd6932012-07-11 10:26:13 -07002490 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002491 public void clearTestProviderEnabled(String provider, String opPackageName) {
2492 if (!canCallerAccessMockLocation(opPackageName)) {
2493 return;
2494 }
2495
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002496 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002497 MockProvider mockProvider = mMockProviders.get(provider);
2498 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002499 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2500 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002501 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 mEnabledProviders.remove(provider);
2503 mDisabledProviders.remove(provider);
2504 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002505 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002506 }
2507 }
2508
Nick Pellye0fd6932012-07-11 10:26:13 -07002509 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002510 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime,
2511 String opPackageName) {
2512 if (!canCallerAccessMockLocation(opPackageName)) {
2513 return;
2514 }
2515
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002516 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002517 MockProvider mockProvider = mMockProviders.get(provider);
2518 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002519 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2520 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002521 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002522 }
2523 }
2524
Nick Pellye0fd6932012-07-11 10:26:13 -07002525 @Override
Svet Ganovf7e9cf42015-05-13 10:40:31 -07002526 public void clearTestProviderStatus(String provider, String opPackageName) {
2527 if (!canCallerAccessMockLocation(opPackageName)) {
2528 return;
2529 }
2530
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002531 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002532 MockProvider mockProvider = mMockProviders.get(provider);
2533 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2535 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002536 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002537 }
2538 }
2539
2540 private void log(String log) {
2541 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002542 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002543 }
2544 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002545
2546 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002547 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2548 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2549 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002550 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002551 + Binder.getCallingPid()
2552 + ", uid=" + Binder.getCallingUid());
2553 return;
2554 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002555
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002556 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002558 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002559 for (Receiver receiver : mReceivers.values()) {
2560 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002561 }
David Christie2ff96af2014-01-30 16:09:37 -08002562 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002563 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2564 pw.println(" " + entry.getKey() + ":");
2565 for (UpdateRecord record : entry.getValue()) {
2566 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002567 }
2568 }
David Christie2ff96af2014-01-30 16:09:37 -08002569 pw.println(" Historical Records by Provider:");
2570 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2571 : mRequestStatistics.statistics.entrySet()) {
2572 PackageProviderKey key = entry.getKey();
2573 PackageStatistics stats = entry.getValue();
2574 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2575 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002576 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002577 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2578 String provider = entry.getKey();
2579 Location location = entry.getValue();
2580 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002581 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002582
David Christie1b9b7b12013-04-15 15:31:11 -07002583 pw.println(" Last Known Locations Coarse Intervals:");
2584 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2585 String provider = entry.getKey();
2586 Location location = entry.getValue();
2587 pw.println(" " + provider + ": " + location);
2588 }
2589
Nick Pellye0fd6932012-07-11 10:26:13 -07002590 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002592 if (mEnabledProviders.size() > 0) {
2593 pw.println(" Enabled Providers:");
2594 for (String i : mEnabledProviders) {
2595 pw.println(" " + i);
2596 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002598 }
2599 if (mDisabledProviders.size() > 0) {
2600 pw.println(" Disabled Providers:");
2601 for (String i : mDisabledProviders) {
2602 pw.println(" " + i);
2603 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002604 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002605 pw.append(" ");
2606 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002607 if (mMockProviders.size() > 0) {
2608 pw.println(" Mock Providers:");
2609 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002610 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002611 }
2612 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002613
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002614 pw.append(" fudger: ");
2615 mLocationFudger.dump(fd, pw, args);
2616
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002617 if (args.length > 0 && "short".equals(args[0])) {
2618 return;
2619 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002620 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002621 pw.print(provider.getName() + " Internal State");
2622 if (provider instanceof LocationProviderProxy) {
2623 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2624 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002625 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002626 pw.println(":");
2627 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630 }
2631}