1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512
|
package com.android.server.location.geofence;
import static android.location.LocationManager.FUSED_PROVIDER; import static android.location.LocationManager.KEY_PROXIMITY_ENTERING;
import static com.android.internal.util.ConcurrentUtils.DIRECT_EXECUTOR; import static com.android.server.location.LocationPermissions.PERMISSION_FINE;
import android.annotation.Nullable; import android.app.AppOpsManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.location.Geofence; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationRequest; import android.location.util.identity.CallerIdentity; import android.os.Binder; import android.os.PowerManager; import android.os.SystemClock; import android.os.WorkSource; import android.stats.location.LocationStatsEnums; import android.util.ArraySet;
import com.android.internal.annotations.GuardedBy; import com.android.server.PendingIntentUtils; import com.android.server.location.LocationPermissions; import com.android.server.location.injector.Injector; import com.android.server.location.injector.LocationPermissionsHelper; import com.android.server.location.injector.LocationUsageLogger; import com.android.server.location.injector.SettingsHelper; import com.android.server.location.injector.UserInfoHelper; import com.android.server.location.injector.UserInfoHelper.UserListener; import com.android.server.location.listeners.ListenerMultiplexer; import com.android.server.location.listeners.PendingIntentListenerRegistration;
import java.util.Collection; import java.util.Objects;
public class GeofenceManager extends ListenerMultiplexer<GeofenceKey, PendingIntent, GeofenceManager.GeofenceRegistration, LocationRequest> implements LocationListener {
private static final String TAG = "GeofenceManager";
private static final String ATTRIBUTION_TAG = "GeofencingService";
private static final long WAKELOCK_TIMEOUT_MS = 30000;
private static final int MAX_SPEED_M_S = 100; private static final long MAX_LOCATION_AGE_MS = 5 * 60 * 1000L; private static final long MAX_LOCATION_INTERVAL_MS = 2 * 60 * 60 * 1000;
protected final class GeofenceRegistration extends PendingIntentListenerRegistration<Geofence, PendingIntent> {
private static final int STATE_UNKNOWN = 0; private static final int STATE_INSIDE = 1; private static final int STATE_OUTSIDE = 2;
private final Location mCenter; private final PowerManager.WakeLock mWakeLock;
private int mGeofenceState;
private boolean mPermitted;
private @Nullable Location mCachedLocation; private float mCachedLocationDistanceM;
protected GeofenceRegistration(Geofence geofence, CallerIdentity identity, PendingIntent pendingIntent) { super(geofence, identity, pendingIntent);
mCenter = new Location(""); mCenter.setLatitude(geofence.getLatitude()); mCenter.setLongitude(geofence.getLongitude());
mWakeLock = Objects.requireNonNull(mContext.getSystemService(PowerManager.class)) .newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG + ":" + identity.getPackageName()); mWakeLock.setReferenceCounted(true); mWakeLock.setWorkSource(identity.addToWorkSource(null)); }
@Override protected GeofenceManager getOwner() { return GeofenceManager.this; }
@Override protected void onPendingIntentListenerRegister() { mGeofenceState = STATE_UNKNOWN; mPermitted = mLocationPermissionsHelper.hasLocationPermissions(PERMISSION_FINE, getIdentity()); }
@Override protected void onActive() { Location location = getLastLocation(); if (location != null) { executeOperation(onLocationChanged(location)); } }
boolean isPermitted() { return mPermitted; }
boolean onLocationPermissionsChanged(String packageName) { if (getIdentity().getPackageName().equals(packageName)) { return onLocationPermissionsChanged(); }
return false; }
boolean onLocationPermissionsChanged(int uid) { if (getIdentity().getUid() == uid) { return onLocationPermissionsChanged(); }
return false; }
private boolean onLocationPermissionsChanged() { boolean permitted = mLocationPermissionsHelper.hasLocationPermissions(PERMISSION_FINE, getIdentity()); if (permitted != mPermitted) { mPermitted = permitted; return true; }
return false; }
double getDistanceToBoundary(Location location) { if (!location.equals(mCachedLocation)) { mCachedLocation = location; mCachedLocationDistanceM = mCenter.distanceTo(mCachedLocation); }
return Math.abs(getRequest().getRadius() - mCachedLocationDistanceM); }
ListenerOperation<PendingIntent> onLocationChanged(Location location) { if (getRequest().isExpired()) { remove(); return null; }
mCachedLocation = location; mCachedLocationDistanceM = mCenter.distanceTo(mCachedLocation);
int oldState = mGeofenceState; float radius = Math.max(getRequest().getRadius(), location.getAccuracy()); if (mCachedLocationDistanceM <= radius) { mGeofenceState = STATE_INSIDE; if (oldState != STATE_INSIDE) { return pendingIntent -> sendIntent(pendingIntent, true); } } else { mGeofenceState = STATE_OUTSIDE; if (oldState == STATE_INSIDE) { return pendingIntent -> sendIntent(pendingIntent, false); } }
return null; }
private void sendIntent(PendingIntent pendingIntent, boolean entering) { Intent intent = new Intent().putExtra(KEY_PROXIMITY_ENTERING, entering);
mWakeLock.acquire(WAKELOCK_TIMEOUT_MS); try { pendingIntent.send(mContext, 0, intent, (pI, i, rC, rD, rE) -> mWakeLock.release(), null, null, PendingIntentUtils.createDontSendToRestrictedAppsBundle(null)); } catch (PendingIntent.CanceledException e) { mWakeLock.release(); removeRegistration(new GeofenceKey(pendingIntent, getRequest()), this); } }
@Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(getIdentity());
ArraySet<String> flags = new ArraySet<>(1); if (!mPermitted) { flags.add("na"); } if (!flags.isEmpty()) { builder.append(" ").append(flags); }
builder.append(" ").append(getRequest()); return builder.toString(); } }
final Object mLock = new Object();
protected final Context mContext;
private final UserListener mUserChangedListener = this::onUserChanged; private final SettingsHelper.UserSettingChangedListener mLocationEnabledChangedListener = this::onLocationEnabledChanged; private final SettingsHelper.UserSettingChangedListener mLocationPackageBlacklistChangedListener = this::onLocationPackageBlacklistChanged; private final LocationPermissionsHelper.LocationPermissionsListener mLocationPermissionsListener = new LocationPermissionsHelper.LocationPermissionsListener() { @Override public void onLocationPermissionsChanged(String packageName) { GeofenceManager.this.onLocationPermissionsChanged(packageName); }
@Override public void onLocationPermissionsChanged(int uid) { GeofenceManager.this.onLocationPermissionsChanged(uid); } };
protected final UserInfoHelper mUserInfoHelper; protected final LocationPermissionsHelper mLocationPermissionsHelper; protected final SettingsHelper mSettingsHelper; protected final LocationUsageLogger mLocationUsageLogger;
@GuardedBy("mLock") private @Nullable LocationManager mLocationManager;
@GuardedBy("mLock") private @Nullable Location mLastLocation;
public GeofenceManager(Context context, Injector injector) { mContext = context.createAttributionContext(ATTRIBUTION_TAG); mUserInfoHelper = injector.getUserInfoHelper(); mSettingsHelper = injector.getSettingsHelper(); mLocationPermissionsHelper = injector.getLocationPermissionsHelper(); mLocationUsageLogger = injector.getLocationUsageLogger(); }
@Override public String getTag() { return TAG; }
private LocationManager getLocationManager() { synchronized (mLock) { if (mLocationManager == null) { mLocationManager = Objects.requireNonNull( mContext.getSystemService(LocationManager.class)); }
return mLocationManager; } }
public void addGeofence(Geofence geofence, PendingIntent pendingIntent, String packageName, @Nullable String attributionTag) { LocationPermissions.enforceCallingOrSelfLocationPermission(mContext, PERMISSION_FINE);
CallerIdentity identity = CallerIdentity.fromBinder(mContext, packageName, attributionTag, AppOpsManager.toReceiverId(pendingIntent));
final long ident = Binder.clearCallingIdentity(); try { putRegistration(new GeofenceKey(pendingIntent, geofence), new GeofenceRegistration(geofence, identity, pendingIntent)); } finally { Binder.restoreCallingIdentity(ident); } }
public void removeGeofence(PendingIntent pendingIntent) { final long identity = Binder.clearCallingIdentity(); try { removeRegistrationIf(key -> key.getPendingIntent().equals(pendingIntent)); } finally { Binder.restoreCallingIdentity(identity); } }
@Override protected boolean isActive(GeofenceRegistration registration) { return registration.isPermitted() && isActive(registration.getIdentity()); }
private boolean isActive(CallerIdentity identity) { if (identity.isSystemServer()) { if (!mSettingsHelper.isLocationEnabled(mUserInfoHelper.getCurrentUserId())) { return false; } } else { if (!mSettingsHelper.isLocationEnabled(identity.getUserId())) { return false; } if (!mUserInfoHelper.isCurrentUserId(identity.getUserId())) { return false; } if (mSettingsHelper.isLocationPackageBlacklisted(identity.getUserId(), identity.getPackageName())) { return false; } }
return true; }
@Override protected void onRegister() { mUserInfoHelper.addListener(mUserChangedListener); mSettingsHelper.addOnLocationEnabledChangedListener(mLocationEnabledChangedListener); mSettingsHelper.addOnLocationPackageBlacklistChangedListener( mLocationPackageBlacklistChangedListener); mLocationPermissionsHelper.addListener(mLocationPermissionsListener); }
@Override protected void onUnregister() { mUserInfoHelper.removeListener(mUserChangedListener); mSettingsHelper.removeOnLocationEnabledChangedListener(mLocationEnabledChangedListener); mSettingsHelper.removeOnLocationPackageBlacklistChangedListener( mLocationPackageBlacklistChangedListener); mLocationPermissionsHelper.removeListener(mLocationPermissionsListener); }
@Override protected void onRegistrationAdded(GeofenceKey key, GeofenceRegistration registration) { mLocationUsageLogger.logLocationApiUsage( LocationStatsEnums.USAGE_ENDED, LocationStatsEnums.API_REQUEST_GEOFENCE, registration.getIdentity().getPackageName(), registration.getIdentity().getAttributionTag(), null, null, false, true, registration.getRequest(), true); }
@Override protected void onRegistrationRemoved(GeofenceKey key, GeofenceRegistration registration) { mLocationUsageLogger.logLocationApiUsage( LocationStatsEnums.USAGE_ENDED, LocationStatsEnums.API_REQUEST_GEOFENCE, registration.getIdentity().getPackageName(), registration.getIdentity().getAttributionTag(), null, null, false, true, registration.getRequest(), true); }
@Override protected boolean registerWithService(LocationRequest locationRequest, Collection<GeofenceRegistration> registrations) { getLocationManager().requestLocationUpdates(FUSED_PROVIDER, locationRequest, DIRECT_EXECUTOR, this); return true; }
@Override protected void unregisterWithService() { synchronized (mLock) { getLocationManager().removeUpdates(this); mLastLocation = null; } }
@Override protected LocationRequest mergeRegistrations(Collection<GeofenceRegistration> registrations) { Location location = getLastLocation();
long realtimeMs = SystemClock.elapsedRealtime();
WorkSource workSource = null; double minFenceDistanceM = Double.MAX_VALUE; for (GeofenceRegistration registration : registrations) { if (registration.getRequest().isExpired(realtimeMs)) { continue; }
workSource = registration.getIdentity().addToWorkSource(workSource);
if (location != null) { double fenceDistanceM = registration.getDistanceToBoundary(location); if (fenceDistanceM < minFenceDistanceM) { minFenceDistanceM = fenceDistanceM; } } }
long intervalMs; if (Double.compare(minFenceDistanceM, Double.MAX_VALUE) < 0) { intervalMs = (long) Math.min(MAX_LOCATION_INTERVAL_MS, Math.max( mSettingsHelper.getBackgroundThrottleProximityAlertIntervalMs(), minFenceDistanceM * 1000 / MAX_SPEED_M_S)); } else { intervalMs = mSettingsHelper.getBackgroundThrottleProximityAlertIntervalMs(); }
return new LocationRequest.Builder(intervalMs) .setMinUpdateIntervalMillis(0) .setHiddenFromAppOps(true) .setWorkSource(workSource) .build(); }
@Override public void onLocationChanged(Location location) { synchronized (mLock) { mLastLocation = location; }
deliverToListeners(registration -> { return registration.onLocationChanged(location); }); updateService(); }
@Nullable Location getLastLocation() { Location location; synchronized (mLock) { location = mLastLocation; }
if (location == null) { location = getLocationManager().getLastLocation(); }
if (location != null) { if (location.getElapsedRealtimeAgeMillis() > MAX_LOCATION_AGE_MS) { location = null; } }
return location; }
void onUserChanged(int userId, int change) { if (change == UserListener.CURRENT_USER_CHANGED) { updateRegistrations(registration -> registration.getIdentity().getUserId() == userId); } }
void onLocationEnabledChanged(int userId) { updateRegistrations(registration -> registration.getIdentity().getUserId() == userId); }
void onLocationPackageBlacklistChanged(int userId) { updateRegistrations(registration -> registration.getIdentity().getUserId() == userId); }
void onLocationPermissionsChanged(String packageName) { updateRegistrations(registration -> registration.onLocationPermissionsChanged(packageName)); }
void onLocationPermissionsChanged(int uid) { updateRegistrations(registration -> registration.onLocationPermissionsChanged(uid)); } }
|