1 /* 2 * Copyright (C) 2006 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 17 package com.android.server.am; 18 19 import static android.app.PendingIntent.FLAG_IMMUTABLE; 20 import static android.app.PendingIntent.FLAG_UPDATE_CURRENT; 21 import static android.os.PowerExemptionManager.REASON_DENIED; 22 23 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_FOREGROUND_SERVICE; 24 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM; 25 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME; 26 import static com.android.server.am.ProcessProfileRecord.HOSTING_COMPONENT_TYPE_BOUND_SERVICE; 27 28 import android.annotation.NonNull; 29 import android.annotation.Nullable; 30 import android.app.IApplicationThread; 31 import android.app.Notification; 32 import android.app.PendingIntent; 33 import android.app.RemoteServiceException.CannotPostForegroundServiceNotificationException; 34 import android.content.ComponentName; 35 import android.content.Context; 36 import android.content.Intent; 37 import android.content.pm.ApplicationInfo; 38 import android.content.pm.PackageManager; 39 import android.content.pm.ServiceInfo; 40 import android.net.Uri; 41 import android.os.Binder; 42 import android.os.Build; 43 import android.os.IBinder; 44 import android.os.PowerExemptionManager; 45 import android.os.SystemClock; 46 import android.os.UserHandle; 47 import android.provider.Settings; 48 import android.util.ArrayMap; 49 import android.util.Slog; 50 import android.util.TimeUtils; 51 import android.util.proto.ProtoOutputStream; 52 import android.util.proto.ProtoUtils; 53 54 import com.android.internal.annotations.GuardedBy; 55 import com.android.internal.app.procstats.ServiceState; 56 import com.android.server.LocalServices; 57 import com.android.server.notification.NotificationManagerInternal; 58 import com.android.server.uri.NeededUriGrants; 59 import com.android.server.uri.UriPermissionOwner; 60 61 import java.io.PrintWriter; 62 import java.util.ArrayList; 63 import java.util.List; 64 import java.util.Objects; 65 66 /** 67 * A running application service. 68 */ 69 final class ServiceRecord extends Binder implements ComponentName.WithComponentName { 70 private static final String TAG = TAG_WITH_CLASS_NAME ? "ServiceRecord" : TAG_AM; 71 72 // Maximum number of delivery attempts before giving up. 73 static final int MAX_DELIVERY_COUNT = 3; 74 75 // Maximum number of times it can fail during execution before giving up. 76 static final int MAX_DONE_EXECUTING_COUNT = 6; 77 78 final ActivityManagerService ams; 79 final ComponentName name; // service component. 80 final ComponentName instanceName; // service component's per-instance name. 81 final String shortInstanceName; // instanceName.flattenToShortString(). 82 final String definingPackageName; 83 // Can be different from appInfo.packageName for external services 84 final int definingUid; 85 // Can be different from appInfo.uid for external services 86 final Intent.FilterComparison intent; 87 // original intent used to find service. 88 final ServiceInfo serviceInfo; 89 // all information about the service. 90 ApplicationInfo appInfo; 91 // information about service's app. 92 final int userId; // user that this service is running as 93 final String packageName; // the package implementing intent's component 94 final String processName; // process where this component wants to run 95 final String permission;// permission needed to access service 96 final boolean exported; // from ServiceInfo.exported 97 final Runnable restarter; // used to schedule retries of starting the service 98 final long createRealTime; // when this service was created 99 final boolean isSdkSandbox; // whether this is a sdk sandbox service 100 final int sdkSandboxClientAppUid; // the app uid for which this sdk sandbox service is running 101 final String sdkSandboxClientAppPackage; // the app package for which this sdk sandbox service 102 // is running 103 final ArrayMap<Intent.FilterComparison, IntentBindRecord> bindings 104 = new ArrayMap<Intent.FilterComparison, IntentBindRecord>(); 105 // All active bindings to the service. 106 private final ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections 107 = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>(); 108 // IBinder -> ConnectionRecord of all bound clients 109 110 ProcessRecord app; // where this service is running or null. 111 ProcessRecord isolationHostProc; // process which we've started for this service (used for 112 // isolated and sdk sandbox processes) 113 ServiceState tracker; // tracking service execution, may be null 114 ServiceState restartTracker; // tracking service restart 115 boolean allowlistManager; // any bindings to this service have BIND_ALLOW_WHITELIST_MANAGEMENT? 116 boolean delayed; // are we waiting to start this service in the background? 117 boolean fgRequired; // is the service required to go foreground after starting? 118 boolean fgWaiting; // is a timeout for going foreground already scheduled? 119 boolean isNotAppComponentUsage; // is service binding not considered component/package usage? 120 boolean isForeground; // is service currently in foreground mode? 121 int foregroundId; // Notification ID of last foreground req. 122 Notification foregroundNoti; // Notification record of foreground state. 123 long fgDisplayTime; // time at which the FGS notification should become visible 124 int foregroundServiceType; // foreground service types. 125 long lastActivity; // last time there was some activity on the service. 126 long startingBgTimeout; // time at which we scheduled this for a delayed start. 127 boolean startRequested; // someone explicitly called start? 128 boolean delayedStop; // service has been stopped but is in a delayed start? 129 boolean stopIfKilled; // last onStart() said to stop if service killed? 130 boolean callStart; // last onStart() has asked to always be called on restart. 131 int executeNesting; // number of outstanding operations keeping foreground. 132 boolean executeFg; // should we be executing in the foreground? 133 long executingStart; // start time of last execute request. 134 boolean createdFromFg; // was this service last created due to a foreground process call? 135 int crashCount; // number of times proc has crashed with service running 136 int totalRestartCount; // number of times we have had to restart. 137 int restartCount; // number of restarts performed in a row. 138 long restartDelay; // delay until next restart attempt. 139 long restartTime; // time of last restart. 140 long nextRestartTime; // time when restartDelay will expire. 141 boolean destroying; // set when we have started destroying the service 142 long destroyTime; // time at which destory was initiated. 143 int pendingConnectionGroup; // To be filled in to ProcessRecord once it connects 144 int pendingConnectionImportance; // To be filled in to ProcessRecord once it connects 145 146 /** 147 * The last time (in uptime timebase) a bind request was made with BIND_ALMOST_PERCEPTIBLE for 148 * this service while on TOP. 149 */ 150 long lastTopAlmostPerceptibleBindRequestUptimeMs; 151 152 // any current binding to this service has BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS flag? 153 private boolean mIsAllowedBgActivityStartsByBinding; 154 // is this service currently allowed to start activities from background by providing 155 // allowBackgroundActivityStarts=true to startServiceLocked()? 156 private boolean mIsAllowedBgActivityStartsByStart; 157 // used to clean up the state of mIsAllowedBgActivityStartsByStart after a timeout 158 private Runnable mCleanUpAllowBgActivityStartsByStartCallback; 159 private ProcessRecord mAppForAllowingBgActivityStartsByStart; 160 // These are the originating tokens that currently allow bg activity starts by service start. 161 // This is used to trace back the grant when starting activities. We only pass such token to the 162 // ProcessRecord if it's the *only* cause for bg activity starts exemption, otherwise we pass 163 // null. 164 @GuardedBy("ams") 165 private List<IBinder> mBgActivityStartsByStartOriginatingTokens = new ArrayList<>(); 166 167 // allow while-in-use permissions in foreground service or not. 168 // while-in-use permissions in FGS started from background might be restricted. 169 boolean mAllowWhileInUsePermissionInFgs; 170 // A copy of mAllowWhileInUsePermissionInFgs's value when the service is entering FGS state. 171 boolean mAllowWhileInUsePermissionInFgsAtEntering; 172 173 // the most recent package that start/bind this service. 174 String mRecentCallingPackage; 175 // the most recent uid that start/bind this service. 176 int mRecentCallingUid; 177 // ApplicationInfo of the most recent callingPackage that start/bind this service. 178 @Nullable ApplicationInfo mRecentCallerApplicationInfo; 179 180 // The uptime when the service enters FGS state. 181 long mFgsEnterTime = 0; 182 // The uptime when the service exits FGS state. 183 long mFgsExitTime = 0; 184 // FGS notification is deferred. 185 boolean mFgsNotificationDeferred; 186 // FGS notification was deferred. 187 boolean mFgsNotificationWasDeferred; 188 // FGS notification was shown before the FGS finishes, or it wasn't deferred in the first place. 189 boolean mFgsNotificationShown; 190 // Whether FGS package has permissions to show notifications. 191 boolean mFgsHasNotificationPermission; 192 193 // allow the service becomes foreground service? Service started from background may not be 194 // allowed to become a foreground service. 195 @PowerExemptionManager.ReasonCode int mAllowStartForeground = REASON_DENIED; 196 // A copy of mAllowStartForeground's value when the service is entering FGS state. 197 @PowerExemptionManager.ReasonCode int mAllowStartForegroundAtEntering = REASON_DENIED; 198 // Debug info why mAllowStartForeground is allowed or denied. 199 String mInfoAllowStartForeground; 200 // Debug info if mAllowStartForeground is allowed because of a temp-allowlist. 201 ActivityManagerService.FgsTempAllowListItem mInfoTempFgsAllowListReason; 202 // Is the same mInfoAllowStartForeground string has been logged before? Used for dedup. 203 boolean mLoggedInfoAllowStartForeground; 204 // The number of times Service.startForeground() is called; 205 int mStartForegroundCount; 206 // Last time mAllowWhileInUsePermissionInFgs or mAllowStartForeground is set. 207 long mLastSetFgsRestrictionTime; 208 209 String stringName; // caching of toString 210 211 private int lastStartId; // identifier of most recent start request. 212 213 boolean mKeepWarming; // Whether or not it'll keep critical code path of the host warm 214 215 /** 216 * The original earliest restart time, which considers the number of crashes, etc., 217 * but doesn't include the extra delays we put in between to scatter the restarts; 218 * it's the earliest time this auto service restart could happen alone(except those 219 * batch restarts which happens at time of process attach). 220 */ 221 long mEarliestRestartTime; 222 223 /** 224 * The original time when the service start is scheduled, it does NOT include the reschedules. 225 * 226 * <p>The {@link #restartDelay} would be updated when its restart is rescheduled, but this field 227 * won't, so it could be used when dumping how long the restart is delayed actually.</p> 228 */ 229 long mRestartSchedulingTime; 230 231 static class StartItem { 232 final ServiceRecord sr; 233 final boolean taskRemoved; 234 final int id; 235 final int callingId; 236 final Intent intent; 237 final NeededUriGrants neededGrants; 238 long deliveredTime; 239 int deliveryCount; 240 int doneExecutingCount; 241 UriPermissionOwner uriPermissions; 242 243 String stringName; // caching of toString 244 StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent, NeededUriGrants _neededGrants, int _callingId)245 StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent, 246 NeededUriGrants _neededGrants, int _callingId) { 247 sr = _sr; 248 taskRemoved = _taskRemoved; 249 id = _id; 250 intent = _intent; 251 neededGrants = _neededGrants; 252 callingId = _callingId; 253 } 254 getUriPermissionsLocked()255 UriPermissionOwner getUriPermissionsLocked() { 256 if (uriPermissions == null) { 257 uriPermissions = new UriPermissionOwner(sr.ams.mUgmInternal, this); 258 } 259 return uriPermissions; 260 } 261 removeUriPermissionsLocked()262 void removeUriPermissionsLocked() { 263 if (uriPermissions != null) { 264 uriPermissions.removeUriPermissions(); 265 uriPermissions = null; 266 } 267 } 268 dumpDebug(ProtoOutputStream proto, long fieldId, long now)269 public void dumpDebug(ProtoOutputStream proto, long fieldId, long now) { 270 long token = proto.start(fieldId); 271 proto.write(ServiceRecordProto.StartItem.ID, id); 272 ProtoUtils.toDuration(proto, 273 ServiceRecordProto.StartItem.DURATION, deliveredTime, now); 274 proto.write(ServiceRecordProto.StartItem.DELIVERY_COUNT, deliveryCount); 275 proto.write(ServiceRecordProto.StartItem.DONE_EXECUTING_COUNT, doneExecutingCount); 276 if (intent != null) { 277 intent.dumpDebug(proto, ServiceRecordProto.StartItem.INTENT, true, true, 278 true, false); 279 } 280 if (neededGrants != null) { 281 neededGrants.dumpDebug(proto, ServiceRecordProto.StartItem.NEEDED_GRANTS); 282 } 283 if (uriPermissions != null) { 284 uriPermissions.dumpDebug(proto, ServiceRecordProto.StartItem.URI_PERMISSIONS); 285 } 286 proto.end(token); 287 } 288 toString()289 public String toString() { 290 if (stringName != null) { 291 return stringName; 292 } 293 StringBuilder sb = new StringBuilder(128); 294 sb.append("ServiceRecord{") 295 .append(Integer.toHexString(System.identityHashCode(sr))) 296 .append(' ').append(sr.shortInstanceName) 297 .append(" StartItem ") 298 .append(Integer.toHexString(System.identityHashCode(this))) 299 .append(" id=").append(id).append('}'); 300 return stringName = sb.toString(); 301 } 302 } 303 304 final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>(); 305 // start() arguments which been delivered. 306 final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>(); 307 // start() arguments that haven't yet been delivered. 308 dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now)309 void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) { 310 final int N = list.size(); 311 for (int i=0; i<N; i++) { 312 StartItem si = list.get(i); 313 pw.print(prefix); pw.print("#"); pw.print(i); 314 pw.print(" id="); pw.print(si.id); 315 if (now != 0) { 316 pw.print(" dur="); 317 TimeUtils.formatDuration(si.deliveredTime, now, pw); 318 } 319 if (si.deliveryCount != 0) { 320 pw.print(" dc="); pw.print(si.deliveryCount); 321 } 322 if (si.doneExecutingCount != 0) { 323 pw.print(" dxc="); pw.print(si.doneExecutingCount); 324 } 325 pw.println(""); 326 pw.print(prefix); pw.print(" intent="); 327 if (si.intent != null) pw.println(si.intent.toString()); 328 else pw.println("null"); 329 if (si.neededGrants != null) { 330 pw.print(prefix); pw.print(" neededGrants="); 331 pw.println(si.neededGrants); 332 } 333 if (si.uriPermissions != null) { 334 si.uriPermissions.dump(pw, prefix); 335 } 336 } 337 } 338 dumpDebug(ProtoOutputStream proto, long fieldId)339 void dumpDebug(ProtoOutputStream proto, long fieldId) { 340 long token = proto.start(fieldId); 341 proto.write(ServiceRecordProto.SHORT_NAME, this.shortInstanceName); 342 proto.write(ServiceRecordProto.IS_RUNNING, app != null); 343 if (app != null) { 344 proto.write(ServiceRecordProto.PID, app.getPid()); 345 } 346 if (intent != null) { 347 intent.getIntent().dumpDebug(proto, ServiceRecordProto.INTENT, false, true, false, 348 false); 349 } 350 proto.write(ServiceRecordProto.PACKAGE_NAME, packageName); 351 proto.write(ServiceRecordProto.PROCESS_NAME, processName); 352 proto.write(ServiceRecordProto.PERMISSION, permission); 353 354 long now = SystemClock.uptimeMillis(); 355 long nowReal = SystemClock.elapsedRealtime(); 356 if (appInfo != null) { 357 long appInfoToken = proto.start(ServiceRecordProto.APPINFO); 358 proto.write(ServiceRecordProto.AppInfo.BASE_DIR, appInfo.sourceDir); 359 if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) { 360 proto.write(ServiceRecordProto.AppInfo.RES_DIR, appInfo.publicSourceDir); 361 } 362 proto.write(ServiceRecordProto.AppInfo.DATA_DIR, appInfo.dataDir); 363 proto.end(appInfoToken); 364 } 365 if (app != null) { 366 app.dumpDebug(proto, ServiceRecordProto.APP); 367 } 368 if (isolationHostProc != null) { 369 isolationHostProc.dumpDebug(proto, ServiceRecordProto.ISOLATED_PROC); 370 } 371 proto.write(ServiceRecordProto.WHITELIST_MANAGER, allowlistManager); 372 proto.write(ServiceRecordProto.DELAYED, delayed); 373 if (isForeground || foregroundId != 0) { 374 long fgToken = proto.start(ServiceRecordProto.FOREGROUND); 375 proto.write(ServiceRecordProto.Foreground.ID, foregroundId); 376 foregroundNoti.dumpDebug(proto, ServiceRecordProto.Foreground.NOTIFICATION); 377 proto.end(fgToken); 378 } 379 ProtoUtils.toDuration(proto, ServiceRecordProto.CREATE_REAL_TIME, createRealTime, nowReal); 380 ProtoUtils.toDuration(proto, 381 ServiceRecordProto.STARTING_BG_TIMEOUT, startingBgTimeout, now); 382 ProtoUtils.toDuration(proto, ServiceRecordProto.LAST_ACTIVITY_TIME, lastActivity, now); 383 ProtoUtils.toDuration(proto, ServiceRecordProto.RESTART_TIME, restartTime, now); 384 proto.write(ServiceRecordProto.CREATED_FROM_FG, createdFromFg); 385 proto.write(ServiceRecordProto.ALLOW_WHILE_IN_USE_PERMISSION_IN_FGS, 386 mAllowWhileInUsePermissionInFgs); 387 388 if (startRequested || delayedStop || lastStartId != 0) { 389 long startToken = proto.start(ServiceRecordProto.START); 390 proto.write(ServiceRecordProto.Start.START_REQUESTED, startRequested); 391 proto.write(ServiceRecordProto.Start.DELAYED_STOP, delayedStop); 392 proto.write(ServiceRecordProto.Start.STOP_IF_KILLED, stopIfKilled); 393 proto.write(ServiceRecordProto.Start.LAST_START_ID, lastStartId); 394 proto.end(startToken); 395 } 396 397 if (executeNesting != 0) { 398 long executNestingToken = proto.start(ServiceRecordProto.EXECUTE); 399 proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_NESTING, executeNesting); 400 proto.write(ServiceRecordProto.ExecuteNesting.EXECUTE_FG, executeFg); 401 ProtoUtils.toDuration(proto, 402 ServiceRecordProto.ExecuteNesting.EXECUTING_START, executingStart, now); 403 proto.end(executNestingToken); 404 } 405 if (destroying || destroyTime != 0) { 406 ProtoUtils.toDuration(proto, ServiceRecordProto.DESTORY_TIME, destroyTime, now); 407 } 408 if (crashCount != 0 || restartCount != 0 || (nextRestartTime - mRestartSchedulingTime) != 0 409 || nextRestartTime != 0) { 410 long crashToken = proto.start(ServiceRecordProto.CRASH); 411 proto.write(ServiceRecordProto.Crash.RESTART_COUNT, restartCount); 412 ProtoUtils.toDuration(proto, ServiceRecordProto.Crash.RESTART_DELAY, 413 (nextRestartTime - mRestartSchedulingTime), now); 414 ProtoUtils.toDuration(proto, 415 ServiceRecordProto.Crash.NEXT_RESTART_TIME, nextRestartTime, now); 416 proto.write(ServiceRecordProto.Crash.CRASH_COUNT, crashCount); 417 proto.end(crashToken); 418 } 419 420 if (deliveredStarts.size() > 0) { 421 final int N = deliveredStarts.size(); 422 for (int i = 0; i < N; i++) { 423 deliveredStarts.get(i).dumpDebug(proto, 424 ServiceRecordProto.DELIVERED_STARTS, now); 425 } 426 } 427 if (pendingStarts.size() > 0) { 428 final int N = pendingStarts.size(); 429 for (int i = 0; i < N; i++) { 430 pendingStarts.get(i).dumpDebug(proto, ServiceRecordProto.PENDING_STARTS, now); 431 } 432 } 433 if (bindings.size() > 0) { 434 final int N = bindings.size(); 435 for (int i=0; i<N; i++) { 436 IntentBindRecord b = bindings.valueAt(i); 437 b.dumpDebug(proto, ServiceRecordProto.BINDINGS); 438 } 439 } 440 if (connections.size() > 0) { 441 final int N = connections.size(); 442 for (int conni=0; conni<N; conni++) { 443 ArrayList<ConnectionRecord> c = connections.valueAt(conni); 444 for (int i=0; i<c.size(); i++) { 445 c.get(i).dumpDebug(proto, ServiceRecordProto.CONNECTIONS); 446 } 447 } 448 } 449 proto.end(token); 450 } 451 dump(PrintWriter pw, String prefix)452 void dump(PrintWriter pw, String prefix) { 453 pw.print(prefix); pw.print("intent={"); 454 pw.print(intent.getIntent().toShortString(false, true, false, false)); 455 pw.println('}'); 456 pw.print(prefix); pw.print("packageName="); pw.println(packageName); 457 pw.print(prefix); pw.print("processName="); pw.println(processName); 458 if (permission != null) { 459 pw.print(prefix); pw.print("permission="); pw.println(permission); 460 } 461 long now = SystemClock.uptimeMillis(); 462 long nowReal = SystemClock.elapsedRealtime(); 463 if (appInfo != null) { 464 pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir); 465 if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) { 466 pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir); 467 } 468 pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir); 469 } 470 pw.print(prefix); pw.print("app="); pw.println(app); 471 if (isolationHostProc != null) { 472 pw.print(prefix); pw.print("isolationHostProc="); pw.println(isolationHostProc); 473 } 474 if (allowlistManager) { 475 pw.print(prefix); pw.print("allowlistManager="); pw.println(allowlistManager); 476 } 477 if (mIsAllowedBgActivityStartsByBinding) { 478 pw.print(prefix); pw.print("mIsAllowedBgActivityStartsByBinding="); 479 pw.println(mIsAllowedBgActivityStartsByBinding); 480 } 481 if (mIsAllowedBgActivityStartsByStart) { 482 pw.print(prefix); pw.print("mIsAllowedBgActivityStartsByStart="); 483 pw.println(mIsAllowedBgActivityStartsByStart); 484 } 485 pw.print(prefix); pw.print("allowWhileInUsePermissionInFgs="); 486 pw.println(mAllowWhileInUsePermissionInFgs); 487 pw.print(prefix); pw.print("recentCallingPackage="); 488 pw.println(mRecentCallingPackage); 489 pw.print(prefix); pw.print("recentCallingUid="); 490 pw.println(mRecentCallingUid); 491 pw.print(prefix); pw.print("allowStartForeground="); 492 pw.println(PowerExemptionManager.reasonCodeToString(mAllowStartForeground)); 493 pw.print(prefix); pw.print("startForegroundCount="); 494 pw.println(mStartForegroundCount); 495 pw.print(prefix); pw.print("infoAllowStartForeground="); 496 pw.println(mInfoAllowStartForeground); 497 if (delayed) { 498 pw.print(prefix); pw.print("delayed="); pw.println(delayed); 499 } 500 if (isForeground || foregroundId != 0) { 501 pw.print(prefix); pw.print("isForeground="); pw.print(isForeground); 502 pw.print(" foregroundId="); pw.print(foregroundId); 503 pw.print(" foregroundNoti="); pw.println(foregroundNoti); 504 } 505 pw.print(prefix); pw.print("createTime="); 506 TimeUtils.formatDuration(createRealTime, nowReal, pw); 507 pw.print(" startingBgTimeout="); 508 TimeUtils.formatDuration(startingBgTimeout, now, pw); 509 pw.println(); 510 pw.print(prefix); pw.print("lastActivity="); 511 TimeUtils.formatDuration(lastActivity, now, pw); 512 pw.print(" restartTime="); 513 TimeUtils.formatDuration(restartTime, now, pw); 514 pw.print(" createdFromFg="); pw.println(createdFromFg); 515 if (pendingConnectionGroup != 0) { 516 pw.print(prefix); pw.print(" pendingConnectionGroup="); 517 pw.print(pendingConnectionGroup); 518 pw.print(" Importance="); pw.println(pendingConnectionImportance); 519 } 520 if (startRequested || delayedStop || lastStartId != 0) { 521 pw.print(prefix); pw.print("startRequested="); pw.print(startRequested); 522 pw.print(" delayedStop="); pw.print(delayedStop); 523 pw.print(" stopIfKilled="); pw.print(stopIfKilled); 524 pw.print(" callStart="); pw.print(callStart); 525 pw.print(" lastStartId="); pw.println(lastStartId); 526 } 527 if (executeNesting != 0) { 528 pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting); 529 pw.print(" executeFg="); pw.print(executeFg); 530 pw.print(" executingStart="); 531 TimeUtils.formatDuration(executingStart, now, pw); 532 pw.println(); 533 } 534 if (destroying || destroyTime != 0) { 535 pw.print(prefix); pw.print("destroying="); pw.print(destroying); 536 pw.print(" destroyTime="); 537 TimeUtils.formatDuration(destroyTime, now, pw); 538 pw.println(); 539 } 540 if (crashCount != 0 || restartCount != 0 541 || (nextRestartTime - mRestartSchedulingTime) != 0 || nextRestartTime != 0) { 542 pw.print(prefix); pw.print("restartCount="); pw.print(restartCount); 543 pw.print(" restartDelay="); 544 TimeUtils.formatDuration(nextRestartTime - mRestartSchedulingTime, now, pw); 545 pw.print(" nextRestartTime="); 546 TimeUtils.formatDuration(nextRestartTime, now, pw); 547 pw.print(" crashCount="); pw.println(crashCount); 548 } 549 if (deliveredStarts.size() > 0) { 550 pw.print(prefix); pw.println("Delivered Starts:"); 551 dumpStartList(pw, prefix, deliveredStarts, now); 552 } 553 if (pendingStarts.size() > 0) { 554 pw.print(prefix); pw.println("Pending Starts:"); 555 dumpStartList(pw, prefix, pendingStarts, 0); 556 } 557 if (bindings.size() > 0) { 558 pw.print(prefix); pw.println("Bindings:"); 559 for (int i=0; i<bindings.size(); i++) { 560 IntentBindRecord b = bindings.valueAt(i); 561 pw.print(prefix); pw.print("* IntentBindRecord{"); 562 pw.print(Integer.toHexString(System.identityHashCode(b))); 563 if ((b.collectFlags()&Context.BIND_AUTO_CREATE) != 0) { 564 pw.append(" CREATE"); 565 } 566 pw.println("}:"); 567 b.dumpInService(pw, prefix + " "); 568 } 569 } 570 if (connections.size() > 0) { 571 pw.print(prefix); pw.println("All Connections:"); 572 for (int conni=0; conni<connections.size(); conni++) { 573 ArrayList<ConnectionRecord> c = connections.valueAt(conni); 574 for (int i=0; i<c.size(); i++) { 575 pw.print(prefix); pw.print(" "); pw.println(c.get(i)); 576 } 577 } 578 } 579 } 580 ServiceRecord(ActivityManagerService ams, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter)581 ServiceRecord(ActivityManagerService ams, ComponentName name, 582 ComponentName instanceName, String definingPackageName, int definingUid, 583 Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, 584 Runnable restarter) { 585 this(ams, name, instanceName, definingPackageName, definingUid, intent, sInfo, callerIsFg, 586 restarter, null, 0, null); 587 } 588 ServiceRecord(ActivityManagerService ams, ComponentName name, ComponentName instanceName, String definingPackageName, int definingUid, Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, Runnable restarter, String sdkSandboxProcessName, int sdkSandboxClientAppUid, String sdkSandboxClientAppPackage)589 ServiceRecord(ActivityManagerService ams, ComponentName name, 590 ComponentName instanceName, String definingPackageName, int definingUid, 591 Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg, 592 Runnable restarter, String sdkSandboxProcessName, int sdkSandboxClientAppUid, 593 String sdkSandboxClientAppPackage) { 594 this.ams = ams; 595 this.name = name; 596 this.instanceName = instanceName; 597 shortInstanceName = instanceName.flattenToShortString(); 598 this.definingPackageName = definingPackageName; 599 this.definingUid = definingUid; 600 this.intent = intent; 601 serviceInfo = sInfo; 602 appInfo = sInfo.applicationInfo; 603 packageName = sInfo.applicationInfo.packageName; 604 this.isSdkSandbox = sdkSandboxProcessName != null; 605 this.sdkSandboxClientAppUid = sdkSandboxClientAppUid; 606 this.sdkSandboxClientAppPackage = sdkSandboxClientAppPackage; 607 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) != 0) { 608 processName = sInfo.processName + ":" + instanceName.getClassName(); 609 } else if (sdkSandboxProcessName != null) { 610 processName = sdkSandboxProcessName; 611 } else { 612 processName = sInfo.processName; 613 } 614 permission = sInfo.permission; 615 exported = sInfo.exported; 616 this.restarter = restarter; 617 createRealTime = SystemClock.elapsedRealtime(); 618 lastActivity = SystemClock.uptimeMillis(); 619 userId = UserHandle.getUserId(appInfo.uid); 620 createdFromFg = callerIsFg; 621 updateKeepWarmLocked(); 622 // initialize notification permission state; this'll be updated whenever there's an attempt 623 // to post or update a notification, but that doesn't cover the time before the first 624 // notification 625 updateFgsHasNotificationPermission(); 626 } 627 getTracker()628 public ServiceState getTracker() { 629 if (tracker != null) { 630 return tracker; 631 } 632 if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) { 633 tracker = ams.mProcessStats.getServiceState(serviceInfo.packageName, 634 serviceInfo.applicationInfo.uid, 635 serviceInfo.applicationInfo.longVersionCode, 636 serviceInfo.processName, serviceInfo.name); 637 tracker.applyNewOwner(this); 638 } 639 return tracker; 640 } 641 forceClearTracker()642 public void forceClearTracker() { 643 if (tracker != null) { 644 tracker.clearCurrentOwner(this, true); 645 tracker = null; 646 } 647 } 648 makeRestarting(int memFactor, long now)649 public void makeRestarting(int memFactor, long now) { 650 if (restartTracker == null) { 651 if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) { 652 restartTracker = ams.mProcessStats.getServiceState( 653 serviceInfo.packageName, 654 serviceInfo.applicationInfo.uid, 655 serviceInfo.applicationInfo.longVersionCode, 656 serviceInfo.processName, serviceInfo.name); 657 } 658 if (restartTracker == null) { 659 return; 660 } 661 } 662 restartTracker.setRestarting(true, memFactor, now); 663 } 664 setProcess(ProcessRecord proc, IApplicationThread thread, int pid, UidRecord uidRecord)665 public void setProcess(ProcessRecord proc, IApplicationThread thread, int pid, 666 UidRecord uidRecord) { 667 if (proc != null) { 668 // We're starting a new process for this service, but a previous one is allowed to start 669 // background activities. Remove that ability now (unless the new process is the same as 670 // the previous one, which is a common case). 671 if (mAppForAllowingBgActivityStartsByStart != null) { 672 if (mAppForAllowingBgActivityStartsByStart != proc) { 673 mAppForAllowingBgActivityStartsByStart 674 .removeAllowBackgroundActivityStartsToken(this); 675 ams.mHandler.removeCallbacks(mCleanUpAllowBgActivityStartsByStartCallback); 676 } 677 } 678 // Make sure the cleanup callback knows about the new process. 679 mAppForAllowingBgActivityStartsByStart = mIsAllowedBgActivityStartsByStart 680 ? proc : null; 681 if (mIsAllowedBgActivityStartsByStart 682 || mIsAllowedBgActivityStartsByBinding) { 683 proc.addOrUpdateAllowBackgroundActivityStartsToken(this, 684 getExclusiveOriginatingToken()); 685 } else { 686 proc.removeAllowBackgroundActivityStartsToken(this); 687 } 688 } 689 if (app != null && app != proc) { 690 // If the old app is allowed to start bg activities because of a service start, leave it 691 // that way until the cleanup callback runs. Otherwise we can remove its bg activity 692 // start ability immediately (it can't be bound now). 693 if (!mIsAllowedBgActivityStartsByStart) { 694 app.removeAllowBackgroundActivityStartsToken(this); 695 } 696 app.mServices.updateBoundClientUids(); 697 app.mServices.updateHostingComonentTypeForBindingsLocked(); 698 } 699 app = proc; 700 if (pendingConnectionGroup > 0 && proc != null) { 701 final ProcessServiceRecord psr = proc.mServices; 702 psr.setConnectionService(this); 703 psr.setConnectionGroup(pendingConnectionGroup); 704 psr.setConnectionImportance(pendingConnectionImportance); 705 pendingConnectionGroup = pendingConnectionImportance = 0; 706 } 707 if (ActivityManagerService.TRACK_PROCSTATS_ASSOCIATIONS) { 708 for (int conni = connections.size() - 1; conni >= 0; conni--) { 709 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 710 for (int i = 0; i < cr.size(); i++) { 711 final ConnectionRecord conn = cr.get(i); 712 if (proc != null) { 713 conn.startAssociationIfNeeded(); 714 } else { 715 conn.stopAssociation(); 716 } 717 } 718 } 719 } 720 if (proc != null) { 721 proc.mServices.updateBoundClientUids(); 722 proc.mServices.updateHostingComonentTypeForBindingsLocked(); 723 } 724 } 725 726 @NonNull getConnections()727 ArrayMap<IBinder, ArrayList<ConnectionRecord>> getConnections() { 728 return connections; 729 } 730 addConnection(IBinder binder, ConnectionRecord c)731 void addConnection(IBinder binder, ConnectionRecord c) { 732 ArrayList<ConnectionRecord> clist = connections.get(binder); 733 if (clist == null) { 734 clist = new ArrayList<>(); 735 connections.put(binder, clist); 736 } 737 clist.add(c); 738 739 // if we have a process attached, add bound client uid of this connection to it 740 if (app != null) { 741 app.mServices.addBoundClientUid(c.clientUid); 742 app.mProfile.addHostingComponentType(HOSTING_COMPONENT_TYPE_BOUND_SERVICE); 743 } 744 } 745 removeConnection(IBinder binder)746 void removeConnection(IBinder binder) { 747 connections.remove(binder); 748 // if we have a process attached, tell it to update the state of bound clients 749 if (app != null) { 750 app.mServices.updateBoundClientUids(); 751 app.mServices.updateHostingComonentTypeForBindingsLocked(); 752 } 753 } 754 755 /** 756 * @return {@code true} if the killed service which was started by {@link Context#startService} 757 * has no reason to start again. Note this condition doesn't consider the bindings. 758 */ canStopIfKilled(boolean isStartCanceled)759 boolean canStopIfKilled(boolean isStartCanceled) { 760 return startRequested && (stopIfKilled || isStartCanceled) && pendingStarts.isEmpty(); 761 } 762 updateIsAllowedBgActivityStartsByBinding()763 void updateIsAllowedBgActivityStartsByBinding() { 764 boolean isAllowedByBinding = false; 765 for (int conni = connections.size() - 1; conni >= 0; conni--) { 766 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 767 for (int i = 0; i < cr.size(); i++) { 768 if ((cr.get(i).flags & Context.BIND_ALLOW_BACKGROUND_ACTIVITY_STARTS) != 0) { 769 isAllowedByBinding = true; 770 break; 771 } 772 } 773 if (isAllowedByBinding) { 774 break; 775 } 776 } 777 setAllowedBgActivityStartsByBinding(isAllowedByBinding); 778 } 779 setAllowedBgActivityStartsByBinding(boolean newValue)780 void setAllowedBgActivityStartsByBinding(boolean newValue) { 781 mIsAllowedBgActivityStartsByBinding = newValue; 782 updateParentProcessBgActivityStartsToken(); 783 } 784 785 /** 786 * Called when the service is started with allowBackgroundActivityStarts set. We allow 787 * it for background activity starts, setting up a callback to remove this ability after a 788 * timeout. Note that the ability for starting background activities persists for the process 789 * even if the service is subsequently stopped. 790 */ allowBgActivityStartsOnServiceStart(@ullable IBinder originatingToken)791 void allowBgActivityStartsOnServiceStart(@Nullable IBinder originatingToken) { 792 mBgActivityStartsByStartOriginatingTokens.add(originatingToken); 793 setAllowedBgActivityStartsByStart(true); 794 if (app != null) { 795 mAppForAllowingBgActivityStartsByStart = app; 796 } 797 798 // This callback is stateless, so we create it once when we first need it. 799 if (mCleanUpAllowBgActivityStartsByStartCallback == null) { 800 mCleanUpAllowBgActivityStartsByStartCallback = () -> { 801 synchronized (ams) { 802 mBgActivityStartsByStartOriginatingTokens.remove(0); 803 if (!mBgActivityStartsByStartOriginatingTokens.isEmpty()) { 804 // There are other callbacks in the queue, let's just update the originating 805 // token 806 if (mIsAllowedBgActivityStartsByStart) { 807 // mAppForAllowingBgActivityStartsByStart can be null here for example 808 // if get 2 calls to allowBgActivityStartsOnServiceStart() without a 809 // process attached to this ServiceRecord, so we need to perform a null 810 // check here. 811 if (mAppForAllowingBgActivityStartsByStart != null) { 812 mAppForAllowingBgActivityStartsByStart 813 .addOrUpdateAllowBackgroundActivityStartsToken( 814 this, getExclusiveOriginatingToken()); 815 } 816 } else { 817 Slog.wtf(TAG, 818 "Service callback to revoke bg activity starts by service " 819 + "start triggered but " 820 + "mIsAllowedBgActivityStartsByStart = false. This " 821 + "should never happen."); 822 } 823 } else { 824 // Last callback on the queue 825 if (app == mAppForAllowingBgActivityStartsByStart) { 826 // The process we allowed is still running the service. We remove 827 // the ability by start, but it may still be allowed via bound 828 // connections. 829 setAllowedBgActivityStartsByStart(false); 830 } else if (mAppForAllowingBgActivityStartsByStart != null) { 831 // The process we allowed is not running the service. It therefore can't 832 // be bound so we can unconditionally remove the ability. 833 mAppForAllowingBgActivityStartsByStart 834 .removeAllowBackgroundActivityStartsToken(ServiceRecord.this); 835 } 836 mAppForAllowingBgActivityStartsByStart = null; 837 } 838 } 839 }; 840 } 841 842 // Existing callbacks will only update the originating token, only when the last callback is 843 // executed is the grant revoked. 844 ams.mHandler.postDelayed(mCleanUpAllowBgActivityStartsByStartCallback, 845 ams.mConstants.SERVICE_BG_ACTIVITY_START_TIMEOUT); 846 } 847 setAllowedBgActivityStartsByStart(boolean newValue)848 private void setAllowedBgActivityStartsByStart(boolean newValue) { 849 mIsAllowedBgActivityStartsByStart = newValue; 850 updateParentProcessBgActivityStartsToken(); 851 } 852 853 /** 854 * Whether the process this service runs in should be temporarily allowed to start 855 * activities from background depends on the current state of both 856 * {@code mIsAllowedBgActivityStartsByStart} and 857 * {@code mIsAllowedBgActivityStartsByBinding}. If either is true, this ServiceRecord 858 * should be contributing as a token in parent ProcessRecord. 859 * 860 * @see com.android.server.am.ProcessRecord#addOrUpdateAllowBackgroundActivityStartsToken( 861 * Binder, IBinder) 862 * @see com.android.server.am.ProcessRecord#removeAllowBackgroundActivityStartsToken(Binder) 863 */ updateParentProcessBgActivityStartsToken()864 private void updateParentProcessBgActivityStartsToken() { 865 if (app == null) { 866 return; 867 } 868 if (mIsAllowedBgActivityStartsByStart || mIsAllowedBgActivityStartsByBinding) { 869 // if the token is already there it's safe to "re-add it" - we're dealing with 870 // a set of Binder objects 871 app.addOrUpdateAllowBackgroundActivityStartsToken(this, getExclusiveOriginatingToken()); 872 } else { 873 app.removeAllowBackgroundActivityStartsToken(this); 874 } 875 } 876 877 /** 878 * Returns the originating token if that's the only reason background activity starts are 879 * allowed. In order for that to happen the service has to be allowed only due to starts, since 880 * bindings are not associated with originating tokens, and all the start tokens have to be the 881 * same and there can't be any null originating token in the queue. 882 * 883 * Originating tokens are optional, so the caller could provide null when it allows bg activity 884 * starts. 885 */ 886 @Nullable getExclusiveOriginatingToken()887 private IBinder getExclusiveOriginatingToken() { 888 if (mIsAllowedBgActivityStartsByBinding 889 || mBgActivityStartsByStartOriginatingTokens.isEmpty()) { 890 return null; 891 } 892 IBinder firstToken = mBgActivityStartsByStartOriginatingTokens.get(0); 893 for (int i = 1, n = mBgActivityStartsByStartOriginatingTokens.size(); i < n; i++) { 894 IBinder token = mBgActivityStartsByStartOriginatingTokens.get(i); 895 if (token != firstToken) { 896 return null; 897 } 898 } 899 return firstToken; 900 } 901 902 @GuardedBy("ams") updateKeepWarmLocked()903 void updateKeepWarmLocked() { 904 mKeepWarming = ams.mConstants.KEEP_WARMING_SERVICES.contains(name) 905 && (ams.mUserController.getCurrentUserId() == userId 906 || ams.mUserController.isCurrentProfile(userId) 907 || ams.isSingleton(processName, appInfo, instanceName.getClassName(), 908 serviceInfo.flags)); 909 } 910 retrieveAppBindingLocked(Intent intent, ProcessRecord app)911 public AppBindRecord retrieveAppBindingLocked(Intent intent, 912 ProcessRecord app) { 913 Intent.FilterComparison filter = new Intent.FilterComparison(intent); 914 IntentBindRecord i = bindings.get(filter); 915 if (i == null) { 916 i = new IntentBindRecord(this, filter); 917 bindings.put(filter, i); 918 } 919 AppBindRecord a = i.apps.get(app); 920 if (a != null) { 921 return a; 922 } 923 a = new AppBindRecord(this, i, app); 924 i.apps.put(app, a); 925 return a; 926 } 927 hasAutoCreateConnections()928 public boolean hasAutoCreateConnections() { 929 // XXX should probably keep a count of the number of auto-create 930 // connections directly in the service. 931 for (int conni=connections.size()-1; conni>=0; conni--) { 932 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 933 for (int i=0; i<cr.size(); i++) { 934 if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) { 935 return true; 936 } 937 } 938 } 939 return false; 940 } 941 updateAllowlistManager()942 public void updateAllowlistManager() { 943 allowlistManager = false; 944 for (int conni=connections.size()-1; conni>=0; conni--) { 945 ArrayList<ConnectionRecord> cr = connections.valueAt(conni); 946 for (int i=0; i<cr.size(); i++) { 947 if ((cr.get(i).flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) { 948 allowlistManager = true; 949 return; 950 } 951 } 952 } 953 } 954 resetRestartCounter()955 public void resetRestartCounter() { 956 restartCount = 0; 957 restartDelay = 0; 958 restartTime = 0; 959 mEarliestRestartTime = 0; 960 mRestartSchedulingTime = 0; 961 } 962 findDeliveredStart(int id, boolean taskRemoved, boolean remove)963 public StartItem findDeliveredStart(int id, boolean taskRemoved, boolean remove) { 964 final int N = deliveredStarts.size(); 965 for (int i=0; i<N; i++) { 966 StartItem si = deliveredStarts.get(i); 967 if (si.id == id && si.taskRemoved == taskRemoved) { 968 if (remove) deliveredStarts.remove(i); 969 return si; 970 } 971 } 972 973 return null; 974 } 975 getLastStartId()976 public int getLastStartId() { 977 return lastStartId; 978 } 979 makeNextStartId()980 public int makeNextStartId() { 981 lastStartId++; 982 if (lastStartId < 1) { 983 lastStartId = 1; 984 } 985 return lastStartId; 986 } 987 updateFgsHasNotificationPermission()988 private void updateFgsHasNotificationPermission() { 989 // Do asynchronous communication with notification manager to avoid deadlocks. 990 final String localPackageName = packageName; 991 final int appUid = appInfo.uid; 992 993 ams.mHandler.post(new Runnable() { 994 public void run() { 995 NotificationManagerInternal nm = LocalServices.getService( 996 NotificationManagerInternal.class); 997 if (nm == null) { 998 return; 999 } 1000 // Record whether the package has permission to notify the user 1001 mFgsHasNotificationPermission = nm.areNotificationsEnabledForPackage( 1002 localPackageName, appUid); 1003 } 1004 }); 1005 } 1006 postNotification()1007 public void postNotification() { 1008 if (isForeground && foregroundNoti != null && app != null) { 1009 final int appUid = appInfo.uid; 1010 final int appPid = app.getPid(); 1011 // Do asynchronous communication with notification manager to 1012 // avoid deadlocks. 1013 final String localPackageName = packageName; 1014 final int localForegroundId = foregroundId; 1015 final Notification _foregroundNoti = foregroundNoti; 1016 final ServiceRecord record = this; 1017 if (DEBUG_FOREGROUND_SERVICE) { 1018 Slog.d(TAG, "Posting notification " + _foregroundNoti 1019 + " for foreground service " + this); 1020 } 1021 ams.mHandler.post(new Runnable() { 1022 public void run() { 1023 NotificationManagerInternal nm = LocalServices.getService( 1024 NotificationManagerInternal.class); 1025 if (nm == null) { 1026 return; 1027 } 1028 // Record whether the package has permission to notify the user 1029 mFgsHasNotificationPermission = nm.areNotificationsEnabledForPackage( 1030 localPackageName, appUid); 1031 Notification localForegroundNoti = _foregroundNoti; 1032 try { 1033 if (localForegroundNoti.getSmallIcon() == null) { 1034 // It is not correct for the caller to not supply a notification 1035 // icon, but this used to be able to slip through, so for 1036 // those dirty apps we will create a notification clearly 1037 // blaming the app. 1038 Slog.v(TAG, "Attempted to start a foreground service (" 1039 + shortInstanceName 1040 + ") with a broken notification (no icon: " 1041 + localForegroundNoti 1042 + ")"); 1043 1044 CharSequence appName = appInfo.loadLabel( 1045 ams.mContext.getPackageManager()); 1046 if (appName == null) { 1047 appName = appInfo.packageName; 1048 } 1049 Context ctx = null; 1050 try { 1051 ctx = ams.mContext.createPackageContextAsUser( 1052 appInfo.packageName, 0, new UserHandle(userId)); 1053 1054 Notification.Builder notiBuilder = new Notification.Builder(ctx, 1055 localForegroundNoti.getChannelId()); 1056 1057 // it's ugly, but it clearly identifies the app 1058 notiBuilder.setSmallIcon(appInfo.icon); 1059 1060 // mark as foreground 1061 notiBuilder.setFlag(Notification.FLAG_FOREGROUND_SERVICE, true); 1062 1063 Intent runningIntent = new Intent( 1064 Settings.ACTION_APPLICATION_DETAILS_SETTINGS); 1065 runningIntent.setData(Uri.fromParts("package", 1066 appInfo.packageName, null)); 1067 PendingIntent pi = PendingIntent.getActivityAsUser(ams.mContext, 0, 1068 runningIntent, FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE, null, 1069 UserHandle.of(userId)); 1070 notiBuilder.setColor(ams.mContext.getColor( 1071 com.android.internal 1072 .R.color.system_notification_accent_color)); 1073 notiBuilder.setContentTitle( 1074 ams.mContext.getString( 1075 com.android.internal.R.string 1076 .app_running_notification_title, 1077 appName)); 1078 notiBuilder.setContentText( 1079 ams.mContext.getString( 1080 com.android.internal.R.string 1081 .app_running_notification_text, 1082 appName)); 1083 notiBuilder.setContentIntent(pi); 1084 1085 localForegroundNoti = notiBuilder.build(); 1086 } catch (PackageManager.NameNotFoundException e) { 1087 } 1088 } 1089 if (nm.getNotificationChannel(localPackageName, appUid, 1090 localForegroundNoti.getChannelId()) == null) { 1091 int targetSdkVersion = Build.VERSION_CODES.O_MR1; 1092 try { 1093 final ApplicationInfo applicationInfo = 1094 ams.mContext.getPackageManager().getApplicationInfoAsUser( 1095 appInfo.packageName, 0, userId); 1096 targetSdkVersion = applicationInfo.targetSdkVersion; 1097 } catch (PackageManager.NameNotFoundException e) { 1098 } 1099 if (targetSdkVersion >= Build.VERSION_CODES.O_MR1) { 1100 throw new RuntimeException( 1101 "invalid channel for service notification: " 1102 + foregroundNoti); 1103 } 1104 } 1105 if (localForegroundNoti.getSmallIcon() == null) { 1106 // Notifications whose icon is 0 are defined to not show 1107 // a notification. We don't want to 1108 // just ignore it, we want to prevent the service from 1109 // being foreground. 1110 throw new RuntimeException("invalid service notification: " 1111 + foregroundNoti); 1112 } 1113 nm.enqueueNotification(localPackageName, localPackageName, 1114 appUid, appPid, null, localForegroundId, localForegroundNoti, 1115 userId); 1116 1117 foregroundNoti = localForegroundNoti; // save it for amending next time 1118 1119 signalForegroundServiceNotification(packageName, appInfo.uid, 1120 localForegroundId, false /* canceling */); 1121 1122 } catch (RuntimeException e) { 1123 Slog.w(TAG, "Error showing notification for service", e); 1124 // If it gave us a garbage notification, it doesn't 1125 // get to be foreground. 1126 ams.mServices.killMisbehavingService(record, 1127 appUid, appPid, localPackageName, 1128 CannotPostForegroundServiceNotificationException.TYPE_ID); 1129 } 1130 } 1131 }); 1132 } 1133 } 1134 cancelNotification()1135 public void cancelNotification() { 1136 // Do asynchronous communication with notification manager to 1137 // avoid deadlocks. 1138 final String localPackageName = packageName; 1139 final int localForegroundId = foregroundId; 1140 final int appUid = appInfo.uid; 1141 final int appPid = app != null ? app.getPid() : 0; 1142 ams.mHandler.post(new Runnable() { 1143 public void run() { 1144 NotificationManagerInternal nm = LocalServices.getService( 1145 NotificationManagerInternal.class); 1146 if (nm == null) { 1147 return; 1148 } 1149 try { 1150 nm.cancelNotification(localPackageName, localPackageName, appUid, appPid, 1151 null, localForegroundId, userId); 1152 } catch (RuntimeException e) { 1153 Slog.w(TAG, "Error canceling notification for service", e); 1154 } 1155 signalForegroundServiceNotification(packageName, appInfo.uid, localForegroundId, 1156 true /* canceling */); 1157 } 1158 }); 1159 } 1160 signalForegroundServiceNotification(String packageName, int uid, int foregroundId, boolean canceling)1161 private void signalForegroundServiceNotification(String packageName, int uid, 1162 int foregroundId, boolean canceling) { 1163 synchronized (ams) { 1164 for (int i = ams.mForegroundServiceStateListeners.size() - 1; i >= 0; i--) { 1165 ams.mForegroundServiceStateListeners.get(i).onForegroundServiceNotificationUpdated( 1166 packageName, appInfo.uid, foregroundId, canceling); 1167 } 1168 } 1169 } 1170 stripForegroundServiceFlagFromNotification()1171 public void stripForegroundServiceFlagFromNotification() { 1172 final int localForegroundId = foregroundId; 1173 final int localUserId = userId; 1174 final String localPackageName = packageName; 1175 1176 // Do asynchronous communication with notification manager to 1177 // avoid deadlocks. 1178 ams.mHandler.post(new Runnable() { 1179 @Override 1180 public void run() { 1181 NotificationManagerInternal nmi = LocalServices.getService( 1182 NotificationManagerInternal.class); 1183 if (nmi == null) { 1184 return; 1185 } 1186 nmi.removeForegroundServiceFlagFromNotification(localPackageName, localForegroundId, 1187 localUserId); 1188 } 1189 }); 1190 } 1191 clearDeliveredStartsLocked()1192 public void clearDeliveredStartsLocked() { 1193 for (int i=deliveredStarts.size()-1; i>=0; i--) { 1194 deliveredStarts.get(i).removeUriPermissionsLocked(); 1195 } 1196 deliveredStarts.clear(); 1197 } 1198 toString()1199 public String toString() { 1200 if (stringName != null) { 1201 return stringName; 1202 } 1203 StringBuilder sb = new StringBuilder(128); 1204 sb.append("ServiceRecord{") 1205 .append(Integer.toHexString(System.identityHashCode(this))) 1206 .append(" u").append(userId) 1207 .append(' ').append(shortInstanceName).append('}'); 1208 return stringName = sb.toString(); 1209 } 1210 getComponentName()1211 public ComponentName getComponentName() { 1212 return name; 1213 } 1214 } 1215