blob: 132aa55df28667763713b74648fd62282d50f14f [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;
destradaaea8a8a62014-06-23 18:19:03 -070063import android.location.IGpsMeasurementsListener;
destradaa4b3e3932014-07-21 18:01:47 -070064import android.location.IGpsNavigationMessageListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.location.IGpsStatusListener;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -040066import android.location.IGpsStatusProvider;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.location.ILocationListener;
68import android.location.ILocationManager;
Danke Xie22d1f9f2009-08-18 18:28:45 -040069import android.location.INetInitiatedListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.location.Location;
71import android.location.LocationManager;
72import android.location.LocationProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070073import android.location.LocationRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Binder;
75import android.os.Bundle;
76import android.os.Handler;
77import android.os.IBinder;
Mike Lockwood3d12b512009-04-21 23:25:35 -070078import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Message;
80import android.os.PowerManager;
Mike Lockwoode932f7f2009-04-06 10:51:26 -070081import android.os.Process;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.RemoteException;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070083import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070084import android.os.UserHandle;
Amith Yamasanib27528d2014-06-05 15:02:10 -070085import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070086import android.os.WorkSource;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080089import android.util.Slog;
Amith Yamasanib27528d2014-06-05 15:02:10 -070090
Mike Lockwood43e33f22010-03-26 10:41:48 -040091import java.io.FileDescriptor;
92import java.io.PrintWriter;
93import java.util.ArrayList;
Nick Pelly6fa9ad42012-07-16 12:18:23 -070094import java.util.Arrays;
Mike Lockwood43e33f22010-03-26 10:41:48 -040095import java.util.HashMap;
96import java.util.HashSet;
97import java.util.List;
98import java.util.Map;
Mike Lockwood43e33f22010-03-26 10:41:48 -040099import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
101/**
102 * The service class that manages LocationProviders and issues location
103 * updates and alerts.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104 */
Victoria Lease5cd731a2012-12-19 15:04:21 -0800105public class LocationManagerService extends ILocationManager.Stub {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106 private static final String TAG = "LocationManagerService";
JP Abgrallf79811e72013-02-01 18:45:05 -0800107 public static final boolean D = Log.isLoggable(TAG, Log.DEBUG);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700108
109 private static final String WAKELOCK_KEY = TAG;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110
Victoria Lease37425c32012-10-16 16:08:48 -0700111 // Location resolution level: no location data whatsoever
112 private static final int RESOLUTION_LEVEL_NONE = 0;
113 // Location resolution level: coarse location data only
114 private static final int RESOLUTION_LEVEL_COARSE = 1;
115 // Location resolution level: fine location data
116 private static final int RESOLUTION_LEVEL_FINE = 2;
117
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String ACCESS_MOCK_LOCATION =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700119 android.Manifest.permission.ACCESS_MOCK_LOCATION;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120 private static final String ACCESS_LOCATION_EXTRA_COMMANDS =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700121 android.Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS;
Mike Lockwood275555c2009-05-01 11:30:34 -0400122 private static final String INSTALL_LOCATION_PROVIDER =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700123 android.Manifest.permission.INSTALL_LOCATION_PROVIDER;
124
125 private static final String NETWORK_LOCATION_SERVICE_ACTION =
Stan Chesnutt39062dd2013-07-22 14:33:30 -0700126 "com.android.location.service.v3.NetworkLocationProvider";
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700127 private static final String FUSED_LOCATION_SERVICE_ACTION =
128 "com.android.location.service.FusedLocationProvider";
129
130 private static final int MSG_LOCATION_CHANGED = 1;
131
David Christie1b9b7b12013-04-15 15:31:11 -0700132 private static final long NANOS_PER_MILLI = 1000000L;
133
David Christie0b837452013-07-29 16:02:13 -0700134 // The maximum interval a location request can have and still be considered "high power".
135 private static final long HIGH_POWER_INTERVAL_MS = 5 * 60 * 1000;
136
Nick Pellyf1be6862012-05-15 10:53:42 -0700137 // Location Providers may sometimes deliver location updates
138 // slightly faster that requested - provide grace period so
139 // we don't unnecessarily filter events that are otherwise on
140 // time
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700141 private static final int MAX_PROVIDER_SCHEDULING_JITTER_MS = 100;
Nick Pellyf1be6862012-05-15 10:53:42 -0700142
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700143 private static final LocationRequest DEFAULT_LOCATION_REQUEST = new LocationRequest();
144
145 private final Context mContext;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800146 private final AppOpsManager mAppOps;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700147
148 // used internally for synchronization
149 private final Object mLock = new Object();
150
Victoria Lease5cd731a2012-12-19 15:04:21 -0800151 // --- fields below are final after systemReady() ---
Nick Pelly74fa7ea2012-08-13 19:36:38 -0700152 private LocationFudger mLocationFudger;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700153 private GeofenceManager mGeofenceManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700154 private PackageManager mPackageManager;
Victoria Lease0aa28602013-05-29 15:28:26 -0700155 private PowerManager mPowerManager;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700156 private UserManager mUserManager;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700157 private GeocoderProxy mGeocodeProvider;
158 private IGpsStatusProvider mGpsStatusProvider;
159 private INetInitiatedListener mNetInitiatedListener;
160 private LocationWorkerHandler mLocationHandler;
Nick Pelly4035f5a2012-08-17 14:43:49 -0700161 private PassiveProvider mPassiveProvider; // track passive provider for special cases
162 private LocationBlacklist mBlacklist;
destradaaea8a8a62014-06-23 18:19:03 -0700163 private GpsMeasurementsProvider mGpsMeasurementsProvider;
destradaa4b3e3932014-07-21 18:01:47 -0700164 private GpsNavigationMessageProvider mGpsNavigationMessageProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700165
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700166 // --- fields below are protected by mLock ---
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 // Set of providers that are explicitly enabled
168 private final Set<String> mEnabledProviders = new HashSet<String>();
169
170 // Set of providers that are explicitly disabled
171 private final Set<String> mDisabledProviders = new HashSet<String>();
172
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700173 // Mock (test) providers
174 private final HashMap<String, MockProvider> mMockProviders =
175 new HashMap<String, MockProvider>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700177 // all receivers
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400178 private final HashMap<Object, Receiver> mReceivers = new HashMap<Object, Receiver>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700180 // currently installed providers (with mocks replacing real providers)
Mike Lockwoodd03ff942010-02-09 08:46:14 -0500181 private final ArrayList<LocationProviderInterface> mProviders =
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700182 new ArrayList<LocationProviderInterface>();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400183
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700184 // real providers, saved here when mocked out
185 private final HashMap<String, LocationProviderInterface> mRealProviders =
186 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700188 // mapping from provider name to provider
189 private final HashMap<String, LocationProviderInterface> mProvidersByName =
190 new HashMap<String, LocationProviderInterface>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700192 // mapping from provider name to all its UpdateRecords
193 private final HashMap<String, ArrayList<UpdateRecord>> mRecordsByProvider =
194 new HashMap<String, ArrayList<UpdateRecord>>();
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700195
David Christie2ff96af2014-01-30 16:09:37 -0800196 private final LocationRequestStatistics mRequestStatistics = new LocationRequestStatistics();
197
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700198 // mapping from provider name to last known location
199 private final HashMap<String, Location> mLastLocation = new HashMap<String, Location>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
David Christie1b9b7b12013-04-15 15:31:11 -0700201 // same as mLastLocation, but is not updated faster than LocationFudger.FASTEST_INTERVAL_MS.
202 // locations stored here are not fudged for coarse permissions.
203 private final HashMap<String, Location> mLastLocationCoarseInterval =
204 new HashMap<String, Location>();
205
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700206 // all providers that operate over proxy, for authorizing incoming location
207 private final ArrayList<LocationProviderProxy> mProxyProviders =
208 new ArrayList<LocationProviderProxy>();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Victoria Lease38389b62012-09-30 11:44:22 -0700210 // current active user on the device - other users are denied location data
211 private int mCurrentUserId = UserHandle.USER_OWNER;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700212 private int[] mCurrentUserProfiles = new int[] { UserHandle.USER_OWNER };
Victoria Lease38389b62012-09-30 11:44:22 -0700213
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700214 public LocationManagerService(Context context) {
215 super();
216 mContext = context;
Dianne Hackborna06de0f2012-12-11 16:34:47 -0800217 mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
The Android Open Source Project4df24232009-03-05 14:34:35 -0800218
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700219 if (D) Log.d(TAG, "Constructed");
220
221 // most startup is deferred until systemReady()
222 }
223
Svetoslav Ganova0027152013-06-25 14:59:53 -0700224 public void systemRunning() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700225 synchronized (mLock) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800226 if (D) Log.d(TAG, "systemReady()");
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700227
Victoria Lease5cd731a2012-12-19 15:04:21 -0800228 // fetch package manager
229 mPackageManager = mContext.getPackageManager();
230
Victoria Lease0aa28602013-05-29 15:28:26 -0700231 // fetch power manager
232 mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Victoria Lease5cd731a2012-12-19 15:04:21 -0800233
234 // prepare worker thread
Dianne Hackborn8d044e82013-04-30 17:24:15 -0700235 mLocationHandler = new LocationWorkerHandler(BackgroundThread.get().getLooper());
Victoria Lease5cd731a2012-12-19 15:04:21 -0800236
237 // prepare mLocationHandler's dependents
238 mLocationFudger = new LocationFudger(mContext, mLocationHandler);
239 mBlacklist = new LocationBlacklist(mContext, mLocationHandler);
240 mBlacklist.init();
241 mGeofenceManager = new GeofenceManager(mContext, mBlacklist);
242
Dianne Hackbornc2293022013-02-06 23:14:49 -0800243 // Monitor for app ops mode changes.
Dianne Hackborn9bb0ee92013-09-22 12:31:38 -0700244 AppOpsManager.OnOpChangedListener callback
245 = new AppOpsManager.OnOpChangedInternalListener() {
246 public void onOpChanged(int op, String packageName) {
Dianne Hackbornc2293022013-02-06 23:14:49 -0800247 synchronized (mLock) {
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700248 for (Receiver receiver : mReceivers.values()) {
249 receiver.updateMonitoring(true);
250 }
Dianne Hackbornc2293022013-02-06 23:14:49 -0800251 applyAllProviderRequirementsLocked();
252 }
253 }
254 };
255 mAppOps.startWatchingMode(AppOpsManager.OP_COARSE_LOCATION, null, callback);
256
Amith Yamasanib27528d2014-06-05 15:02:10 -0700257 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
258 updateUserProfiles(mCurrentUserId);
259
Victoria Lease5cd731a2012-12-19 15:04:21 -0800260 // prepare providers
261 loadProvidersLocked();
262 updateProvidersLocked();
263 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700264
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700265 // listen for settings changes
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700266 mContext.getContentResolver().registerContentObserver(
Laurent Tu75defb62012-11-01 16:21:52 -0700267 Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true,
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700268 new ContentObserver(mLocationHandler) {
Victoria Lease5cd731a2012-12-19 15:04:21 -0800269 @Override
270 public void onChange(boolean selfChange) {
271 synchronized (mLock) {
272 updateProvidersLocked();
273 }
274 }
275 }, UserHandle.USER_ALL);
276 mPackageMonitor.register(mContext, mLocationHandler.getLooper(), true);
Brian Muramatsubb95cb92012-08-29 10:43:21 -0700277
Victoria Lease38389b62012-09-30 11:44:22 -0700278 // listen for user change
279 IntentFilter intentFilter = new IntentFilter();
280 intentFilter.addAction(Intent.ACTION_USER_SWITCHED);
Amith Yamasanib27528d2014-06-05 15:02:10 -0700281 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
282 intentFilter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
Victoria Lease38389b62012-09-30 11:44:22 -0700283
284 mContext.registerReceiverAsUser(new BroadcastReceiver() {
285 @Override
286 public void onReceive(Context context, Intent intent) {
287 String action = intent.getAction();
288 if (Intent.ACTION_USER_SWITCHED.equals(action)) {
289 switchUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE, 0));
Amith Yamasanib27528d2014-06-05 15:02:10 -0700290 } else if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action)
291 || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) {
292 updateUserProfiles(mCurrentUserId);
Victoria Lease38389b62012-09-30 11:44:22 -0700293 }
294 }
Victoria Lease5cd731a2012-12-19 15:04:21 -0800295 }, UserHandle.ALL, intentFilter, null, mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700296 }
297
Amith Yamasanib27528d2014-06-05 15:02:10 -0700298 /**
299 * Makes a list of userids that are related to the current user. This is
300 * relevant when using managed profiles. Otherwise the list only contains
301 * the current user.
302 *
303 * @param currentUserId the current user, who might have an alter-ego.
304 */
305 void updateUserProfiles(int currentUserId) {
306 List<UserInfo> profiles = mUserManager.getProfiles(currentUserId);
307 synchronized (mLock) {
308 mCurrentUserProfiles = new int[profiles.size()];
309 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
310 mCurrentUserProfiles[i] = profiles.get(i).id;
311 }
312 }
313 }
314
315 /**
316 * Checks if the specified userId matches any of the current foreground
317 * users stored in mCurrentUserProfiles.
318 */
319 private boolean isCurrentProfile(int userId) {
320 synchronized (mLock) {
321 for (int i = 0; i < mCurrentUserProfiles.length; i++) {
322 if (mCurrentUserProfiles[i] == userId) {
323 return true;
324 }
325 }
326 return false;
327 }
328 }
329
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500330 private void ensureFallbackFusedProviderPresentLocked(ArrayList<String> pkgs) {
331 PackageManager pm = mContext.getPackageManager();
332 String systemPackageName = mContext.getPackageName();
333 ArrayList<HashSet<Signature>> sigSets = ServiceWatcher.getSignatureSets(mContext, pkgs);
334
335 List<ResolveInfo> rInfos = pm.queryIntentServicesAsUser(
336 new Intent(FUSED_LOCATION_SERVICE_ACTION),
337 PackageManager.GET_META_DATA, mCurrentUserId);
338 for (ResolveInfo rInfo : rInfos) {
339 String packageName = rInfo.serviceInfo.packageName;
340
341 // Check that the signature is in the list of supported sigs. If it's not in
342 // this list the standard provider binding logic won't bind to it.
343 try {
344 PackageInfo pInfo;
345 pInfo = pm.getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
346 if (!ServiceWatcher.isSignatureMatch(pInfo.signatures, sigSets)) {
347 Log.w(TAG, packageName + " resolves service " + FUSED_LOCATION_SERVICE_ACTION +
348 ", but has wrong signature, ignoring");
349 continue;
350 }
351 } catch (NameNotFoundException e) {
352 Log.e(TAG, "missing package: " + packageName);
353 continue;
354 }
355
356 // Get the version info
357 if (rInfo.serviceInfo.metaData == null) {
358 Log.w(TAG, "Found fused provider without metadata: " + packageName);
359 continue;
360 }
361
362 int version = rInfo.serviceInfo.metaData.getInt(
363 ServiceWatcher.EXTRA_SERVICE_VERSION, -1);
364 if (version == 0) {
365 // This should be the fallback fused location provider.
366
367 // Make sure it's in the system partition.
368 if ((rInfo.serviceInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
369 if (D) Log.d(TAG, "Fallback candidate not in /system: " + packageName);
370 continue;
371 }
372
373 // Check that the fallback is signed the same as the OS
374 // as a proxy for coreApp="true"
375 if (pm.checkSignatures(systemPackageName, packageName)
376 != PackageManager.SIGNATURE_MATCH) {
377 if (D) Log.d(TAG, "Fallback candidate not signed the same as system: "
378 + packageName);
379 continue;
380 }
381
382 // Found a valid fallback.
383 if (D) Log.d(TAG, "Found fallback provider: " + packageName);
384 return;
385 } else {
386 if (D) Log.d(TAG, "Fallback candidate not version 0: " + packageName);
387 }
388 }
389
390 throw new IllegalStateException("Unable to find a fused location provider that is in the "
391 + "system partition with version 0 and signed with the platform certificate. "
392 + "Such a package is needed to provide a default fused location provider in the "
393 + "event that no other fused location provider has been installed or is currently "
394 + "available. For example, coreOnly boot mode when decrypting the data "
395 + "partition. The fallback must also be marked coreApp=\"true\" in the manifest");
396 }
397
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700398 private void loadProvidersLocked() {
Victoria Lease5c24fd02012-10-01 11:00:50 -0700399 // create a passive location provider, which is always enabled
400 PassiveProvider passiveProvider = new PassiveProvider(this);
401 addProviderLocked(passiveProvider);
402 mEnabledProviders.add(passiveProvider.getName());
403 mPassiveProvider = passiveProvider;
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700404 // Create a gps location provider
405 GpsLocationProvider gpsProvider = new GpsLocationProvider(mContext, this,
406 mLocationHandler.getLooper());
Victoria Lease5c24fd02012-10-01 11:00:50 -0700407
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700408 if (GpsLocationProvider.isSupported()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700409 mGpsStatusProvider = gpsProvider.getGpsStatusProvider();
410 mNetInitiatedListener = gpsProvider.getNetInitiatedListener();
411 addProviderLocked(gpsProvider);
412 mRealProviders.put(LocationManager.GPS_PROVIDER, gpsProvider);
413 }
destradaaea8a8a62014-06-23 18:19:03 -0700414 mGpsMeasurementsProvider = gpsProvider.getGpsMeasurementsProvider();
destradaa4b3e3932014-07-21 18:01:47 -0700415 mGpsNavigationMessageProvider = gpsProvider.getGpsNavigationMessageProvider();
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700416
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700417 /*
418 Load package name(s) containing location provider support.
419 These packages can contain services implementing location providers:
420 Geocoder Provider, Network Location Provider, and
421 Fused Location Provider. They will each be searched for
422 service components implementing these providers.
423 The location framework also has support for installation
424 of new location providers at run-time. The new package does not
425 have to be explicitly listed here, however it must have a signature
426 that matches the signature of at least one package on this list.
427 */
428 Resources resources = mContext.getResources();
429 ArrayList<String> providerPackageNames = new ArrayList<String>();
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500430 String[] pkgs = resources.getStringArray(
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700431 com.android.internal.R.array.config_locationProviderPackageNames);
Jeff Hamiltonfbadb692012-10-05 14:21:58 -0500432 if (D) Log.d(TAG, "certificates for location providers pulled from: " +
433 Arrays.toString(pkgs));
434 if (pkgs != null) providerPackageNames.addAll(Arrays.asList(pkgs));
435
436 ensureFallbackFusedProviderPresentLocked(providerPackageNames);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700437
438 // bind to network provider
439 LocationProviderProxy networkProvider = LocationProviderProxy.createAndBind(
440 mContext,
441 LocationManager.NETWORK_PROVIDER,
442 NETWORK_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700443 com.android.internal.R.bool.config_enableNetworkLocationOverlay,
444 com.android.internal.R.string.config_networkLocationProviderPackageName,
445 com.android.internal.R.array.config_locationProviderPackageNames,
446 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700447 if (networkProvider != null) {
448 mRealProviders.put(LocationManager.NETWORK_PROVIDER, networkProvider);
449 mProxyProviders.add(networkProvider);
450 addProviderLocked(networkProvider);
451 } else {
452 Slog.w(TAG, "no network location provider found");
453 }
454
455 // bind to fused provider
456 LocationProviderProxy fusedLocationProvider = LocationProviderProxy.createAndBind(
457 mContext,
458 LocationManager.FUSED_PROVIDER,
459 FUSED_LOCATION_SERVICE_ACTION,
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700460 com.android.internal.R.bool.config_enableFusedLocationOverlay,
461 com.android.internal.R.string.config_fusedLocationProviderPackageName,
462 com.android.internal.R.array.config_locationProviderPackageNames,
463 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700464 if (fusedLocationProvider != null) {
465 addProviderLocked(fusedLocationProvider);
466 mProxyProviders.add(fusedLocationProvider);
467 mEnabledProviders.add(fusedLocationProvider.getName());
Kenny Rootc3575182012-10-09 12:44:40 -0700468 mRealProviders.put(LocationManager.FUSED_PROVIDER, fusedLocationProvider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700469 } else {
470 Slog.e(TAG, "no fused location provider found",
471 new IllegalStateException("Location service needs a fused location provider"));
472 }
473
474 // bind to geocoder provider
Zhentao Sunc5fc9982013-04-17 17:47:53 -0700475 mGeocodeProvider = GeocoderProxy.createAndBind(mContext,
476 com.android.internal.R.bool.config_enableGeocoderOverlay,
477 com.android.internal.R.string.config_geocoderProviderPackageName,
478 com.android.internal.R.array.config_locationProviderPackageNames,
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800479 mLocationHandler);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700480 if (mGeocodeProvider == null) {
481 Slog.e(TAG, "no geocoder provider found");
482 }
Jaikumar Ganesh8ce470d2013-04-03 12:22:18 -0700483
destradaaa4fa3b52014-07-09 10:46:39 -0700484 // bind to fused hardware provider if supported
destradaaf9a274c2014-07-25 15:11:56 -0700485 FlpHardwareProvider flpHardwareProvider = FlpHardwareProvider.getInstance(mContext);
destradaa5ce66d82014-05-28 18:24:08 -0700486 if (FlpHardwareProvider.isSupported()) {
destradaaf9a274c2014-07-25 15:11:56 -0700487 FusedProxy fusedProxy = FusedProxy.createAndBind(
488 mContext,
489 mLocationHandler,
490 flpHardwareProvider.getLocationHardware(),
491 com.android.internal.R.bool.config_enableHardwareFlpOverlay,
492 com.android.internal.R.string.config_hardwareFlpPackageName,
493 com.android.internal.R.array.config_locationProviderPackageNames);
494 if (fusedProxy == null) {
495 Slog.e(TAG, "Unable to bind FusedProxy.");
496 }
destradaacfbdcd22014-04-30 11:29:11 -0700497 } else {
destradaaf9a274c2014-07-25 15:11:56 -0700498 Slog.e(TAG, "FLP HAL not supported");
499 }
500
501 // bind to geofence provider
502 GeofenceProxy provider = GeofenceProxy.createAndBind(
503 mContext,com.android.internal.R.bool.config_enableGeofenceOverlay,
504 com.android.internal.R.string.config_geofenceProviderPackageName,
505 com.android.internal.R.array.config_locationProviderPackageNames,
506 mLocationHandler,
507 gpsProvider.getGpsGeofenceProxy(),
508 flpHardwareProvider.getGeofenceHardware());
509 if (provider == null) {
510 Slog.e(TAG, "Unable to bind FLP Geofence proxy.");
destradaa0682809a2013-08-12 18:50:30 -0700511 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900512
destradaaa4fa3b52014-07-09 10:46:39 -0700513 // bind to the hardware activity recognition if supported
514 if (ActivityRecognitionHardware.isSupported()) {
515 ActivityRecognitionProxy proxy = ActivityRecognitionProxy.createAndBind(
516 mContext,
517 mLocationHandler,
518 ActivityRecognitionHardware.getInstance(mContext),
519 com.android.internal.R.bool.config_enableActivityRecognitionHardwareOverlay,
520 com.android.internal.R.string.config_activityRecognitionHardwarePackageName,
521 com.android.internal.R.array.config_locationProviderPackageNames);
522
523 if (proxy == null) {
524 Slog.e(TAG, "Unable to bind ActivityRecognitionProxy.");
525 }
526 } else {
527 Slog.e(TAG, "Hardware Activity-Recognition not supported.");
528 }
529
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +0900530 String[] testProviderStrings = resources.getStringArray(
531 com.android.internal.R.array.config_testLocationProviders);
532 for (String testProviderString : testProviderStrings) {
533 String fragments[] = testProviderString.split(",");
534 String name = fragments[0].trim();
535 if (mProvidersByName.get(name) != null) {
536 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
537 }
538 ProviderProperties properties = new ProviderProperties(
539 Boolean.parseBoolean(fragments[1]) /* requiresNetwork */,
540 Boolean.parseBoolean(fragments[2]) /* requiresSatellite */,
541 Boolean.parseBoolean(fragments[3]) /* requiresCell */,
542 Boolean.parseBoolean(fragments[4]) /* hasMonetaryCost */,
543 Boolean.parseBoolean(fragments[5]) /* supportsAltitude */,
544 Boolean.parseBoolean(fragments[6]) /* supportsSpeed */,
545 Boolean.parseBoolean(fragments[7]) /* supportsBearing */,
546 Integer.parseInt(fragments[8]) /* powerRequirement */,
547 Integer.parseInt(fragments[9]) /* accuracy */);
548 addTestProviderLocked(name, properties);
549 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700550 }
Mike Lockwood9637d472009-04-02 21:41:57 -0700551
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800552 /**
Victoria Lease38389b62012-09-30 11:44:22 -0700553 * Called when the device's active user changes.
554 * @param userId the new active user's UserId
555 */
556 private void switchUser(int userId) {
Jianzheng Zhoud5c69462013-10-10 14:02:09 +0800557 if (mCurrentUserId == userId) {
558 return;
559 }
Victoria Lease83762d22012-10-03 13:51:17 -0700560 mBlacklist.switchUser(userId);
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800561 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED);
Victoria Lease38389b62012-09-30 11:44:22 -0700562 synchronized (mLock) {
Victoria Leaseb711d572012-10-02 13:14:11 -0700563 mLastLocation.clear();
David Christie1b9b7b12013-04-15 15:31:11 -0700564 mLastLocationCoarseInterval.clear();
Victoria Leaseb711d572012-10-02 13:14:11 -0700565 for (LocationProviderInterface p : mProviders) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700566 updateProviderListenersLocked(p.getName(), false);
Victoria Leaseb711d572012-10-02 13:14:11 -0700567 }
Victoria Lease38389b62012-09-30 11:44:22 -0700568 mCurrentUserId = userId;
Amith Yamasanib27528d2014-06-05 15:02:10 -0700569 updateUserProfiles(userId);
Victoria Leaseb711d572012-10-02 13:14:11 -0700570 updateProvidersLocked();
Victoria Lease38389b62012-09-30 11:44:22 -0700571 }
572 }
573
574 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800575 * A wrapper class holding either an ILocationListener or a PendingIntent to receive
576 * location updates.
577 */
Mike Lockwood48f17512009-04-23 09:12:08 -0700578 private final class Receiver implements IBinder.DeathRecipient, PendingIntent.OnFinished {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700579 final int mUid; // uid of receiver
580 final int mPid; // pid of receiver
581 final String mPackageName; // package name of receiver
Victoria Lease37425c32012-10-16 16:08:48 -0700582 final int mAllowedResolutionLevel; // resolution level allowed to receiver
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800584 final ILocationListener mListener;
585 final PendingIntent mPendingIntent;
David Christie82edc9b2013-07-19 11:31:42 -0700586 final WorkSource mWorkSource; // WorkSource for battery blame, or null to assign to caller.
David Christie40e57822013-07-30 11:36:48 -0700587 final boolean mHideFromAppOps; // True if AppOps should not monitor this receiver.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 final Object mKey;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700589
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400590 final HashMap<String,UpdateRecord> mUpdateRecords = new HashMap<String,UpdateRecord>();
Nick Pellyf1be6862012-05-15 10:53:42 -0700591
David Christie0b837452013-07-29 16:02:13 -0700592 // True if app ops has started monitoring this receiver for locations.
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700593 boolean mOpMonitoring;
David Christie0b837452013-07-29 16:02:13 -0700594 // True if app ops has started monitoring this receiver for high power (gps) locations.
595 boolean mOpHighPowerMonitoring;
Mike Lockwood48f17512009-04-23 09:12:08 -0700596 int mPendingBroadcasts;
Victoria Lease0aa28602013-05-29 15:28:26 -0700597 PowerManager.WakeLock mWakeLock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800598
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700599 Receiver(ILocationListener listener, PendingIntent intent, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -0700600 String packageName, WorkSource workSource, boolean hideFromAppOps) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800601 mListener = listener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602 mPendingIntent = intent;
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700603 if (listener != null) {
604 mKey = listener.asBinder();
605 } else {
606 mKey = intent;
607 }
Victoria Lease37425c32012-10-16 16:08:48 -0700608 mAllowedResolutionLevel = getAllowedResolutionLevel(pid, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700609 mUid = uid;
610 mPid = pid;
611 mPackageName = packageName;
David Christie82edc9b2013-07-19 11:31:42 -0700612 if (workSource != null && workSource.size() <= 0) {
613 workSource = null;
614 }
615 mWorkSource = workSource;
David Christie40e57822013-07-30 11:36:48 -0700616 mHideFromAppOps = hideFromAppOps;
Victoria Lease0aa28602013-05-29 15:28:26 -0700617
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700618 updateMonitoring(true);
619
Victoria Lease0aa28602013-05-29 15:28:26 -0700620 // construct/configure wakelock
621 mWakeLock = mPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, WAKELOCK_KEY);
David Christie82edc9b2013-07-19 11:31:42 -0700622 if (workSource == null) {
623 workSource = new WorkSource(mUid, mPackageName);
624 }
625 mWakeLock.setWorkSource(workSource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800626 }
627
628 @Override
629 public boolean equals(Object otherObj) {
630 if (otherObj instanceof Receiver) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700631 return mKey.equals(((Receiver)otherObj).mKey);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800632 }
633 return false;
634 }
635
636 @Override
637 public int hashCode() {
638 return mKey.hashCode();
639 }
Mike Lockwood3681f262009-05-12 10:52:03 -0400640
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800641 @Override
642 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700643 StringBuilder s = new StringBuilder();
644 s.append("Reciever[");
645 s.append(Integer.toHexString(System.identityHashCode(this)));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800646 if (mListener != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700647 s.append(" listener");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800648 } else {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700649 s.append(" intent");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800650 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700651 for (String p : mUpdateRecords.keySet()) {
652 s.append(" ").append(mUpdateRecords.get(p).toString());
653 }
654 s.append("]");
655 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800656 }
657
David Christie15b31912013-08-13 15:54:32 -0700658 /**
659 * Update AppOp monitoring for this receiver.
660 *
661 * @param allow If true receiver is currently active, if false it's been removed.
662 */
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700663 public void updateMonitoring(boolean allow) {
David Christie40e57822013-07-30 11:36:48 -0700664 if (mHideFromAppOps) {
665 return;
666 }
667
David Christie15b31912013-08-13 15:54:32 -0700668 boolean requestingLocation = false;
669 boolean requestingHighPowerLocation = false;
670 if (allow) {
671 // See if receiver has any enabled update records. Also note if any update records
672 // are high power (has a high power provider with an interval under a threshold).
673 for (UpdateRecord updateRecord : mUpdateRecords.values()) {
674 if (isAllowedByCurrentUserSettingsLocked(updateRecord.mProvider)) {
675 requestingLocation = true;
676 LocationProviderInterface locationProvider
David Christie2ff96af2014-01-30 16:09:37 -0800677 = mProvidersByName.get(updateRecord.mProvider);
David Christie15b31912013-08-13 15:54:32 -0700678 ProviderProperties properties = locationProvider != null
679 ? locationProvider.getProperties() : null;
680 if (properties != null
681 && properties.mPowerRequirement == Criteria.POWER_HIGH
682 && updateRecord.mRequest.getInterval() < HIGH_POWER_INTERVAL_MS) {
683 requestingHighPowerLocation = true;
684 break;
685 }
686 }
687 }
688 }
689
David Christie0b837452013-07-29 16:02:13 -0700690 // First update monitoring of any location request (including high power).
David Christie15b31912013-08-13 15:54:32 -0700691 mOpMonitoring = updateMonitoring(
692 requestingLocation,
693 mOpMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700694 AppOpsManager.OP_MONITOR_LOCATION);
695
696 // Now update monitoring of high power requests only.
David Christiec750c1f2013-08-08 12:56:57 -0700697 boolean wasHighPowerMonitoring = mOpHighPowerMonitoring;
David Christie15b31912013-08-13 15:54:32 -0700698 mOpHighPowerMonitoring = updateMonitoring(
699 requestingHighPowerLocation,
700 mOpHighPowerMonitoring,
David Christie0b837452013-07-29 16:02:13 -0700701 AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION);
David Christiec750c1f2013-08-08 12:56:57 -0700702 if (mOpHighPowerMonitoring != wasHighPowerMonitoring) {
David Christie15b31912013-08-13 15:54:32 -0700703 // Send an intent to notify that a high power request has been added/removed.
David Christiec750c1f2013-08-08 12:56:57 -0700704 Intent intent = new Intent(LocationManager.HIGH_POWER_REQUEST_CHANGE_ACTION);
705 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
706 }
David Christie0b837452013-07-29 16:02:13 -0700707 }
708
709 /**
710 * Update AppOps monitoring for a single location request and op type.
711 *
712 * @param allowMonitoring True if monitoring is allowed for this request/op.
713 * @param currentlyMonitoring True if AppOps is currently monitoring this request/op.
714 * @param op AppOps code for the op to update.
715 * @return True if monitoring is on for this request/op after updating.
716 */
717 private boolean updateMonitoring(boolean allowMonitoring, boolean currentlyMonitoring,
718 int op) {
719 if (!currentlyMonitoring) {
720 if (allowMonitoring) {
721 return mAppOps.startOpNoThrow(op, mUid, mPackageName)
722 == AppOpsManager.MODE_ALLOWED;
723 }
724 } else {
725 if (!allowMonitoring || mAppOps.checkOpNoThrow(op, mUid, mPackageName)
726 != AppOpsManager.MODE_ALLOWED) {
727 mAppOps.finishOp(op, mUid, mPackageName);
728 return false;
729 }
730 }
731
732 return currentlyMonitoring;
Dianne Hackborn1304f4a2013-07-09 18:17:27 -0700733 }
734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800735 public boolean isListener() {
736 return mListener != null;
737 }
738
739 public boolean isPendingIntent() {
740 return mPendingIntent != null;
741 }
742
743 public ILocationListener getListener() {
744 if (mListener != null) {
745 return mListener;
746 }
747 throw new IllegalStateException("Request for non-existent listener");
748 }
749
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800750 public boolean callStatusChangedLocked(String provider, int status, Bundle extras) {
751 if (mListener != null) {
752 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700753 synchronized (this) {
754 // synchronize to ensure incrementPendingBroadcastsLocked()
755 // is called before decrementPendingBroadcasts()
756 mListener.onStatusChanged(provider, status, extras);
Nick Pellye0fd6932012-07-11 10:26:13 -0700757 // call this after broadcasting so we do not increment
758 // if we throw an exeption.
759 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700760 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800761 } catch (RemoteException e) {
762 return false;
763 }
764 } else {
765 Intent statusChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800766 statusChanged.putExtras(new Bundle(extras));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800767 statusChanged.putExtra(LocationManager.KEY_STATUS_CHANGED, status);
768 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700769 synchronized (this) {
770 // synchronize to ensure incrementPendingBroadcastsLocked()
771 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700772 mPendingIntent.send(mContext, 0, statusChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700773 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700774 // call this after broadcasting so we do not increment
775 // if we throw an exeption.
776 incrementPendingBroadcastsLocked();
777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800778 } catch (PendingIntent.CanceledException e) {
779 return false;
780 }
781 }
782 return true;
783 }
784
785 public boolean callLocationChangedLocked(Location location) {
786 if (mListener != null) {
787 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700788 synchronized (this) {
789 // synchronize to ensure incrementPendingBroadcastsLocked()
790 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c5406a2012-11-29 16:18:01 -0800791 mListener.onLocationChanged(new Location(location));
Nick Pellye0fd6932012-07-11 10:26:13 -0700792 // call this after broadcasting so we do not increment
793 // if we throw an exeption.
794 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 } catch (RemoteException e) {
797 return false;
798 }
799 } else {
800 Intent locationChanged = new Intent();
Victoria Lease61ecb022012-11-13 15:12:51 -0800801 locationChanged.putExtra(LocationManager.KEY_LOCATION_CHANGED, new Location(location));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800802 try {
Mike Lockwood48f17512009-04-23 09:12:08 -0700803 synchronized (this) {
804 // synchronize to ensure incrementPendingBroadcastsLocked()
805 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700806 mPendingIntent.send(mContext, 0, locationChanged, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700807 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700808 // call this after broadcasting so we do not increment
809 // if we throw an exeption.
810 incrementPendingBroadcastsLocked();
811 }
812 } catch (PendingIntent.CanceledException e) {
813 return false;
814 }
815 }
816 return true;
817 }
818
819 public boolean callProviderEnabledLocked(String provider, boolean enabled) {
David Christie15b31912013-08-13 15:54:32 -0700820 // First update AppOp monitoring.
821 // An app may get/lose location access as providers are enabled/disabled.
822 updateMonitoring(true);
823
Mike Lockwood48f17512009-04-23 09:12:08 -0700824 if (mListener != null) {
825 try {
826 synchronized (this) {
827 // synchronize to ensure incrementPendingBroadcastsLocked()
828 // is called before decrementPendingBroadcasts()
829 if (enabled) {
830 mListener.onProviderEnabled(provider);
831 } else {
832 mListener.onProviderDisabled(provider);
833 }
Nick Pellye0fd6932012-07-11 10:26:13 -0700834 // call this after broadcasting so we do not increment
835 // if we throw an exeption.
836 incrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700837 }
838 } catch (RemoteException e) {
839 return false;
840 }
841 } else {
842 Intent providerIntent = new Intent();
843 providerIntent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, enabled);
844 try {
845 synchronized (this) {
846 // synchronize to ensure incrementPendingBroadcastsLocked()
847 // is called before decrementPendingBroadcasts()
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700848 mPendingIntent.send(mContext, 0, providerIntent, this, mLocationHandler,
Victoria Lease37425c32012-10-16 16:08:48 -0700849 getResolutionPermission(mAllowedResolutionLevel));
Mike Lockwood48f17512009-04-23 09:12:08 -0700850 // call this after broadcasting so we do not increment
851 // if we throw an exeption.
852 incrementPendingBroadcastsLocked();
853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854 } catch (PendingIntent.CanceledException e) {
855 return false;
856 }
857 }
858 return true;
859 }
860
Nick Pellyf1be6862012-05-15 10:53:42 -0700861 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800862 public void binderDied() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700863 if (D) Log.d(TAG, "Location listener died");
864
Mike Lockwood2f82c4e2009-04-17 08:24:10 -0400865 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 removeUpdatesLocked(this);
867 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700868 synchronized (this) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700869 clearPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700870 }
871 }
872
Nick Pellye0fd6932012-07-11 10:26:13 -0700873 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700874 public void onSendFinished(PendingIntent pendingIntent, Intent intent,
875 int resultCode, String resultData, Bundle resultExtras) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400876 synchronized (this) {
877 decrementPendingBroadcastsLocked();
Mike Lockwood48f17512009-04-23 09:12:08 -0700878 }
879 }
880
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400881 // this must be called while synchronized by caller in a synchronized block
882 // containing the sending of the broadcaset
883 private void incrementPendingBroadcastsLocked() {
884 if (mPendingBroadcasts++ == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700885 mWakeLock.acquire();
Mike Lockwood0528b9b2009-05-07 10:12:54 -0400886 }
887 }
888
889 private void decrementPendingBroadcastsLocked() {
890 if (--mPendingBroadcasts == 0) {
Victoria Lease0aa28602013-05-29 15:28:26 -0700891 if (mWakeLock.isHeld()) {
892 mWakeLock.release();
893 }
894 }
895 }
896
897 public void clearPendingBroadcastsLocked() {
898 if (mPendingBroadcasts > 0) {
899 mPendingBroadcasts = 0;
900 if (mWakeLock.isHeld()) {
901 mWakeLock.release();
902 }
Mike Lockwood48f17512009-04-23 09:12:08 -0700903 }
904 }
905 }
906
Nick Pellye0fd6932012-07-11 10:26:13 -0700907 @Override
Mike Lockwood48f17512009-04-23 09:12:08 -0700908 public void locationCallbackFinished(ILocationListener listener) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700909 //Do not use getReceiverLocked here as that will add the ILocationListener to
Joshua Bartel080b61b2009-10-05 12:44:46 -0400910 //the receiver list if it is not found. If it is not found then the
911 //LocationListener was removed when it had a pending broadcast and should
912 //not be added back.
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700913 synchronized (mLock) {
914 IBinder binder = listener.asBinder();
915 Receiver receiver = mReceivers.get(binder);
916 if (receiver != null) {
917 synchronized (receiver) {
918 // so wakelock calls will succeed
919 long identity = Binder.clearCallingIdentity();
920 receiver.decrementPendingBroadcastsLocked();
921 Binder.restoreCallingIdentity(identity);
David Christie2ff96af2014-01-30 16:09:37 -0800922 }
Dianne Hackbornf5fdca92013-06-05 14:53:33 -0700923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 }
925 }
926
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700927 private void addProviderLocked(LocationProviderInterface provider) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400928 mProviders.add(provider);
929 mProvidersByName.put(provider.getName(), provider);
930 }
931
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700932 private void removeProviderLocked(LocationProviderInterface provider) {
933 provider.disable();
Mike Lockwood15e3d0f2009-05-01 07:53:28 -0400934 mProviders.remove(provider);
935 mProvidersByName.remove(provider.getName());
936 }
937
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800938 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800939 * Returns "true" if access to the specified location provider is allowed by the current
940 * user's settings. Access to all location providers is forbidden to non-location-provider
941 * processes belonging to background users.
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800942 *
943 * @param provider the name of the location provider
Victoria Lease03cdd3d2013-02-01 15:15:54 -0800944 * @return
945 */
Victoria Lease09eeaec2013-02-05 11:34:13 -0800946 private boolean isAllowedByCurrentUserSettingsLocked(String provider) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 if (mEnabledProviders.contains(provider)) {
948 return true;
949 }
950 if (mDisabledProviders.contains(provider)) {
951 return false;
952 }
953 // Use system settings
954 ContentResolver resolver = mContext.getContentResolver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955
Victoria Leaseb711d572012-10-02 13:14:11 -0700956 return Settings.Secure.isLocationProviderEnabledForUser(resolver, provider, mCurrentUserId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 }
958
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700959 /**
Victoria Lease09eeaec2013-02-05 11:34:13 -0800960 * Returns "true" if access to the specified location provider is allowed by the specified
961 * user's settings. Access to all location providers is forbidden to non-location-provider
962 * processes belonging to background users.
963 *
964 * @param provider the name of the location provider
965 * @param uid the requestor's UID
966 * @return
967 */
968 private boolean isAllowedByUserSettingsLocked(String provider, int uid) {
Amith Yamasanib27528d2014-06-05 15:02:10 -0700969 if (!isCurrentProfile(UserHandle.getUserId(uid)) && !isUidALocationProvider(uid)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -0800970 return false;
971 }
972 return isAllowedByCurrentUserSettingsLocked(provider);
973 }
974
975 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700976 * Returns the permission string associated with the specified resolution level.
977 *
978 * @param resolutionLevel the resolution level
979 * @return the permission string
Nick Pelly6fa9ad42012-07-16 12:18:23 -0700980 */
Victoria Lease37425c32012-10-16 16:08:48 -0700981 private String getResolutionPermission(int resolutionLevel) {
982 switch (resolutionLevel) {
983 case RESOLUTION_LEVEL_FINE:
984 return android.Manifest.permission.ACCESS_FINE_LOCATION;
985 case RESOLUTION_LEVEL_COARSE:
986 return android.Manifest.permission.ACCESS_COARSE_LOCATION;
987 default:
988 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
Victoria Leaseda479c52012-10-15 15:24:16 -0700990 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700991
Victoria Leaseda479c52012-10-15 15:24:16 -0700992 /**
Victoria Lease37425c32012-10-16 16:08:48 -0700993 * Returns the resolution level allowed to the given PID/UID pair.
994 *
995 * @param pid the PID
996 * @param uid the UID
997 * @return resolution level allowed to the pid/uid pair
Victoria Leaseda479c52012-10-15 15:24:16 -0700998 */
Victoria Lease37425c32012-10-16 16:08:48 -0700999 private int getAllowedResolutionLevel(int pid, int uid) {
1000 if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
1001 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1002 return RESOLUTION_LEVEL_FINE;
1003 } else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
1004 pid, uid) == PackageManager.PERMISSION_GRANTED) {
1005 return RESOLUTION_LEVEL_COARSE;
1006 } else {
1007 return RESOLUTION_LEVEL_NONE;
Victoria Leaseda479c52012-10-15 15:24:16 -07001008 }
Victoria Lease4fab68b2012-09-13 13:20:59 -07001009 }
1010
1011 /**
Victoria Lease37425c32012-10-16 16:08:48 -07001012 * Returns the resolution level allowed to the caller
1013 *
1014 * @return resolution level allowed to caller
Victoria Lease4fab68b2012-09-13 13:20:59 -07001015 */
Victoria Lease37425c32012-10-16 16:08:48 -07001016 private int getCallerAllowedResolutionLevel() {
1017 return getAllowedResolutionLevel(Binder.getCallingPid(), Binder.getCallingUid());
1018 }
1019
1020 /**
1021 * Throw SecurityException if specified resolution level is insufficient to use geofences.
1022 *
1023 * @param allowedResolutionLevel resolution level allowed to caller
1024 */
1025 private void checkResolutionLevelIsSufficientForGeofenceUse(int allowedResolutionLevel) {
1026 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Lease4fab68b2012-09-13 13:20:59 -07001027 throw new SecurityException("Geofence usage requires ACCESS_FINE_LOCATION permission");
1028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001029 }
1030
Victoria Lease37425c32012-10-16 16:08:48 -07001031 /**
1032 * Return the minimum resolution level required to use the specified location provider.
1033 *
1034 * @param provider the name of the location provider
1035 * @return minimum resolution level required for provider
1036 */
1037 private int getMinimumResolutionLevelForProviderUse(String provider) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001038 if (LocationManager.GPS_PROVIDER.equals(provider) ||
1039 LocationManager.PASSIVE_PROVIDER.equals(provider)) {
1040 // gps and passive providers require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001041 return RESOLUTION_LEVEL_FINE;
Victoria Lease8dbb6342012-09-21 16:55:53 -07001042 } else if (LocationManager.NETWORK_PROVIDER.equals(provider) ||
1043 LocationManager.FUSED_PROVIDER.equals(provider)) {
1044 // network and fused providers are ok with COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001045 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001046 } else {
1047 // mock providers
1048 LocationProviderInterface lp = mMockProviders.get(provider);
1049 if (lp != null) {
1050 ProviderProperties properties = lp.getProperties();
1051 if (properties != null) {
1052 if (properties.mRequiresSatellite) {
1053 // provider requiring satellites require FINE permission
Victoria Lease37425c32012-10-16 16:08:48 -07001054 return RESOLUTION_LEVEL_FINE;
Laurent Tu941221c2012-10-04 14:21:52 -07001055 } else if (properties.mRequiresNetwork || properties.mRequiresCell) {
1056 // provider requiring network and or cell require COARSE or FINE
Victoria Lease37425c32012-10-16 16:08:48 -07001057 return RESOLUTION_LEVEL_COARSE;
Laurent Tu941221c2012-10-04 14:21:52 -07001058 }
1059 }
1060 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001061 }
Victoria Lease37425c32012-10-16 16:08:48 -07001062 return RESOLUTION_LEVEL_FINE; // if in doubt, require FINE
Victoria Leaseda479c52012-10-15 15:24:16 -07001063 }
1064
Victoria Lease37425c32012-10-16 16:08:48 -07001065 /**
1066 * Throw SecurityException if specified resolution level is insufficient to use the named
1067 * location provider.
1068 *
1069 * @param allowedResolutionLevel resolution level allowed to caller
1070 * @param providerName the name of the location provider
1071 */
1072 private void checkResolutionLevelIsSufficientForProviderUse(int allowedResolutionLevel,
1073 String providerName) {
1074 int requiredResolutionLevel = getMinimumResolutionLevelForProviderUse(providerName);
1075 if (allowedResolutionLevel < requiredResolutionLevel) {
1076 switch (requiredResolutionLevel) {
1077 case RESOLUTION_LEVEL_FINE:
1078 throw new SecurityException("\"" + providerName + "\" location provider " +
1079 "requires ACCESS_FINE_LOCATION permission.");
1080 case RESOLUTION_LEVEL_COARSE:
1081 throw new SecurityException("\"" + providerName + "\" location provider " +
1082 "requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.");
1083 default:
1084 throw new SecurityException("Insufficient permission for \"" + providerName +
1085 "\" location provider.");
Victoria Leaseda479c52012-10-15 15:24:16 -07001086 }
1087 }
Victoria Lease8dbb6342012-09-21 16:55:53 -07001088 }
1089
David Christie82edc9b2013-07-19 11:31:42 -07001090 /**
1091 * Throw SecurityException if WorkSource use is not allowed (i.e. can't blame other packages
1092 * for battery).
1093 */
David Christie40e57822013-07-30 11:36:48 -07001094 private void checkDeviceStatsAllowed() {
David Christie82edc9b2013-07-19 11:31:42 -07001095 mContext.enforceCallingOrSelfPermission(
1096 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
1097 }
1098
David Christie40e57822013-07-30 11:36:48 -07001099 private void checkUpdateAppOpsAllowed() {
1100 mContext.enforceCallingOrSelfPermission(
1101 android.Manifest.permission.UPDATE_APP_OPS_STATS, null);
1102 }
1103
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001104 public static int resolutionLevelToOp(int allowedResolutionLevel) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001105 if (allowedResolutionLevel != RESOLUTION_LEVEL_NONE) {
1106 if (allowedResolutionLevel == RESOLUTION_LEVEL_COARSE) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001107 return AppOpsManager.OP_COARSE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001108 } else {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001109 return AppOpsManager.OP_FINE_LOCATION;
Dianne Hackborn35654b62013-01-14 17:38:02 -08001110 }
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001111 }
1112 return -1;
1113 }
1114
1115 boolean reportLocationAccessNoThrow(int uid, String packageName, int allowedResolutionLevel) {
1116 int op = resolutionLevelToOp(allowedResolutionLevel);
1117 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001118 if (mAppOps.noteOpNoThrow(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1119 return false;
1120 }
1121 }
1122 return true;
1123 }
1124
1125 boolean checkLocationAccess(int uid, String packageName, int allowedResolutionLevel) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001126 int op = resolutionLevelToOp(allowedResolutionLevel);
1127 if (op >= 0) {
Dianne Hackborn35654b62013-01-14 17:38:02 -08001128 if (mAppOps.checkOp(op, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
1129 return false;
1130 }
1131 }
1132 return true;
1133 }
1134
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001135 /**
1136 * Returns all providers by name, including passive, but excluding
Laurent Tu0d21e212012-10-02 15:33:48 -07001137 * fused, also including ones that are not permitted to
1138 * be accessed by the calling activity or are currently disabled.
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001139 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001140 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 public List<String> getAllProviders() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001142 ArrayList<String> out;
1143 synchronized (mLock) {
1144 out = new ArrayList<String>(mProviders.size());
1145 for (LocationProviderInterface provider : mProviders) {
1146 String name = provider.getName();
1147 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07001148 continue;
1149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 out.add(name);
1151 }
1152 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001153
1154 if (D) Log.d(TAG, "getAllProviders()=" + out);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 return out;
1156 }
1157
Mike Lockwood03ca2162010-04-01 08:10:09 -07001158 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001159 * Return all providers by name, that match criteria and are optionally
1160 * enabled.
1161 * Can return passive provider, but never returns fused provider.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001162 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001163 @Override
1164 public List<String> getProviders(Criteria criteria, boolean enabledOnly) {
Victoria Lease37425c32012-10-16 16:08:48 -07001165 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001166 ArrayList<String> out;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001167 int uid = Binder.getCallingUid();;
Victoria Lease269518e2012-10-29 08:25:39 -07001168 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001169 try {
1170 synchronized (mLock) {
1171 out = new ArrayList<String>(mProviders.size());
1172 for (LocationProviderInterface provider : mProviders) {
1173 String name = provider.getName();
1174 if (LocationManager.FUSED_PROVIDER.equals(name)) {
Victoria Lease8dbb6342012-09-21 16:55:53 -07001175 continue;
1176 }
Victoria Lease37425c32012-10-16 16:08:48 -07001177 if (allowedResolutionLevel >= getMinimumResolutionLevelForProviderUse(name)) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08001178 if (enabledOnly && !isAllowedByUserSettingsLocked(name, uid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001179 continue;
1180 }
1181 if (criteria != null && !LocationProvider.propertiesMeetCriteria(
1182 name, provider.getProperties(), criteria)) {
1183 continue;
1184 }
1185 out.add(name);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001186 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001187 }
Mike Lockwood03ca2162010-04-01 08:10:09 -07001188 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001189 } finally {
1190 Binder.restoreCallingIdentity(identity);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001191 }
1192
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001193 if (D) Log.d(TAG, "getProviders()=" + out);
1194 return out;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001195 }
1196
1197 /**
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001198 * Return the name of the best provider given a Criteria object.
1199 * This method has been deprecated from the public API,
Victoria Lease8dbb6342012-09-21 16:55:53 -07001200 * and the whole LocationProvider (including #meetsCriteria)
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001201 * has been deprecated as well. So this method now uses
1202 * some simplified logic.
Mike Lockwood03ca2162010-04-01 08:10:09 -07001203 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001204 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001205 public String getBestProvider(Criteria criteria, boolean enabledOnly) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001206 String result = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001207
1208 List<String> providers = getProviders(criteria, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001209 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001210 result = pickBest(providers);
1211 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1212 return result;
1213 }
1214 providers = getProviders(null, enabledOnly);
Victoria Lease8dbb6342012-09-21 16:55:53 -07001215 if (!providers.isEmpty()) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001216 result = pickBest(providers);
1217 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
1218 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001219 }
1220
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001221 if (D) Log.d(TAG, "getBestProvider(" + criteria + ", " + enabledOnly + ")=" + result);
Mike Lockwood03ca2162010-04-01 08:10:09 -07001222 return null;
1223 }
1224
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001225 private String pickBest(List<String> providers) {
Victoria Lease1925e292012-09-24 17:00:18 -07001226 if (providers.contains(LocationManager.GPS_PROVIDER)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001227 return LocationManager.GPS_PROVIDER;
Victoria Lease1925e292012-09-24 17:00:18 -07001228 } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
1229 return LocationManager.NETWORK_PROVIDER;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001230 } else {
1231 return providers.get(0);
1232 }
1233 }
1234
Nick Pellye0fd6932012-07-11 10:26:13 -07001235 @Override
Mike Lockwood03ca2162010-04-01 08:10:09 -07001236 public boolean providerMeetsCriteria(String provider, Criteria criteria) {
1237 LocationProviderInterface p = mProvidersByName.get(provider);
1238 if (p == null) {
1239 throw new IllegalArgumentException("provider=" + provider);
1240 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001241
1242 boolean result = LocationProvider.propertiesMeetCriteria(
1243 p.getName(), p.getProperties(), criteria);
1244 if (D) Log.d(TAG, "providerMeetsCriteria(" + provider + ", " + criteria + ")=" + result);
1245 return result;
Mike Lockwood03ca2162010-04-01 08:10:09 -07001246 }
1247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 private void updateProvidersLocked() {
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001249 boolean changesMade = false;
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001250 for (int i = mProviders.size() - 1; i >= 0; i--) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001251 LocationProviderInterface p = mProviders.get(i);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001252 boolean isEnabled = p.isEnabled();
1253 String name = p.getName();
Victoria Lease09eeaec2013-02-05 11:34:13 -08001254 boolean shouldBeEnabled = isAllowedByCurrentUserSettingsLocked(name);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 if (isEnabled && !shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001256 updateProviderListenersLocked(name, false);
David Christieb084fef2013-12-18 14:33:57 -08001257 // If any provider has been disabled, clear all last locations for all providers.
1258 // This is to be on the safe side in case a provider has location derived from
1259 // this disabled provider.
1260 mLastLocation.clear();
1261 mLastLocationCoarseInterval.clear();
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001262 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001263 } else if (!isEnabled && shouldBeEnabled) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001264 updateProviderListenersLocked(name, true);
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001265 changesMade = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
Brad Fitzpatrick0c5a0402010-08-27 14:01:23 -07001267 }
1268 if (changesMade) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001269 mContext.sendBroadcastAsUser(new Intent(LocationManager.PROVIDERS_CHANGED_ACTION),
1270 UserHandle.ALL);
Tom O'Neill40a86c22013-09-03 18:05:13 -07001271 mContext.sendBroadcastAsUser(new Intent(LocationManager.MODE_CHANGED_ACTION),
1272 UserHandle.ALL);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
1274 }
1275
Amith Yamasanib27528d2014-06-05 15:02:10 -07001276 private void updateProviderListenersLocked(String provider, boolean enabled) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001277 int listeners = 0;
1278
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001279 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001280 if (p == null) return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281
1282 ArrayList<Receiver> deadReceivers = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07001283
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1285 if (records != null) {
1286 final int N = records.size();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001287 for (int i = 0; i < N; i++) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 UpdateRecord record = records.get(i);
Amith Yamasanib27528d2014-06-05 15:02:10 -07001289 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001290 // Sends a notification message to the receiver
1291 if (!record.mReceiver.callProviderEnabledLocked(provider, enabled)) {
1292 if (deadReceivers == null) {
1293 deadReceivers = new ArrayList<Receiver>();
1294 }
1295 deadReceivers.add(record.mReceiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001297 listeners++;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300 }
1301
1302 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001303 for (int i = deadReceivers.size() - 1; i >= 0; i--) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 removeUpdatesLocked(deadReceivers.get(i));
1305 }
1306 }
Nick Pellye0fd6932012-07-11 10:26:13 -07001307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (enabled) {
1309 p.enable();
1310 if (listeners > 0) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001311 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
1313 } else {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 p.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001316 }
1317
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001318 private void applyRequirementsLocked(String provider) {
1319 LocationProviderInterface p = mProvidersByName.get(provider);
1320 if (p == null) return;
1321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001323 WorkSource worksource = new WorkSource();
1324 ProviderRequest providerRequest = new ProviderRequest();
1325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 if (records != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001327 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001328 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001329 if (checkLocationAccess(record.mReceiver.mUid, record.mReceiver.mPackageName,
1330 record.mReceiver.mAllowedResolutionLevel)) {
1331 LocationRequest locationRequest = record.mRequest;
1332 providerRequest.locationRequests.add(locationRequest);
1333 if (locationRequest.getInterval() < providerRequest.interval) {
1334 providerRequest.reportLocation = true;
1335 providerRequest.interval = locationRequest.getInterval();
1336 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001337 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001338 }
1339 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001340
1341 if (providerRequest.reportLocation) {
1342 // calculate who to blame for power
1343 // This is somewhat arbitrary. We pick a threshold interval
1344 // that is slightly higher that the minimum interval, and
1345 // spread the blame across all applications with a request
1346 // under that threshold.
1347 long thresholdInterval = (providerRequest.interval + 1000) * 3 / 2;
1348 for (UpdateRecord record : records) {
Amith Yamasanib27528d2014-06-05 15:02:10 -07001349 if (isCurrentProfile(UserHandle.getUserId(record.mReceiver.mUid))) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001350 LocationRequest locationRequest = record.mRequest;
1351 if (locationRequest.getInterval() <= thresholdInterval) {
David Christiee55c9682013-08-22 10:10:34 -07001352 if (record.mReceiver.mWorkSource != null
1353 && record.mReceiver.mWorkSource.size() > 0
1354 && record.mReceiver.mWorkSource.getName(0) != null) {
David Christie82edc9b2013-07-19 11:31:42 -07001355 // Assign blame to another work source.
David Christiee55c9682013-08-22 10:10:34 -07001356 // Can only assign blame if the WorkSource contains names.
David Christie82edc9b2013-07-19 11:31:42 -07001357 worksource.add(record.mReceiver.mWorkSource);
1358 } else {
1359 // Assign blame to caller.
1360 worksource.add(
1361 record.mReceiver.mUid,
1362 record.mReceiver.mPackageName);
1363 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001364 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001365 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001366 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001369
1370 if (D) Log.d(TAG, "provider request: " + provider + " " + providerRequest);
1371 p.setRequest(providerRequest, worksource);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373
1374 private class UpdateRecord {
1375 final String mProvider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001376 final LocationRequest mRequest;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 final Receiver mReceiver;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001378 Location mLastFixBroadcast;
1379 long mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380
1381 /**
1382 * Note: must be constructed with lock held.
1383 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001384 UpdateRecord(String provider, LocationRequest request, Receiver receiver) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 mProvider = provider;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001386 mRequest = request;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 mReceiver = receiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001388
1389 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
1390 if (records == null) {
1391 records = new ArrayList<UpdateRecord>();
1392 mRecordsByProvider.put(provider, records);
1393 }
1394 if (!records.contains(this)) {
1395 records.add(this);
1396 }
David Christie2ff96af2014-01-30 16:09:37 -08001397
1398 // Update statistics for historical location requests by package/provider
1399 mRequestStatistics.startRequesting(
1400 mReceiver.mPackageName, provider, request.getInterval());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402
1403 /**
David Christie2ff96af2014-01-30 16:09:37 -08001404 * Method to be called when a record will no longer be used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 */
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001406 void disposeLocked(boolean removeReceiver) {
David Christie2ff96af2014-01-30 16:09:37 -08001407 mRequestStatistics.stopRequesting(mReceiver.mPackageName, mProvider);
1408
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001409 // remove from mRecordsByProvider
1410 ArrayList<UpdateRecord> globalRecords = mRecordsByProvider.get(this.mProvider);
1411 if (globalRecords != null) {
1412 globalRecords.remove(this);
1413 }
1414
1415 if (!removeReceiver) return; // the caller will handle the rest
1416
1417 // remove from Receiver#mUpdateRecords
1418 HashMap<String, UpdateRecord> receiverRecords = mReceiver.mUpdateRecords;
1419 if (receiverRecords != null) {
1420 receiverRecords.remove(this.mProvider);
1421
1422 // and also remove the Receiver if it has no more update records
1423 if (removeReceiver && receiverRecords.size() == 0) {
1424 removeUpdatesLocked(mReceiver);
1425 }
Mike Lockwood3a76fd62009-09-01 07:26:56 -04001426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428
1429 @Override
1430 public String toString() {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001431 StringBuilder s = new StringBuilder();
1432 s.append("UpdateRecord[");
1433 s.append(mProvider);
1434 s.append(' ').append(mReceiver.mPackageName).append('(');
1435 s.append(mReceiver.mUid).append(')');
1436 s.append(' ').append(mRequest);
1437 s.append(']');
1438 return s.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001440 }
1441
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001442 private Receiver getReceiverLocked(ILocationListener listener, int pid, int uid,
David Christie40e57822013-07-30 11:36:48 -07001443 String packageName, WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001444 IBinder binder = listener.asBinder();
1445 Receiver receiver = mReceivers.get(binder);
1446 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001447 receiver = new Receiver(listener, null, pid, uid, packageName, workSource,
1448 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001449 mReceivers.put(binder, receiver);
1450
1451 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001452 receiver.getListener().asBinder().linkToDeath(receiver, 0);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001453 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001454 Slog.e(TAG, "linkToDeath failed:", e);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001455 return null;
1456 }
1457 }
1458 return receiver;
1459 }
1460
David Christie82edc9b2013-07-19 11:31:42 -07001461 private Receiver getReceiverLocked(PendingIntent intent, int pid, int uid, String packageName,
David Christie40e57822013-07-30 11:36:48 -07001462 WorkSource workSource, boolean hideFromAppOps) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001463 Receiver receiver = mReceivers.get(intent);
1464 if (receiver == null) {
David Christie40e57822013-07-30 11:36:48 -07001465 receiver = new Receiver(null, intent, pid, uid, packageName, workSource,
1466 hideFromAppOps);
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001467 mReceivers.put(intent, receiver);
1468 }
1469 return receiver;
1470 }
1471
Victoria Lease37425c32012-10-16 16:08:48 -07001472 /**
1473 * Creates a LocationRequest based upon the supplied LocationRequest that to meets resolution
1474 * and consistency requirements.
1475 *
1476 * @param request the LocationRequest from which to create a sanitized version
Victoria Lease37425c32012-10-16 16:08:48 -07001477 * @return a version of request that meets the given resolution and consistency requirements
1478 * @hide
1479 */
1480 private LocationRequest createSanitizedRequest(LocationRequest request, int resolutionLevel) {
1481 LocationRequest sanitizedRequest = new LocationRequest(request);
1482 if (resolutionLevel < RESOLUTION_LEVEL_FINE) {
1483 switch (sanitizedRequest.getQuality()) {
Victoria Lease09016ab2012-09-16 12:33:15 -07001484 case LocationRequest.ACCURACY_FINE:
Victoria Lease37425c32012-10-16 16:08:48 -07001485 sanitizedRequest.setQuality(LocationRequest.ACCURACY_BLOCK);
Victoria Lease09016ab2012-09-16 12:33:15 -07001486 break;
1487 case LocationRequest.POWER_HIGH:
Victoria Lease37425c32012-10-16 16:08:48 -07001488 sanitizedRequest.setQuality(LocationRequest.POWER_LOW);
Victoria Lease09016ab2012-09-16 12:33:15 -07001489 break;
1490 }
1491 // throttle
Victoria Lease37425c32012-10-16 16:08:48 -07001492 if (sanitizedRequest.getInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1493 sanitizedRequest.setInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001494 }
Victoria Lease37425c32012-10-16 16:08:48 -07001495 if (sanitizedRequest.getFastestInterval() < LocationFudger.FASTEST_INTERVAL_MS) {
1496 sanitizedRequest.setFastestInterval(LocationFudger.FASTEST_INTERVAL_MS);
Victoria Lease09016ab2012-09-16 12:33:15 -07001497 }
Nick Pelly74fa7ea2012-08-13 19:36:38 -07001498 }
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001499 // make getFastestInterval() the minimum of interval and fastest interval
Victoria Lease37425c32012-10-16 16:08:48 -07001500 if (sanitizedRequest.getFastestInterval() > sanitizedRequest.getInterval()) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07001501 request.setFastestInterval(request.getInterval());
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001502 }
Victoria Lease37425c32012-10-16 16:08:48 -07001503 return sanitizedRequest;
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001504 }
1505
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001506 private void checkPackageName(String packageName) {
Nick Pellye0fd6932012-07-11 10:26:13 -07001507 if (packageName == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001508 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001509 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001510 int uid = Binder.getCallingUid();
Nick Pellye0fd6932012-07-11 10:26:13 -07001511 String[] packages = mPackageManager.getPackagesForUid(uid);
1512 if (packages == null) {
1513 throw new SecurityException("invalid UID " + uid);
1514 }
1515 for (String pkg : packages) {
1516 if (packageName.equals(pkg)) return;
1517 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001518 throw new SecurityException("invalid package name: " + packageName);
Nick Pellye0fd6932012-07-11 10:26:13 -07001519 }
1520
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001521 private void checkPendingIntent(PendingIntent intent) {
1522 if (intent == null) {
1523 throw new IllegalArgumentException("invalid pending intent: " + intent);
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001524 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001525 }
1526
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001527 private Receiver checkListenerOrIntentLocked(ILocationListener listener, PendingIntent intent,
David Christie40e57822013-07-30 11:36:48 -07001528 int pid, int uid, String packageName, WorkSource workSource, boolean hideFromAppOps) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001529 if (intent == null && listener == null) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001530 throw new IllegalArgumentException("need either listener or intent");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001531 } else if (intent != null && listener != null) {
1532 throw new IllegalArgumentException("cannot register both listener and intent");
1533 } else if (intent != null) {
1534 checkPendingIntent(intent);
David Christie40e57822013-07-30 11:36:48 -07001535 return getReceiverLocked(intent, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001536 } else {
David Christie40e57822013-07-30 11:36:48 -07001537 return getReceiverLocked(listener, pid, uid, packageName, workSource, hideFromAppOps);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001538 }
Dianne Hackborn6c418d52011-06-29 14:05:33 -07001539 }
1540
Nick Pellye0fd6932012-07-11 10:26:13 -07001541 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001542 public void requestLocationUpdates(LocationRequest request, ILocationListener listener,
1543 PendingIntent intent, String packageName) {
1544 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1545 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001546 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1547 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1548 request.getProvider());
David Christie82edc9b2013-07-19 11:31:42 -07001549 WorkSource workSource = request.getWorkSource();
1550 if (workSource != null && workSource.size() > 0) {
David Christie40e57822013-07-30 11:36:48 -07001551 checkDeviceStatsAllowed();
1552 }
1553 boolean hideFromAppOps = request.getHideFromAppOps();
1554 if (hideFromAppOps) {
1555 checkUpdateAppOpsAllowed();
David Christie82edc9b2013-07-19 11:31:42 -07001556 }
Victoria Lease37425c32012-10-16 16:08:48 -07001557 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001559 final int pid = Binder.getCallingPid();
1560 final int uid = Binder.getCallingUid();
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001561 // providers may use public location API's, need to clear identity
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001562 long identity = Binder.clearCallingIdentity();
1563 try {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001564 // We don't check for MODE_IGNORED here; we will do that when we go to deliver
1565 // a location.
Dianne Hackborn35654b62013-01-14 17:38:02 -08001566 checkLocationAccess(uid, packageName, allowedResolutionLevel);
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001567
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001568 synchronized (mLock) {
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001569 Receiver recevier = checkListenerOrIntentLocked(listener, intent, pid, uid,
David Christie40e57822013-07-30 11:36:48 -07001570 packageName, workSource, hideFromAppOps);
Victoria Lease37425c32012-10-16 16:08:48 -07001571 requestLocationUpdatesLocked(sanitizedRequest, recevier, pid, uid, packageName);
Mike Lockwood2d4d1bf2010-10-18 17:06:26 -04001572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 } finally {
1574 Binder.restoreCallingIdentity(identity);
1575 }
1576 }
1577
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001578 private void requestLocationUpdatesLocked(LocationRequest request, Receiver receiver,
1579 int pid, int uid, String packageName) {
1580 // Figure out the provider. Either its explicitly request (legacy use cases), or
1581 // use the fused provider
1582 if (request == null) request = DEFAULT_LOCATION_REQUEST;
1583 String name = request.getProvider();
Victoria Lease09016ab2012-09-16 12:33:15 -07001584 if (name == null) {
1585 throw new IllegalArgumentException("provider name must not be null");
1586 }
Zhentao Sunc5fc9982013-04-17 17:47:53 -07001587
1588 if (D) Log.d(TAG, "request " + Integer.toHexString(System.identityHashCode(receiver))
1589 + " " + name + " " + request + " from " + packageName + "(" + uid + ")");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001590 LocationProviderInterface provider = mProvidersByName.get(name);
1591 if (provider == null) {
Victoria Leaseb30f3832013-10-13 12:15:40 -07001592 throw new IllegalArgumentException("provider doesn't exist: " + name);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001593 }
1594
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001595 UpdateRecord record = new UpdateRecord(name, request, receiver);
1596 UpdateRecord oldRecord = receiver.mUpdateRecords.put(name, record);
1597 if (oldRecord != null) {
1598 oldRecord.disposeLocked(false);
1599 }
1600
Victoria Lease09eeaec2013-02-05 11:34:13 -08001601 boolean isProviderEnabled = isAllowedByUserSettingsLocked(name, uid);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001602 if (isProviderEnabled) {
1603 applyRequirementsLocked(name);
1604 } else {
1605 // Notify the listener that updates are currently disabled
1606 receiver.callProviderEnabledLocked(name, false);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001607 }
David Christie0b837452013-07-29 16:02:13 -07001608 // Update the monitoring here just in case multiple location requests were added to the
1609 // same receiver (this request may be high power and the initial might not have been).
1610 receiver.updateMonitoring(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
Nick Pellye0fd6932012-07-11 10:26:13 -07001613 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001614 public void removeUpdates(ILocationListener listener, PendingIntent intent,
1615 String packageName) {
1616 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001617
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001618 final int pid = Binder.getCallingPid();
1619 final int uid = Binder.getCallingUid();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001620
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001621 synchronized (mLock) {
David Christie82edc9b2013-07-19 11:31:42 -07001622 WorkSource workSource = null;
David Christie40e57822013-07-30 11:36:48 -07001623 boolean hideFromAppOps = false;
1624 Receiver receiver = checkListenerOrIntentLocked(listener, intent, pid, uid,
1625 packageName, workSource, hideFromAppOps);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001626
1627 // providers may use public location API's, need to clear identity
1628 long identity = Binder.clearCallingIdentity();
1629 try {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001630 removeUpdatesLocked(receiver);
Dianne Hackbornf5fdca92013-06-05 14:53:33 -07001631 } finally {
1632 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635 }
1636
1637 private void removeUpdatesLocked(Receiver receiver) {
Dianne Hackborn7ff30112012-11-08 11:12:09 -08001638 if (D) Log.i(TAG, "remove " + Integer.toHexString(System.identityHashCode(receiver)));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001639
1640 if (mReceivers.remove(receiver.mKey) != null && receiver.isListener()) {
1641 receiver.getListener().asBinder().unlinkToDeath(receiver, 0);
1642 synchronized (receiver) {
Victoria Lease0aa28602013-05-29 15:28:26 -07001643 receiver.clearPendingBroadcastsLocked();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001644 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 }
1646
Dianne Hackborn1304f4a2013-07-09 18:17:27 -07001647 receiver.updateMonitoring(false);
1648
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001649 // Record which providers were associated with this listener
1650 HashSet<String> providers = new HashSet<String>();
1651 HashMap<String, UpdateRecord> oldRecords = receiver.mUpdateRecords;
1652 if (oldRecords != null) {
1653 // Call dispose() on the obsolete update records.
1654 for (UpdateRecord record : oldRecords.values()) {
David Christie2ff96af2014-01-30 16:09:37 -08001655 // Update statistics for historical location requests by package/provider
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001656 record.disposeLocked(false);
1657 }
1658 // Accumulate providers
1659 providers.addAll(oldRecords.keySet());
1660 }
1661
1662 // update provider
1663 for (String provider : providers) {
1664 // If provider is already disabled, don't need to do anything
Victoria Lease09eeaec2013-02-05 11:34:13 -08001665 if (!isAllowedByCurrentUserSettingsLocked(provider)) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001666 continue;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001667 }
1668
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001669 applyRequirementsLocked(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
1671 }
1672
Dianne Hackbornc2293022013-02-06 23:14:49 -08001673 private void applyAllProviderRequirementsLocked() {
1674 for (LocationProviderInterface p : mProviders) {
1675 // If provider is already disabled, don't need to do anything
Dianne Hackborn64d41d72013-02-07 00:33:31 -08001676 if (!isAllowedByCurrentUserSettingsLocked(p.getName())) {
Dianne Hackbornc2293022013-02-06 23:14:49 -08001677 continue;
1678 }
1679
1680 applyRequirementsLocked(p.getName());
1681 }
1682 }
1683
Nick Pellye0fd6932012-07-11 10:26:13 -07001684 @Override
Nick Pelly4035f5a2012-08-17 14:43:49 -07001685 public Location getLastLocation(LocationRequest request, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001686 if (D) Log.d(TAG, "getLastLocation: " + request);
1687 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001688 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
Nick Pelly4035f5a2012-08-17 14:43:49 -07001689 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001690 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1691 request.getProvider());
1692 // no need to sanitize this request, as only the provider name is used
Nick Pelly4035f5a2012-08-17 14:43:49 -07001693
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001694 final int uid = Binder.getCallingUid();
1695 final long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001696 try {
1697 if (mBlacklist.isBlacklisted(packageName)) {
1698 if (D) Log.d(TAG, "not returning last loc for blacklisted app: " +
1699 packageName);
Victoria Lease09016ab2012-09-16 12:33:15 -07001700 return null;
1701 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001702
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001703 if (!reportLocationAccessNoThrow(uid, packageName, allowedResolutionLevel)) {
1704 if (D) Log.d(TAG, "not returning last loc for no op app: " +
1705 packageName);
1706 return null;
1707 }
1708
Victoria Leaseb711d572012-10-02 13:14:11 -07001709 synchronized (mLock) {
1710 // Figure out the provider. Either its explicitly request (deprecated API's),
1711 // or use the fused provider
1712 String name = request.getProvider();
1713 if (name == null) name = LocationManager.FUSED_PROVIDER;
1714 LocationProviderInterface provider = mProvidersByName.get(name);
1715 if (provider == null) return null;
1716
Victoria Lease09eeaec2013-02-05 11:34:13 -08001717 if (!isAllowedByUserSettingsLocked(name, uid)) return null;
Victoria Leaseb711d572012-10-02 13:14:11 -07001718
David Christie1b9b7b12013-04-15 15:31:11 -07001719 Location location;
1720 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
1721 // Make sure that an app with coarse permissions can't get frequent location
1722 // updates by calling LocationManager.getLastKnownLocation repeatedly.
1723 location = mLastLocationCoarseInterval.get(name);
1724 } else {
1725 location = mLastLocation.get(name);
1726 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001727 if (location == null) {
1728 return null;
1729 }
Victoria Lease37425c32012-10-16 16:08:48 -07001730 if (allowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
Victoria Leaseb711d572012-10-02 13:14:11 -07001731 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
1732 if (noGPSLocation != null) {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001733 return new Location(mLocationFudger.getOrCreate(noGPSLocation));
Victoria Leaseb711d572012-10-02 13:14:11 -07001734 }
Victoria Lease37425c32012-10-16 16:08:48 -07001735 } else {
Dianne Hackborn6c5406a2012-11-29 16:18:01 -08001736 return new Location(location);
Victoria Lease09016ab2012-09-16 12:33:15 -07001737 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001738 }
Victoria Leaseb711d572012-10-02 13:14:11 -07001739 return null;
1740 } finally {
1741 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001742 }
1743 }
1744
1745 @Override
1746 public void requestGeofence(LocationRequest request, Geofence geofence, PendingIntent intent,
1747 String packageName) {
1748 if (request == null) request = DEFAULT_LOCATION_REQUEST;
Victoria Lease37425c32012-10-16 16:08:48 -07001749 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1750 checkResolutionLevelIsSufficientForGeofenceUse(allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001751 checkPendingIntent(intent);
1752 checkPackageName(packageName);
Victoria Lease37425c32012-10-16 16:08:48 -07001753 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
1754 request.getProvider());
1755 LocationRequest sanitizedRequest = createSanitizedRequest(request, allowedResolutionLevel);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001756
Victoria Lease37425c32012-10-16 16:08:48 -07001757 if (D) Log.d(TAG, "requestGeofence: " + sanitizedRequest + " " + geofence + " " + intent);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001758
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001759 // geo-fence manager uses the public location API, need to clear identity
1760 int uid = Binder.getCallingUid();
Victoria Lease56e675b2012-11-05 19:25:06 -08001761 if (UserHandle.getUserId(uid) != UserHandle.USER_OWNER) {
1762 // temporary measure until geofences work for secondary users
1763 Log.w(TAG, "proximity alerts are currently available only to the primary user");
1764 return;
1765 }
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001766 long identity = Binder.clearCallingIdentity();
1767 try {
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08001768 mGeofenceManager.addFence(sanitizedRequest, geofence, intent, allowedResolutionLevel,
1769 uid, packageName);
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001770 } finally {
1771 Binder.restoreCallingIdentity(identity);
1772 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001773 }
1774
1775 @Override
1776 public void removeGeofence(Geofence geofence, PendingIntent intent, String packageName) {
Victoria Lease37425c32012-10-16 16:08:48 -07001777 checkResolutionLevelIsSufficientForGeofenceUse(getCallerAllowedResolutionLevel());
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001778 checkPendingIntent(intent);
1779 checkPackageName(packageName);
1780
1781 if (D) Log.d(TAG, "removeGeofence: " + geofence + " " + intent);
1782
Nick Pelly2b7a0d02012-08-17 15:09:44 -07001783 // geo-fence manager uses the public location API, need to clear identity
1784 long identity = Binder.clearCallingIdentity();
1785 try {
1786 mGeofenceManager.removeFence(geofence, intent);
1787 } finally {
1788 Binder.restoreCallingIdentity(identity);
1789 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001790 }
1791
1792
1793 @Override
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001794 public boolean addGpsStatusListener(IGpsStatusListener listener, String packageName) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001795 if (mGpsStatusProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 return false;
1797 }
Dianne Hackborn35654b62013-01-14 17:38:02 -08001798 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1799 checkResolutionLevelIsSufficientForProviderUse(allowedResolutionLevel,
Victoria Lease37425c32012-10-16 16:08:48 -07001800 LocationManager.GPS_PROVIDER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001801
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001802 final int uid = Binder.getCallingUid();
1803 final long ident = Binder.clearCallingIdentity();
1804 try {
Victoria Lease3d5173d2013-02-05 16:07:32 -08001805 if (!checkLocationAccess(uid, packageName, allowedResolutionLevel)) {
Dianne Hackborna06de0f2012-12-11 16:34:47 -08001806 return false;
1807 }
1808 } finally {
1809 Binder.restoreCallingIdentity(ident);
1810 }
1811
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001812 try {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001813 mGpsStatusProvider.addGpsStatusListener(listener);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001815 Slog.e(TAG, "mGpsStatusProvider.addGpsStatusListener failed", e);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 return false;
1817 }
1818 return true;
1819 }
1820
Nick Pellye0fd6932012-07-11 10:26:13 -07001821 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 public void removeGpsStatusListener(IGpsStatusListener listener) {
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001823 synchronized (mLock) {
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001824 try {
1825 mGpsStatusProvider.removeGpsStatusListener(listener);
1826 } catch (Exception e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001827 Slog.e(TAG, "mGpsStatusProvider.removeGpsStatusListener failed", e);
Mike Lockwood15e3d0f2009-05-01 07:53:28 -04001828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830 }
1831
Nick Pellye0fd6932012-07-11 10:26:13 -07001832 @Override
destradaaea8a8a62014-06-23 18:19:03 -07001833 public boolean addGpsMeasurementsListener(
1834 IGpsMeasurementsListener listener,
1835 String packageName) {
1836 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1837 checkResolutionLevelIsSufficientForProviderUse(
1838 allowedResolutionLevel,
1839 LocationManager.GPS_PROVIDER);
1840
1841 int uid = Binder.getCallingUid();
1842 long identity = Binder.clearCallingIdentity();
1843 boolean hasLocationAccess;
1844 try {
1845 hasLocationAccess = checkLocationAccess(uid, packageName, allowedResolutionLevel);
1846 } finally {
1847 Binder.restoreCallingIdentity(identity);
1848 }
1849
1850 if (!hasLocationAccess) {
1851 return false;
1852 }
destradaaea8a8a62014-06-23 18:19:03 -07001853 return mGpsMeasurementsProvider.addListener(listener);
1854 }
1855
1856 @Override
1857 public boolean removeGpsMeasurementsListener(IGpsMeasurementsListener listener) {
1858 return mGpsMeasurementsProvider.removeListener(listener);
1859 }
1860
1861 @Override
destradaa4b3e3932014-07-21 18:01:47 -07001862 public boolean addGpsNavigationMessageListener(
1863 IGpsNavigationMessageListener listener,
1864 String packageName) {
1865 int allowedResolutionLevel = getCallerAllowedResolutionLevel();
1866 checkResolutionLevelIsSufficientForProviderUse(
1867 allowedResolutionLevel,
1868 LocationManager.GPS_PROVIDER);
1869
1870 int uid = Binder.getCallingUid();
1871 long identity = Binder.clearCallingIdentity();
1872 boolean hasLocationAccess;
1873 try {
1874 hasLocationAccess = checkLocationAccess(uid, packageName, allowedResolutionLevel);
1875 } finally {
1876 Binder.restoreCallingIdentity(identity);
1877 }
1878
1879 if (!hasLocationAccess) {
1880 return false;
1881 }
1882 return mGpsNavigationMessageProvider.addListener(listener);
1883 }
1884
1885 @Override
1886 public boolean removeGpsNavigationMessageListener(IGpsNavigationMessageListener listener) {
1887 return mGpsNavigationMessageProvider.removeListener(listener);
1888 }
1889
1890 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 public boolean sendExtraCommand(String provider, String command, Bundle extras) {
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001892 if (provider == null) {
1893 // throw NullPointerException to remain compatible with previous implementation
1894 throw new NullPointerException();
1895 }
Victoria Lease37425c32012-10-16 16:08:48 -07001896 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1897 provider);
Mike Lockwoodc6cc8362009-08-17 13:16:08 -04001898
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 // and check for ACCESS_LOCATION_EXTRA_COMMANDS
Mike Lockwoodb7e99222009-07-07 13:18:21 -04001900 if ((mContext.checkCallingOrSelfPermission(ACCESS_LOCATION_EXTRA_COMMANDS)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 != PackageManager.PERMISSION_GRANTED)) {
1902 throw new SecurityException("Requires ACCESS_LOCATION_EXTRA_COMMANDS permission");
1903 }
1904
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04001905 synchronized (mLock) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001906 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001907 if (p == null) return false;
Nick Pellye0fd6932012-07-11 10:26:13 -07001908
Mike Lockwoodd03ff942010-02-09 08:46:14 -05001909 return p.sendExtraCommand(command, extras);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910 }
1911 }
1912
Nick Pellye0fd6932012-07-11 10:26:13 -07001913 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001914 public boolean sendNiResponse(int notifId, int userResponse) {
Mike Lockwood18ad9f62009-08-27 14:01:23 -07001915 if (Binder.getCallingUid() != Process.myUid()) {
1916 throw new SecurityException(
1917 "calling sendNiResponse from outside of the system is not allowed");
1918 }
Danke Xie22d1f9f2009-08-18 18:28:45 -04001919 try {
1920 return mNetInitiatedListener.sendNiResponse(notifId, userResponse);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001921 } catch (RemoteException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001922 Slog.e(TAG, "RemoteException in LocationManagerService.sendNiResponse");
Danke Xie22d1f9f2009-08-18 18:28:45 -04001923 return false;
1924 }
1925 }
1926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 /**
Mike Lockwood628fd6d2010-01-25 22:46:13 -05001928 * @return null if the provider does not exist
Alexey Tarasovf2db9fb2009-09-01 02:37:07 +11001929 * @throws SecurityException if the provider is not allowed to be
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930 * accessed by the caller
1931 */
Nick Pellye0fd6932012-07-11 10:26:13 -07001932 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001933 public ProviderProperties getProviderProperties(String provider) {
Laurent Tub7f9d252012-10-16 14:25:00 -07001934 if (mProvidersByName.get(provider) == null) {
David Christie2ff96af2014-01-30 16:09:37 -08001935 return null;
Laurent Tub7f9d252012-10-16 14:25:00 -07001936 }
1937
Victoria Lease37425c32012-10-16 16:08:48 -07001938 checkResolutionLevelIsSufficientForProviderUse(getCallerAllowedResolutionLevel(),
1939 provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001940
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001941 LocationProviderInterface p;
1942 synchronized (mLock) {
1943 p = mProvidersByName.get(provider);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001944 }
1945
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001946 if (p == null) return null;
1947 return p.getProperties();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001948 }
1949
Nick Pellye0fd6932012-07-11 10:26:13 -07001950 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001951 public boolean isProviderEnabled(String provider) {
Tom O'Neilld5759432013-09-11 11:03:03 -07001952 // Fused provider is accessed indirectly via criteria rather than the provider-based APIs,
1953 // so we discourage its use
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001954 if (LocationManager.FUSED_PROVIDER.equals(provider)) return false;
1955
Victoria Lease09eeaec2013-02-05 11:34:13 -08001956 int uid = Binder.getCallingUid();
Victoria Lease269518e2012-10-29 08:25:39 -07001957 long identity = Binder.clearCallingIdentity();
Victoria Leaseb711d572012-10-02 13:14:11 -07001958 try {
1959 synchronized (mLock) {
1960 LocationProviderInterface p = mProvidersByName.get(provider);
1961 if (p == null) return false;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001962
Victoria Lease09eeaec2013-02-05 11:34:13 -08001963 return isAllowedByUserSettingsLocked(provider, uid);
Victoria Leaseb711d572012-10-02 13:14:11 -07001964 }
1965 } finally {
1966 Binder.restoreCallingIdentity(identity);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001967 }
1968 }
1969
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001970 /**
1971 * Returns "true" if the UID belongs to a bound location provider.
1972 *
1973 * @param uid the uid
1974 * @return true if uid belongs to a bound location provider
1975 */
1976 private boolean isUidALocationProvider(int uid) {
1977 if (uid == Process.SYSTEM_UID) {
1978 return true;
1979 }
1980 if (mGeocodeProvider != null) {
David Christie1f141c12014-05-14 15:11:15 -07001981 if (doesUidHavePackage(uid, mGeocodeProvider.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001982 }
1983 for (LocationProviderProxy proxy : mProxyProviders) {
David Christie1f141c12014-05-14 15:11:15 -07001984 if (doesUidHavePackage(uid, proxy.getConnectedPackageName())) return true;
Victoria Lease03cdd3d2013-02-01 15:15:54 -08001985 }
1986 return false;
1987 }
1988
Nick Pelly6fa9ad42012-07-16 12:18:23 -07001989 private void checkCallerIsProvider() {
1990 if (mContext.checkCallingOrSelfPermission(INSTALL_LOCATION_PROVIDER)
1991 == PackageManager.PERMISSION_GRANTED) {
1992 return;
1993 }
1994
1995 // Previously we only used the INSTALL_LOCATION_PROVIDER
1996 // check. But that is system or signature
1997 // protection level which is not flexible enough for
1998 // providers installed oustide the system image. So
1999 // also allow providers with a UID matching the
2000 // currently bound package name
2001
Victoria Lease03cdd3d2013-02-01 15:15:54 -08002002 if (isUidALocationProvider(Binder.getCallingUid())) {
2003 return;
2004 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002005
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002006 throw new SecurityException("need INSTALL_LOCATION_PROVIDER permission, " +
2007 "or UID of a currently bound location provider");
2008 }
2009
David Christie1f141c12014-05-14 15:11:15 -07002010 /**
2011 * Returns true if the given package belongs to the given uid.
2012 */
2013 private boolean doesUidHavePackage(int uid, String packageName) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002014 if (packageName == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002015 return false;
2016 }
David Christie1f141c12014-05-14 15:11:15 -07002017 String[] packageNames = mPackageManager.getPackagesForUid(uid);
2018 if (packageNames == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002019 return false;
2020 }
David Christie1f141c12014-05-14 15:11:15 -07002021 for (String name : packageNames) {
2022 if (packageName.equals(name)) {
2023 return true;
2024 }
2025 }
2026 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002027 }
2028
Nick Pellye0fd6932012-07-11 10:26:13 -07002029 @Override
Mike Lockwooda4903f22010-02-17 06:42:23 -05002030 public void reportLocation(Location location, boolean passive) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002031 checkCallerIsProvider();
Mike Lockwood275555c2009-05-01 11:30:34 -04002032
Nick Pelly2eeeec22012-07-18 13:13:37 -07002033 if (!location.isComplete()) {
2034 Log.w(TAG, "Dropping incomplete location: " + location);
2035 return;
2036 }
2037
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002038 mLocationHandler.removeMessages(MSG_LOCATION_CHANGED, location);
2039 Message m = Message.obtain(mLocationHandler, MSG_LOCATION_CHANGED, location);
Mike Lockwooda4903f22010-02-17 06:42:23 -05002040 m.arg1 = (passive ? 1 : 0);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002041 mLocationHandler.sendMessageAtFrontOfQueue(m);
2042 }
2043
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044
Laurent Tu75defb62012-11-01 16:21:52 -07002045 private static boolean shouldBroadcastSafe(
2046 Location loc, Location lastLoc, UpdateRecord record, long now) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002047 // Always broadcast the first update
2048 if (lastLoc == null) {
2049 return true;
2050 }
2051
Nick Pellyf1be6862012-05-15 10:53:42 -07002052 // Check whether sufficient time has passed
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002053 long minTime = record.mRequest.getFastestInterval();
David Christie1b9b7b12013-04-15 15:31:11 -07002054 long delta = (loc.getElapsedRealtimeNanos() - lastLoc.getElapsedRealtimeNanos())
2055 / NANOS_PER_MILLI;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002056 if (delta < minTime - MAX_PROVIDER_SCHEDULING_JITTER_MS) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002057 return false;
2058 }
2059
2060 // Check whether sufficient distance has been traveled
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002061 double minDistance = record.mRequest.getSmallestDisplacement();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002062 if (minDistance > 0.0) {
2063 if (loc.distanceTo(lastLoc) <= minDistance) {
2064 return false;
2065 }
2066 }
2067
Laurent Tu75defb62012-11-01 16:21:52 -07002068 // Check whether sufficient number of udpates is left
2069 if (record.mRequest.getNumUpdates() <= 0) {
2070 return false;
2071 }
2072
2073 // Check whether the expiry date has passed
2074 if (record.mRequest.getExpireAt() < now) {
2075 return false;
2076 }
2077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002078 return true;
2079 }
2080
Mike Lockwooda4903f22010-02-17 06:42:23 -05002081 private void handleLocationChangedLocked(Location location, boolean passive) {
Nick Pelly4e31c4f2012-08-13 19:35:39 -07002082 if (D) Log.d(TAG, "incoming location: " + location);
2083
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002084 long now = SystemClock.elapsedRealtime();
Mike Lockwooda4903f22010-02-17 06:42:23 -05002085 String provider = (passive ? LocationManager.PASSIVE_PROVIDER : location.getProvider());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002086
Laurent Tu60ec50a2012-10-04 17:00:10 -07002087 // Skip if the provider is unknown.
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002088 LocationProviderInterface p = mProvidersByName.get(provider);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002089 if (p == null) return;
2090
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002091 // Update last known locations
Victoria Lease09016ab2012-09-16 12:33:15 -07002092 Location noGPSLocation = location.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2093 Location lastNoGPSLocation = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002094 Location lastLocation = mLastLocation.get(provider);
Mike Lockwood4e50b782009-04-03 08:24:43 -07002095 if (lastLocation == null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002096 lastLocation = new Location(provider);
2097 mLastLocation.put(provider, lastLocation);
Victoria Lease09016ab2012-09-16 12:33:15 -07002098 } else {
2099 lastNoGPSLocation = lastLocation.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2100 if (noGPSLocation == null && lastNoGPSLocation != null) {
2101 // New location has no no-GPS location: adopt last no-GPS location. This is set
2102 // directly into location because we do not want to notify COARSE clients.
2103 location.setExtraLocation(Location.EXTRA_NO_GPS_LOCATION, lastNoGPSLocation);
2104 }
Mike Lockwood4e50b782009-04-03 08:24:43 -07002105 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002106 lastLocation.set(location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002107
David Christie1b9b7b12013-04-15 15:31:11 -07002108 // Update last known coarse interval location if enough time has passed.
2109 Location lastLocationCoarseInterval = mLastLocationCoarseInterval.get(provider);
2110 if (lastLocationCoarseInterval == null) {
2111 lastLocationCoarseInterval = new Location(location);
2112 mLastLocationCoarseInterval.put(provider, lastLocationCoarseInterval);
2113 }
2114 long timeDiffNanos = location.getElapsedRealtimeNanos()
2115 - lastLocationCoarseInterval.getElapsedRealtimeNanos();
2116 if (timeDiffNanos > LocationFudger.FASTEST_INTERVAL_MS * NANOS_PER_MILLI) {
2117 lastLocationCoarseInterval.set(location);
2118 }
2119 // Don't ever return a coarse location that is more recent than the allowed update
2120 // interval (i.e. don't allow an app to keep registering and unregistering for
2121 // location updates to overcome the minimum interval).
2122 noGPSLocation =
2123 lastLocationCoarseInterval.getExtraLocation(Location.EXTRA_NO_GPS_LOCATION);
2124
Laurent Tu60ec50a2012-10-04 17:00:10 -07002125 // Skip if there are no UpdateRecords for this provider.
2126 ArrayList<UpdateRecord> records = mRecordsByProvider.get(provider);
2127 if (records == null || records.size() == 0) return;
2128
Victoria Lease09016ab2012-09-16 12:33:15 -07002129 // Fetch coarse location
2130 Location coarseLocation = null;
David Christie1b9b7b12013-04-15 15:31:11 -07002131 if (noGPSLocation != null) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002132 coarseLocation = mLocationFudger.getOrCreate(noGPSLocation);
2133 }
2134
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 // Fetch latest status update time
2136 long newStatusUpdateTime = p.getStatusUpdateTime();
2137
David Christie2ff96af2014-01-30 16:09:37 -08002138 // Get latest status
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002139 Bundle extras = new Bundle();
2140 int status = p.getStatus(extras);
2141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 ArrayList<Receiver> deadReceivers = null;
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002143 ArrayList<UpdateRecord> deadUpdateRecords = null;
Nick Pellye0fd6932012-07-11 10:26:13 -07002144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 // Broadcast location or status to all listeners
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002146 for (UpdateRecord r : records) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002147 Receiver receiver = r.mReceiver;
Mike Lockwood03ca2162010-04-01 08:10:09 -07002148 boolean receiverDead = false;
Nick Pelly4035f5a2012-08-17 14:43:49 -07002149
Victoria Lease269518e2012-10-29 08:25:39 -07002150 int receiverUserId = UserHandle.getUserId(receiver.mUid);
Amith Yamasanib27528d2014-06-05 15:02:10 -07002151 if (!isCurrentProfile(receiverUserId) && !isUidALocationProvider(receiver.mUid)) {
Victoria Leaseb711d572012-10-02 13:14:11 -07002152 if (D) {
Victoria Lease269518e2012-10-29 08:25:39 -07002153 Log.d(TAG, "skipping loc update for background user " + receiverUserId +
Victoria Leaseb711d572012-10-02 13:14:11 -07002154 " (current user: " + mCurrentUserId + ", app: " +
2155 receiver.mPackageName + ")");
2156 }
2157 continue;
2158 }
2159
Nick Pelly4035f5a2012-08-17 14:43:49 -07002160 if (mBlacklist.isBlacklisted(receiver.mPackageName)) {
2161 if (D) Log.d(TAG, "skipping loc update for blacklisted app: " +
2162 receiver.mPackageName);
2163 continue;
2164 }
2165
Dianne Hackborn5e45ee62013-01-24 19:13:44 -08002166 if (!reportLocationAccessNoThrow(receiver.mUid, receiver.mPackageName,
2167 receiver.mAllowedResolutionLevel)) {
2168 if (D) Log.d(TAG, "skipping loc update for no op app: " +
2169 receiver.mPackageName);
2170 continue;
2171 }
2172
Victoria Lease09016ab2012-09-16 12:33:15 -07002173 Location notifyLocation = null;
Victoria Lease37425c32012-10-16 16:08:48 -07002174 if (receiver.mAllowedResolutionLevel < RESOLUTION_LEVEL_FINE) {
2175 notifyLocation = coarseLocation; // use coarse location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002176 } else {
Victoria Lease37425c32012-10-16 16:08:48 -07002177 notifyLocation = lastLocation; // use fine location
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002178 }
Victoria Lease09016ab2012-09-16 12:33:15 -07002179 if (notifyLocation != null) {
2180 Location lastLoc = r.mLastFixBroadcast;
Laurent Tu75defb62012-11-01 16:21:52 -07002181 if ((lastLoc == null) || shouldBroadcastSafe(notifyLocation, lastLoc, r, now)) {
Victoria Lease09016ab2012-09-16 12:33:15 -07002182 if (lastLoc == null) {
2183 lastLoc = new Location(notifyLocation);
2184 r.mLastFixBroadcast = lastLoc;
2185 } else {
2186 lastLoc.set(notifyLocation);
2187 }
2188 if (!receiver.callLocationChangedLocked(notifyLocation)) {
2189 Slog.w(TAG, "RemoteException calling onLocationChanged on " + receiver);
2190 receiverDead = true;
2191 }
Laurent Tu75defb62012-11-01 16:21:52 -07002192 r.mRequest.decrementNumUpdates();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002193 }
2194 }
2195
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002196 long prevStatusUpdateTime = r.mLastStatusBroadcast;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002197 if ((newStatusUpdateTime > prevStatusUpdateTime) &&
Victoria Lease09016ab2012-09-16 12:33:15 -07002198 (prevStatusUpdateTime != 0 || status != LocationProvider.AVAILABLE)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002200 r.mLastStatusBroadcast = newStatusUpdateTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002201 if (!receiver.callStatusChangedLocked(provider, status, extras)) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002202 receiverDead = true;
Joe Onorato8a9b2202010-02-26 18:56:32 -08002203 Slog.w(TAG, "RemoteException calling onStatusChanged on " + receiver);
Mike Lockwood03ca2162010-04-01 08:10:09 -07002204 }
2205 }
2206
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002207 // track expired records
Laurent Tu75defb62012-11-01 16:21:52 -07002208 if (r.mRequest.getNumUpdates() <= 0 || r.mRequest.getExpireAt() < now) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002209 if (deadUpdateRecords == null) {
2210 deadUpdateRecords = new ArrayList<UpdateRecord>();
2211 }
2212 deadUpdateRecords.add(r);
2213 }
2214 // track dead receivers
2215 if (receiverDead) {
Mike Lockwood03ca2162010-04-01 08:10:09 -07002216 if (deadReceivers == null) {
2217 deadReceivers = new ArrayList<Receiver>();
2218 }
2219 if (!deadReceivers.contains(receiver)) {
2220 deadReceivers.add(receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002221 }
2222 }
2223 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002224
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002225 // remove dead records and receivers outside the loop
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002226 if (deadReceivers != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002227 for (Receiver receiver : deadReceivers) {
2228 removeUpdatesLocked(receiver);
2229 }
2230 }
2231 if (deadUpdateRecords != null) {
2232 for (UpdateRecord r : deadUpdateRecords) {
2233 r.disposeLocked(true);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002234 }
Victoria Lease8b38b292012-12-04 15:04:43 -08002235 applyRequirementsLocked(provider);
2236 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002237 }
2238
2239 private class LocationWorkerHandler extends Handler {
Victoria Lease5cd731a2012-12-19 15:04:21 -08002240 public LocationWorkerHandler(Looper looper) {
2241 super(looper, null, true);
2242 }
2243
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002244 @Override
2245 public void handleMessage(Message msg) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002246 switch (msg.what) {
2247 case MSG_LOCATION_CHANGED:
2248 handleLocationChanged((Location) msg.obj, msg.arg1 == 1);
2249 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251 }
2252 }
2253
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002254 private boolean isMockProvider(String provider) {
2255 synchronized (mLock) {
2256 return mMockProviders.containsKey(provider);
2257 }
2258 }
2259
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002260 private void handleLocationChanged(Location location, boolean passive) {
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002261 // create a working copy of the incoming Location so that the service can modify it without
2262 // disturbing the caller's copy
2263 Location myLocation = new Location(location);
2264 String provider = myLocation.getProvider();
2265
2266 // set "isFromMockProvider" bit if location came from a mock provider. we do not clear this
2267 // bit if location did not come from a mock provider because passive/fused providers can
2268 // forward locations from mock providers, and should not grant them legitimacy in doing so.
2269 if (!myLocation.isFromMockProvider() && isMockProvider(provider)) {
2270 myLocation.setIsFromMockProvider(true);
2271 }
Jeff Sharkey5e613312012-01-30 11:16:20 -08002272
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002273 synchronized (mLock) {
Victoria Lease09eeaec2013-02-05 11:34:13 -08002274 if (isAllowedByCurrentUserSettingsLocked(provider)) {
2275 if (!passive) {
2276 // notify passive provider of the new location
2277 mPassiveProvider.updateLocation(myLocation);
2278 }
Victoria Lease54ca7ae2013-01-08 09:39:50 -08002279 handleLocationChangedLocked(myLocation, passive);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002280 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002281 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002282 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002283
Mike Lockwoode97ae402010-09-29 15:23:46 -04002284 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
2285 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002286 public void onPackageDisappeared(String packageName, int reason) {
2287 // remove all receivers associated with this package name
2288 synchronized (mLock) {
2289 ArrayList<Receiver> deadReceivers = null;
2290
2291 for (Receiver receiver : mReceivers.values()) {
2292 if (receiver.mPackageName.equals(packageName)) {
2293 if (deadReceivers == null) {
2294 deadReceivers = new ArrayList<Receiver>();
2295 }
2296 deadReceivers.add(receiver);
2297 }
2298 }
2299
2300 // perform removal outside of mReceivers loop
2301 if (deadReceivers != null) {
2302 for (Receiver receiver : deadReceivers) {
2303 removeUpdatesLocked(receiver);
2304 }
2305 }
2306 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002307 }
Mike Lockwoode97ae402010-09-29 15:23:46 -04002308 };
2309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002310 // Geocoder
2311
Nick Pellye0fd6932012-07-11 10:26:13 -07002312 @Override
Mike Lockwoode15735a2010-09-20 17:48:47 -04002313 public boolean geocoderIsPresent() {
Mark Vandevoorde01ac80b2010-05-21 15:43:26 -07002314 return mGeocodeProvider != null;
2315 }
2316
Nick Pellye0fd6932012-07-11 10:26:13 -07002317 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002318 public String getFromLocation(double latitude, double longitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002319 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002320 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002321 return mGeocodeProvider.getFromLocation(latitude, longitude, maxResults,
2322 params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002323 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002324 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002325 }
2326
Mike Lockwooda55c3212009-04-15 11:10:11 -04002327
Nick Pellye0fd6932012-07-11 10:26:13 -07002328 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002329 public String getFromLocationName(String locationName,
Mike Lockwooda55c3212009-04-15 11:10:11 -04002330 double lowerLeftLatitude, double lowerLeftLongitude,
2331 double upperRightLatitude, double upperRightLongitude, int maxResults,
Mike Lockwood34901402010-01-04 12:14:21 -05002332 GeocoderParams params, List<Address> addrs) {
Mike Lockwooda55c3212009-04-15 11:10:11 -04002333
2334 if (mGeocodeProvider != null) {
Mike Lockwood628fd6d2010-01-25 22:46:13 -05002335 return mGeocodeProvider.getFromLocationName(locationName, lowerLeftLatitude,
2336 lowerLeftLongitude, upperRightLatitude, upperRightLongitude,
2337 maxResults, params, addrs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002338 }
Mike Lockwooda55c3212009-04-15 11:10:11 -04002339 return null;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002340 }
2341
2342 // Mock Providers
2343
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002344 private void checkMockPermissionsSafe() {
2345 boolean allowMocks = Settings.Secure.getInt(mContext.getContentResolver(),
2346 Settings.Secure.ALLOW_MOCK_LOCATION, 0) == 1;
2347 if (!allowMocks) {
2348 throw new SecurityException("Requires ACCESS_MOCK_LOCATION secure setting");
2349 }
2350
2351 if (mContext.checkCallingPermission(ACCESS_MOCK_LOCATION) !=
David Christie2ff96af2014-01-30 16:09:37 -08002352 PackageManager.PERMISSION_GRANTED) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002353 throw new SecurityException("Requires ACCESS_MOCK_LOCATION permission");
Nick Pellye0fd6932012-07-11 10:26:13 -07002354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002355 }
2356
Nick Pellye0fd6932012-07-11 10:26:13 -07002357 @Override
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002358 public void addTestProvider(String name, ProviderProperties properties) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002359 checkMockPermissionsSafe();
2360
Mike Lockwooda4903f22010-02-17 06:42:23 -05002361 if (LocationManager.PASSIVE_PROVIDER.equals(name)) {
2362 throw new IllegalArgumentException("Cannot mock the passive location provider");
2363 }
2364
Mike Lockwood86328a92009-10-23 08:38:25 -04002365 long identity = Binder.clearCallingIdentity();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002366 synchronized (mLock) {
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002367 // remove the real provider if we are replacing GPS or network provider
2368 if (LocationManager.GPS_PROVIDER.equals(name)
Nick Pelly1332b532012-08-21 16:25:47 -07002369 || LocationManager.NETWORK_PROVIDER.equals(name)
2370 || LocationManager.FUSED_PROVIDER.equals(name)) {
Mike Lockwoodd03ff942010-02-09 08:46:14 -05002371 LocationProviderInterface p = mProvidersByName.get(name);
2372 if (p != null) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002373 removeProviderLocked(p);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002374 }
2375 }
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002376 addTestProviderLocked(name, properties);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002377 updateProvidersLocked();
2378 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002379 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002380 }
2381
Ji-Hwan Lee26bdb8f2014-04-21 20:48:19 +09002382 private void addTestProviderLocked(String name, ProviderProperties properties) {
2383 if (mProvidersByName.get(name) != null) {
2384 throw new IllegalArgumentException("Provider \"" + name + "\" already exists");
2385 }
2386 MockProvider provider = new MockProvider(name, this, properties);
2387 addProviderLocked(provider);
2388 mMockProviders.put(name, provider);
2389 mLastLocation.put(name, null);
2390 mLastLocationCoarseInterval.put(name, null);
2391 }
2392
Nick Pellye0fd6932012-07-11 10:26:13 -07002393 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002394 public void removeTestProvider(String provider) {
2395 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002396 synchronized (mLock) {
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002397
2398 // These methods can't be called after removing the test provider, so first make sure
Tom O'Neillfe6d3c52014-03-04 08:26:17 -08002399 // we don't leave anything dangling.
Tom O'Neill07ee5d12014-03-03 17:48:35 -08002400 clearTestProviderEnabled(provider);
2401 clearTestProviderLocation(provider);
2402 clearTestProviderStatus(provider);
2403
You Kima6d0b6f2012-10-28 03:58:44 +09002404 MockProvider mockProvider = mMockProviders.remove(provider);
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002405 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002406 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2407 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002408 long identity = Binder.clearCallingIdentity();
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002409 removeProviderLocked(mProvidersByName.get(provider));
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002410
2411 // reinstate real provider if available
2412 LocationProviderInterface realProvider = mRealProviders.get(provider);
2413 if (realProvider != null) {
2414 addProviderLocked(realProvider);
Mike Lockwood7566c1d2009-08-25 10:05:18 -07002415 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002416 mLastLocation.put(provider, null);
David Christie1b9b7b12013-04-15 15:31:11 -07002417 mLastLocationCoarseInterval.put(provider, null);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002418 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002419 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002420 }
2421 }
2422
Nick Pellye0fd6932012-07-11 10:26:13 -07002423 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002424 public void setTestProviderLocation(String provider, Location loc) {
2425 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002426 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002427 MockProvider mockProvider = mMockProviders.get(provider);
2428 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002429 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2430 }
Mike Lockwood95427cd2009-05-07 13:27:54 -04002431 // clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
2432 long identity = Binder.clearCallingIdentity();
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002433 mockProvider.setLocation(loc);
Mike Lockwood95427cd2009-05-07 13:27:54 -04002434 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002435 }
2436 }
2437
Nick Pellye0fd6932012-07-11 10:26:13 -07002438 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002439 public void clearTestProviderLocation(String provider) {
2440 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002441 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002442 MockProvider mockProvider = mMockProviders.get(provider);
2443 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002444 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2445 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002446 mockProvider.clearLocation();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 }
2448 }
2449
Nick Pellye0fd6932012-07-11 10:26:13 -07002450 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002451 public void setTestProviderEnabled(String provider, boolean enabled) {
2452 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002453 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002454 MockProvider mockProvider = mMockProviders.get(provider);
2455 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002456 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2457 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002458 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002459 if (enabled) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002460 mockProvider.enable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002461 mEnabledProviders.add(provider);
2462 mDisabledProviders.remove(provider);
2463 } else {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002464 mockProvider.disable();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002465 mEnabledProviders.remove(provider);
2466 mDisabledProviders.add(provider);
2467 }
2468 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002469 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002470 }
2471 }
2472
Nick Pellye0fd6932012-07-11 10:26:13 -07002473 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002474 public void clearTestProviderEnabled(String provider) {
2475 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002476 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002477 MockProvider mockProvider = mMockProviders.get(provider);
2478 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002479 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2480 }
Mike Lockwood86328a92009-10-23 08:38:25 -04002481 long identity = Binder.clearCallingIdentity();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 mEnabledProviders.remove(provider);
2483 mDisabledProviders.remove(provider);
2484 updateProvidersLocked();
Mike Lockwood86328a92009-10-23 08:38:25 -04002485 Binder.restoreCallingIdentity(identity);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002486 }
2487 }
2488
Nick Pellye0fd6932012-07-11 10:26:13 -07002489 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002490 public void setTestProviderStatus(String provider, int status, Bundle extras, long updateTime) {
2491 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002492 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002493 MockProvider mockProvider = mMockProviders.get(provider);
2494 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002495 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2496 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002497 mockProvider.setStatus(status, extras, updateTime);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002498 }
2499 }
2500
Nick Pellye0fd6932012-07-11 10:26:13 -07002501 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002502 public void clearTestProviderStatus(String provider) {
2503 checkMockPermissionsSafe();
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002504 synchronized (mLock) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002505 MockProvider mockProvider = mMockProviders.get(provider);
2506 if (mockProvider == null) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002507 throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
2508 }
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002509 mockProvider.clearStatus();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002510 }
2511 }
2512
2513 private void log(String log) {
2514 if (Log.isLoggable(TAG, Log.VERBOSE)) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08002515 Slog.d(TAG, log);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002516 }
2517 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002518
2519 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002520 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
2521 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
2522 != PackageManager.PERMISSION_GRANTED) {
Mike Lockwood0528b9b2009-05-07 10:12:54 -04002523 pw.println("Permission Denial: can't dump LocationManagerService from from pid="
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 + Binder.getCallingPid()
2525 + ", uid=" + Binder.getCallingUid());
2526 return;
2527 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002528
Mike Lockwood2f82c4e2009-04-17 08:24:10 -04002529 synchronized (mLock) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002530 pw.println("Current Location Manager state:");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002531 pw.println(" Location Listeners:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002532 for (Receiver receiver : mReceivers.values()) {
2533 pw.println(" " + receiver);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002534 }
David Christie2ff96af2014-01-30 16:09:37 -08002535 pw.println(" Active Records by Provider:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002536 for (Map.Entry<String, ArrayList<UpdateRecord>> entry : mRecordsByProvider.entrySet()) {
2537 pw.println(" " + entry.getKey() + ":");
2538 for (UpdateRecord record : entry.getValue()) {
2539 pw.println(" " + record);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002540 }
2541 }
David Christie2ff96af2014-01-30 16:09:37 -08002542 pw.println(" Historical Records by Provider:");
2543 for (Map.Entry<PackageProviderKey, PackageStatistics> entry
2544 : mRequestStatistics.statistics.entrySet()) {
2545 PackageProviderKey key = entry.getKey();
2546 PackageStatistics stats = entry.getValue();
2547 pw.println(" " + key.packageName + ": " + key.providerName + ": " + stats);
2548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002549 pw.println(" Last Known Locations:");
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002550 for (Map.Entry<String, Location> entry : mLastLocation.entrySet()) {
2551 String provider = entry.getKey();
2552 Location location = entry.getValue();
2553 pw.println(" " + provider + ": " + location);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002554 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002555
David Christie1b9b7b12013-04-15 15:31:11 -07002556 pw.println(" Last Known Locations Coarse Intervals:");
2557 for (Map.Entry<String, Location> entry : mLastLocationCoarseInterval.entrySet()) {
2558 String provider = entry.getKey();
2559 Location location = entry.getValue();
2560 pw.println(" " + provider + ": " + location);
2561 }
2562
Nick Pellye0fd6932012-07-11 10:26:13 -07002563 mGeofenceManager.dump(pw);
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002564
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 if (mEnabledProviders.size() > 0) {
2566 pw.println(" Enabled Providers:");
2567 for (String i : mEnabledProviders) {
2568 pw.println(" " + i);
2569 }
Nick Pellye0fd6932012-07-11 10:26:13 -07002570
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002571 }
2572 if (mDisabledProviders.size() > 0) {
2573 pw.println(" Disabled Providers:");
2574 for (String i : mDisabledProviders) {
2575 pw.println(" " + i);
2576 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002577 }
Nick Pelly4035f5a2012-08-17 14:43:49 -07002578 pw.append(" ");
2579 mBlacklist.dump(pw);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002580 if (mMockProviders.size() > 0) {
2581 pw.println(" Mock Providers:");
2582 for (Map.Entry<String, MockProvider> i : mMockProviders.entrySet()) {
Mike Lockwood7ec434e2009-03-27 07:46:48 -07002583 i.getValue().dump(pw, " ");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002584 }
2585 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002586
Nick Pelly74fa7ea2012-08-13 19:36:38 -07002587 pw.append(" fudger: ");
2588 mLocationFudger.dump(fd, pw, args);
2589
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002590 if (args.length > 0 && "short".equals(args[0])) {
2591 return;
2592 }
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002593 for (LocationProviderInterface provider: mProviders) {
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002594 pw.print(provider.getName() + " Internal State");
2595 if (provider instanceof LocationProviderProxy) {
2596 LocationProviderProxy proxy = (LocationProviderProxy) provider;
2597 pw.print(" (" + proxy.getConnectedPackageName() + ")");
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002598 }
Nick Pelly6fa9ad42012-07-16 12:18:23 -07002599 pw.println(":");
2600 provider.dump(fd, pw, args);
Fred Fettinger3c8fbdf2010-01-04 15:38:13 -06002601 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002602 }
2603 }
2604}