2 * Copyright (C) 2012 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.server.am;
19 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
20 import static com.android.server.am.ActivityManagerDebugConfig.*;
22 import java.io.FileDescriptor;
23 import java.io.IOException;
24 import java.io.PrintWriter;
25 import java.io.StringWriter;
26 import java.util.ArrayList;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
32 import android.app.ActivityThread;
33 import android.app.AppOpsManager;
34 import android.app.NotificationManager;
35 import android.app.ServiceStartArgs;
36 import android.content.IIntentSender;
37 import android.content.IntentSender;
38 import android.content.pm.ParceledListSlice;
39 import android.net.Uri;
40 import android.os.Build;
41 import android.os.Bundle;
42 import android.os.DeadObjectException;
43 import android.os.Handler;
44 import android.os.Looper;
45 import android.os.RemoteCallback;
46 import android.os.SystemProperties;
47 import android.os.TransactionTooLargeException;
48 import android.provider.Settings;
49 import android.util.ArrayMap;
50 import android.util.ArraySet;
52 import com.android.internal.R;
53 import com.android.internal.app.procstats.ServiceState;
54 import com.android.internal.messages.nano.SystemMessageProto;
55 import com.android.internal.notification.SystemNotificationChannels;
56 import com.android.internal.os.BatteryStatsImpl;
57 import com.android.internal.os.TransferPipe;
58 import com.android.internal.util.FastPrintWriter;
59 import com.android.server.am.ActivityManagerService.ItemMatcher;
60 import com.android.server.am.ActivityManagerService.NeededUriGrants;
62 import android.app.ActivityManager;
63 import android.app.AppGlobals;
64 import android.app.IApplicationThread;
65 import android.app.IServiceConnection;
66 import android.app.Notification;
67 import android.app.PendingIntent;
68 import android.app.Service;
69 import android.content.ComponentName;
70 import android.content.Context;
71 import android.content.Intent;
72 import android.content.pm.ApplicationInfo;
73 import android.content.pm.PackageManager;
74 import android.content.pm.ResolveInfo;
75 import android.content.pm.ServiceInfo;
76 import android.os.Binder;
77 import android.os.IBinder;
78 import android.os.Message;
79 import android.os.Process;
80 import android.os.RemoteException;
81 import android.os.SystemClock;
82 import android.os.UserHandle;
83 import android.util.EventLog;
84 import android.util.PrintWriterPrinter;
85 import android.util.Slog;
86 import android.util.SparseArray;
87 import android.util.TimeUtils;
88 import android.webkit.WebViewZygote;
90 public final class ActiveServices {
91 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
92 private static final String TAG_MU = TAG + POSTFIX_MU;
93 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
94 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
96 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
97 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
99 private static final boolean LOG_SERVICE_START_STOP = false;
101 // How long we wait for a service to finish executing.
102 static final int SERVICE_TIMEOUT = 20*1000;
104 // How long we wait for a service to finish executing.
105 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
107 // How long the startForegroundService() grace period is to get around to
108 // calling startForeground() before we ANR + stop it.
109 static final int SERVICE_START_FOREGROUND_TIMEOUT = 5*1000;
111 final ActivityManagerService mAm;
113 // Maximum number of services that we allow to start in the background
115 final int mMaxStartingBackground;
117 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
120 * All currently bound service connections. Keys are the IBinder of
121 * the client's IServiceConnection.
123 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
126 * List of services that we have been asked to start,
127 * but haven't yet been able to. It is used to hold start requests
128 * while waiting for their corresponding application thread to get
131 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
134 * List of services that are scheduled to restart following a crash.
136 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
139 * List of services that are in the process of being destroyed.
141 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
143 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
144 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
147 * For keeping ActiveForegroundApps retaining state while the screen is off.
149 boolean mScreenOn = true;
151 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
152 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
156 final Runnable mLastAnrDumpClearer = new Runnable() {
157 @Override public void run() {
165 * Information about an app that is currently running one or more foreground services.
166 * (This maps directly to the running apps we show in the notification.)
168 static final class ActiveForegroundApp {
172 boolean mShownWhileScreenOn;
174 boolean mShownWhileTop;
176 long mStartVisibleTime;
180 // Temp output of foregroundAppShownEnoughLocked
185 * Information about services for a single user.
187 final class ServiceMap extends Handler {
189 final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
190 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
192 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
193 /* XXX eventually I'd like to have this based on processes instead of services.
194 * That is, if we try to start two services in a row both running in the same
195 * process, this should be one entry in mStartingBackground for that one process
196 * that remains until all services in it are done.
197 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
198 = new ArrayMap<ProcessRecord, DelayingProcess>();
199 final ArrayList<DelayingProcess> mStartingProcessList
200 = new ArrayList<DelayingProcess>();
203 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
205 final ArrayMap<String, ActiveForegroundApp> mActiveForegroundApps = new ArrayMap<>();
206 boolean mActiveForegroundAppsChanged;
208 static final int MSG_BG_START_TIMEOUT = 1;
209 static final int MSG_UPDATE_FOREGROUND_APPS = 2;
211 ServiceMap(Looper looper, int userId) {
217 public void handleMessage(Message msg) {
219 case MSG_BG_START_TIMEOUT: {
221 rescheduleDelayedStartsLocked();
224 case MSG_UPDATE_FOREGROUND_APPS: {
225 updateForegroundApps(this);
230 void ensureNotStartingBackgroundLocked(ServiceRecord r) {
231 if (mStartingBackground.remove(r)) {
232 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
233 "No longer background starting: " + r);
234 rescheduleDelayedStartsLocked();
236 if (mDelayedStartList.remove(r)) {
237 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
241 void rescheduleDelayedStartsLocked() {
242 removeMessages(MSG_BG_START_TIMEOUT);
243 final long now = SystemClock.uptimeMillis();
244 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
245 ServiceRecord r = mStartingBackground.get(i);
246 if (r.startingBgTimeout <= now) {
247 Slog.i(TAG, "Waited long enough for: " + r);
248 mStartingBackground.remove(i);
253 while (mDelayedStartList.size() > 0
254 && mStartingBackground.size() < mMaxStartingBackground) {
255 ServiceRecord r = mDelayedStartList.remove(0);
256 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
257 "REM FR DELAY LIST (exec next): " + r);
258 if (r.pendingStarts.size() <= 0) {
259 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
260 + " delayedStop=" + r.delayedStop);
262 if (DEBUG_DELAYED_SERVICE) {
263 if (mDelayedStartList.size() > 0) {
264 Slog.v(TAG_SERVICE, "Remaining delayed list:");
265 for (int i=0; i<mDelayedStartList.size(); i++) {
266 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
272 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
273 } catch (TransactionTooLargeException e) {
274 // Ignore, nobody upstack cares.
277 if (mStartingBackground.size() > 0) {
278 ServiceRecord next = mStartingBackground.get(0);
279 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
280 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
281 + ", can delay others up to " + when);
282 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
283 sendMessageAtTime(msg, when);
285 if (mStartingBackground.size() < mMaxStartingBackground) {
286 mAm.backgroundServicesFinishedLocked(mUserId);
291 public ActiveServices(ActivityManagerService service) {
295 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
296 } catch(RuntimeException e) {
298 mMaxStartingBackground = maxBg > 0
299 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
302 ServiceRecord getServiceByNameLocked(ComponentName name, int callingUser) {
303 // TODO: Deal with global services
305 Slog.v(TAG_MU, "getServiceByNameLocked(" + name + "), callingUser = " + callingUser);
306 return getServiceMapLocked(callingUser).mServicesByName.get(name);
309 boolean hasBackgroundServicesLocked(int callingUser) {
310 ServiceMap smap = mServiceMap.get(callingUser);
311 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
314 private ServiceMap getServiceMapLocked(int callingUser) {
315 ServiceMap smap = mServiceMap.get(callingUser);
317 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
318 mServiceMap.put(callingUser, smap);
323 ArrayMap<ComponentName, ServiceRecord> getServicesLocked(int callingUser) {
324 return getServiceMapLocked(callingUser).mServicesByName;
327 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
328 int callingPid, int callingUid, boolean fgRequired, String callingPackage, final int userId)
329 throws TransactionTooLargeException {
330 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
331 + " type=" + resolvedType + " args=" + service.getExtras());
333 final boolean callerFg;
334 if (caller != null) {
335 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
336 if (callerApp == null) {
337 throw new SecurityException(
338 "Unable to find app for caller " + caller
339 + " (pid=" + callingPid
340 + ") when starting service " + service);
342 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
347 ServiceLookupResult res =
348 retrieveServiceLocked(service, resolvedType, callingPackage,
349 callingPid, callingUid, userId, true, callerFg, false);
353 if (res.record == null) {
354 return new ComponentName("!", res.permission != null
355 ? res.permission : "private to package");
358 ServiceRecord r = res.record;
360 if (!mAm.mUserController.exists(r.userId)) {
361 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
365 // If this isn't a direct-to-foreground start, check our ability to kick off an
367 if (!r.startRequested && !fgRequired) {
368 // Before going further -- if this app is not allowed to start services in the
369 // background, then at this point we aren't going to let it period.
370 final int allowed = mAm.getAppStartModeLocked(r.appInfo.uid, r.packageName,
371 r.appInfo.targetSdkVersion, callingPid, false, false);
372 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
373 Slog.w(TAG, "Background start not allowed: service "
374 + service + " to " + r.name.flattenToShortString()
375 + " from pid=" + callingPid + " uid=" + callingUid
376 + " pkg=" + callingPackage);
377 if (allowed == ActivityManager.APP_START_MODE_DELAYED) {
378 // In this case we are silently disabling the app, to disrupt as
379 // little as possible existing apps.
382 // This app knows it is in the new model where this operation is not
383 // allowed, so tell it what has happened.
384 UidRecord uidRec = mAm.mActiveUids.get(r.appInfo.uid);
385 return new ComponentName("?", "app is in background uid " + uidRec);
389 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
390 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
392 // If permissions need a review before any of the app components can run,
393 // we do not start the service and launch a review activity if the calling app
394 // is in the foreground passing it a pending intent to start the service when
395 // review is completed.
396 if (mAm.mPermissionReviewRequired) {
397 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
398 callingUid, service, callerFg, userId)) {
403 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
404 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
406 r.lastActivity = SystemClock.uptimeMillis();
407 r.startRequested = true;
408 r.delayedStop = false;
409 r.fgRequired = fgRequired;
410 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
411 service, neededGrants, callingUid));
413 final ServiceMap smap = getServiceMapLocked(r.userId);
414 boolean addToStarting = false;
415 if (!callerFg && !fgRequired && r.app == null
416 && mAm.mUserController.hasStartedUserState(r.userId)) {
417 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
418 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
419 // If this is not coming from a foreground caller, then we may want
420 // to delay the start if there are already other background services
421 // that are starting. This is to avoid process start spam when lots
422 // of applications are all handling things like connectivity broadcasts.
423 // We only do this for cached processes, because otherwise an application
424 // can have assumptions about calling startService() for a service to run
425 // in its own process, and for that process to not be killed before the
426 // service is started. This is especially the case for receivers, which
427 // may start a service in onReceive() to do some additional work and have
428 // initialized some global state as part of that.
429 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
430 + r + " in " + proc);
432 // This service is already scheduled for a delayed start; just leave
434 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
437 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
438 // Something else is starting, delay!
439 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
440 smap.mDelayedStartList.add(r);
444 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
445 addToStarting = true;
446 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
447 // We slightly loosen when we will enqueue this new service as a background
448 // starting service we are waiting for, to also include processes that are
449 // currently running other services or receivers.
450 addToStarting = true;
451 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
452 "Not delaying, but counting as bg: " + r);
453 } else if (DEBUG_DELAYED_STARTS) {
454 StringBuilder sb = new StringBuilder(128);
455 sb.append("Not potential delay (state=").append(proc.curProcState)
456 .append(' ').append(proc.adjType);
457 String reason = proc.makeAdjReason();
458 if (reason != null) {
463 sb.append(r.toString());
464 Slog.v(TAG_SERVICE, sb.toString());
466 } else if (DEBUG_DELAYED_STARTS) {
467 if (callerFg || fgRequired) {
468 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
469 + callingUid + " pid=" + callingPid + " fgRequired=" + fgRequired + "): " + r);
470 } else if (r.app != null) {
471 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
474 "Not potential delay (user " + r.userId + " not started): " + r);
478 ComponentName cmp = startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
482 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
483 String callingPackage, int callingUid, Intent service, boolean callerFg,
485 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
486 r.packageName, r.userId)) {
488 // Show a permission review UI only for starting from a foreground app
490 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
491 + r.packageName + " requires a permissions review");
495 IIntentSender target = mAm.getIntentSenderLocked(
496 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
497 callingUid, userId, null, null, 0, new Intent[]{service},
498 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
499 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
500 | PendingIntent.FLAG_IMMUTABLE, null);
502 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
503 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
504 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
505 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
506 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
508 if (DEBUG_PERMISSIONS_REVIEW) {
509 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
513 mAm.mHandler.post(new Runnable() {
516 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
526 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
527 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
528 ServiceState stracker = r.getTracker();
529 if (stracker != null) {
530 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
533 synchronized (r.stats.getBatteryStats()) {
534 r.stats.startRunningLocked();
536 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
538 return new ComponentName("!!", error);
541 if (r.startRequested && addToStarting) {
542 boolean first = smap.mStartingBackground.size() == 0;
543 smap.mStartingBackground.add(r);
544 r.startingBgTimeout = SystemClock.uptimeMillis() + mAm.mConstants.BG_START_TIMEOUT;
545 if (DEBUG_DELAYED_SERVICE) {
546 RuntimeException here = new RuntimeException("here");
547 here.fillInStackTrace();
548 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
549 } else if (DEBUG_DELAYED_STARTS) {
550 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
553 smap.rescheduleDelayedStartsLocked();
555 } else if (callerFg || r.fgRequired) {
556 smap.ensureNotStartingBackgroundLocked(r);
562 private void stopServiceLocked(ServiceRecord service) {
563 if (service.delayed) {
564 // If service isn't actually running, but is is being held in the
565 // delayed list, then we need to keep it started but note that it
566 // should be stopped once no longer delayed.
567 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
568 service.delayedStop = true;
571 synchronized (service.stats.getBatteryStats()) {
572 service.stats.stopRunningLocked();
574 service.startRequested = false;
575 if (service.tracker != null) {
576 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
577 SystemClock.uptimeMillis());
579 service.callStart = false;
580 bringDownServiceIfNeededLocked(service, false, false);
583 int stopServiceLocked(IApplicationThread caller, Intent service,
584 String resolvedType, int userId) {
585 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
586 + " type=" + resolvedType);
588 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
589 if (caller != null && callerApp == null) {
590 throw new SecurityException(
591 "Unable to find app for caller " + caller
592 + " (pid=" + Binder.getCallingPid()
593 + ") when stopping service " + service);
596 // If this service is active, make sure it is stopped.
597 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
598 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false);
600 if (r.record != null) {
601 final long origId = Binder.clearCallingIdentity();
603 stopServiceLocked(r.record);
605 Binder.restoreCallingIdentity(origId);
615 void stopInBackgroundLocked(int uid) {
616 // Stop all services associated with this uid due to it going to the background
618 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
619 ArrayList<ServiceRecord> stopping = null;
620 if (services != null) {
621 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
622 ServiceRecord service = services.mServicesByName.valueAt(i);
623 if (service.appInfo.uid == uid && service.startRequested) {
624 if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
625 service.appInfo.targetSdkVersion, -1, false, false)
626 != ActivityManager.APP_START_MODE_NORMAL) {
627 if (stopping == null) {
628 stopping = new ArrayList<>();
630 String compName = service.name.flattenToShortString();
631 EventLogTags.writeAmStopIdleService(service.appInfo.uid, compName);
632 StringBuilder sb = new StringBuilder(64);
633 sb.append("Stopping service due to app idle: ");
634 UserHandle.formatUid(sb, service.appInfo.uid);
636 TimeUtils.formatDuration(service.createTime
637 - SystemClock.elapsedRealtime(), sb);
640 Slog.w(TAG, sb.toString());
641 stopping.add(service);
645 if (stopping != null) {
646 for (int i=stopping.size()-1; i>=0; i--) {
647 ServiceRecord service = stopping.get(i);
648 service.delayed = false;
649 services.ensureNotStartingBackgroundLocked(service);
650 stopServiceLocked(service);
656 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
657 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
658 Binder.getCallingPid(), Binder.getCallingUid(),
659 UserHandle.getCallingUserId(), false, false, false);
663 // r.record is null if findServiceLocked() failed the caller permission check
664 if (r.record == null) {
665 throw new SecurityException(
666 "Permission Denial: Accessing service"
667 + " from pid=" + Binder.getCallingPid()
668 + ", uid=" + Binder.getCallingUid()
669 + " requires " + r.permission);
671 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
680 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
682 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
683 + " " + token + " startId=" + startId);
684 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
687 // Asked to only stop if done with all work. Note that
688 // to avoid leaks, we will take this as dropping all
689 // start items up to and including this one.
690 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
692 while (r.deliveredStarts.size() > 0) {
693 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
694 cur.removeUriPermissionsLocked();
701 if (r.getLastStartId() != startId) {
705 if (r.deliveredStarts.size() > 0) {
706 Slog.w(TAG, "stopServiceToken startId " + startId
707 + " is last, but have " + r.deliveredStarts.size()
708 + " remaining args");
712 synchronized (r.stats.getBatteryStats()) {
713 r.stats.stopRunningLocked();
715 r.startRequested = false;
716 if (r.tracker != null) {
717 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
718 SystemClock.uptimeMillis());
721 final long origId = Binder.clearCallingIdentity();
722 bringDownServiceIfNeededLocked(r, false, false);
723 Binder.restoreCallingIdentity(origId);
729 public void setServiceForegroundLocked(ComponentName className, IBinder token,
730 int id, Notification notification, int flags) {
731 final int userId = UserHandle.getCallingUserId();
732 final long origId = Binder.clearCallingIdentity();
734 ServiceRecord r = findServiceLocked(className, token, userId);
736 setServiceForegroundInnerLocked(r, id, notification, flags);
739 Binder.restoreCallingIdentity(origId);
743 boolean foregroundAppShownEnoughLocked(ActiveForegroundApp aa, long nowElapsed) {
744 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Shown enough: pkg=" + aa.mPackageName + ", uid="
746 boolean canRemove = false;
747 aa.mHideTime = Long.MAX_VALUE;
748 if (aa.mShownWhileTop) {
749 // If the app was ever at the top of the screen while the foreground
750 // service was running, then we can always just immediately remove it.
752 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown while on top");
753 } else if (mScreenOn || aa.mShownWhileScreenOn) {
754 final long minTime = aa.mStartVisibleTime
755 + (aa.mStartTime != aa.mStartVisibleTime
756 ? mAm.mConstants.FGSERVICE_SCREEN_ON_AFTER_TIME
757 : mAm.mConstants.FGSERVICE_MIN_SHOWN_TIME);
758 if (nowElapsed >= minTime) {
759 // If shown while the screen is on, and it has been shown for
760 // at least the minimum show time, then we can now remove it.
761 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - shown long enough with screen on");
764 // This is when we will be okay to stop telling the user.
765 long reportTime = nowElapsed + mAm.mConstants.FGSERVICE_MIN_REPORT_TIME;
766 aa.mHideTime = reportTime > minTime ? reportTime : minTime;
767 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
768 + " with screen on");
771 final long minTime = aa.mEndTime
772 + mAm.mConstants.FGSERVICE_SCREEN_ON_BEFORE_TIME;
773 if (nowElapsed >= minTime) {
774 // If the foreground service has only run while the screen is
775 // off, but it has been gone now for long enough that we won't
776 // care to tell the user about it when the screen comes back on,
777 // then we can remove it now.
778 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "YES - gone long enough with screen off");
781 // This is when we won't care about this old fg service.
782 aa.mHideTime = minTime;
783 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "NO -- wait " + (aa.mHideTime-nowElapsed)
784 + " with screen off");
790 void updateForegroundApps(ServiceMap smap) {
791 // This is called from the handler without the lock held.
792 ArrayList<ActiveForegroundApp> active = null;
794 final long now = SystemClock.elapsedRealtime();
795 long nextUpdateTime = Long.MAX_VALUE;
797 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Updating foreground apps for user "
799 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
800 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
801 if (aa.mEndTime != 0) {
802 boolean canRemove = foregroundAppShownEnoughLocked(aa, now);
804 // This was up for longer than the timeout, so just remove immediately.
805 smap.mActiveForegroundApps.removeAt(i);
806 smap.mActiveForegroundAppsChanged = true;
809 if (aa.mHideTime < nextUpdateTime) {
810 nextUpdateTime = aa.mHideTime;
814 if (active == null) {
815 active = new ArrayList<>();
817 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Adding active: pkg="
818 + aa.mPackageName + ", uid=" + aa.mUid);
822 smap.removeMessages(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
823 if (nextUpdateTime < Long.MAX_VALUE) {
824 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Next update time in: "
825 + (nextUpdateTime-now));
826 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
827 smap.sendMessageAtTime(msg, nextUpdateTime
828 + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
831 if (!smap.mActiveForegroundAppsChanged) {
834 smap.mActiveForegroundAppsChanged = false;
837 final NotificationManager nm = (NotificationManager) mAm.mContext.getSystemService(
838 Context.NOTIFICATION_SERVICE);
839 final Context context = mAm.mContext;
841 if (active != null) {
842 for (int i = 0; i < active.size(); i++) {
843 ActiveForegroundApp aa = active.get(i);
844 if (aa.mLabel == null) {
845 PackageManager pm = context.getPackageManager();
847 ApplicationInfo ai = pm.getApplicationInfoAsUser(aa.mPackageName,
848 PackageManager.MATCH_KNOWN_PACKAGES, smap.mUserId);
849 aa.mLabel = ai.loadLabel(pm);
850 } catch (PackageManager.NameNotFoundException e) {
851 aa.mLabel = aa.mPackageName;
860 final long nowElapsed = SystemClock.elapsedRealtime();
861 long oldestStartTime = nowElapsed;
862 if (active.size() == 1) {
863 intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
864 intent.setData(Uri.fromParts("package", active.get(0).mPackageName, null));
865 title = context.getString(
866 R.string.foreground_service_app_in_background, active.get(0).mLabel);
867 msg = context.getString(R.string.foreground_service_tap_for_details);
868 pkgs = new String[] { active.get(0).mPackageName };
869 oldestStartTime = active.get(0).mStartTime;
871 intent = new Intent(Settings.ACTION_FOREGROUND_SERVICES_SETTINGS);
872 pkgs = new String[active.size()];
873 for (int i = 0; i < active.size(); i++) {
874 pkgs[i] = active.get(i).mPackageName;
875 oldestStartTime = Math.min(oldestStartTime, active.get(i).mStartTime);
877 intent.putExtra("packages", pkgs);
878 title = context.getString(
879 R.string.foreground_service_apps_in_background, active.size());
880 msg = active.get(0).mLabel.toString();
881 for (int i = 1; i < active.size(); i++) {
882 msg = context.getString(R.string.foreground_service_multiple_separator,
883 msg, active.get(i).mLabel);
886 Bundle notificationBundle = new Bundle();
887 notificationBundle.putStringArray(Notification.EXTRA_FOREGROUND_APPS, pkgs);
888 Notification.Builder n =
889 new Notification.Builder(context,
890 SystemNotificationChannels.FOREGROUND_SERVICE)
891 .addExtras(notificationBundle)
892 .setSmallIcon(R.drawable.stat_sys_vitals)
894 .setShowWhen(oldestStartTime < nowElapsed)
895 .setWhen(System.currentTimeMillis() - (nowElapsed - oldestStartTime))
896 .setColor(context.getColor(
897 com.android.internal.R.color.system_notification_accent_color))
898 .setContentTitle(title)
901 PendingIntent.getActivityAsUser(context, 0, intent,
902 PendingIntent.FLAG_UPDATE_CURRENT,
903 null, new UserHandle(smap.mUserId)));
904 nm.notifyAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
905 n.build(), new UserHandle(smap.mUserId));
907 nm.cancelAsUser(null, SystemMessageProto.SystemMessage.NOTE_FOREGROUND_SERVICES,
908 new UserHandle(smap.mUserId));
912 private void requestUpdateActiveForegroundAppsLocked(ServiceMap smap, long timeElapsed) {
913 Message msg = smap.obtainMessage(ServiceMap.MSG_UPDATE_FOREGROUND_APPS);
914 if (timeElapsed != 0) {
915 smap.sendMessageAtTime(msg,
916 timeElapsed + SystemClock.uptimeMillis() - SystemClock.elapsedRealtime());
918 smap.mActiveForegroundAppsChanged = true;
919 smap.sendMessage(msg);
923 private void decActiveForegroundAppLocked(ServiceMap smap, ServiceRecord r) {
924 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
925 if (active != null) {
927 if (active.mNumActive <= 0) {
928 active.mEndTime = SystemClock.elapsedRealtime();
929 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Ended running of service");
930 if (foregroundAppShownEnoughLocked(active, active.mEndTime)) {
931 // Have been active for long enough that we will remove it immediately.
932 smap.mActiveForegroundApps.remove(r.packageName);
933 smap.mActiveForegroundAppsChanged = true;
934 requestUpdateActiveForegroundAppsLocked(smap, 0);
935 } else if (active.mHideTime < Long.MAX_VALUE){
936 requestUpdateActiveForegroundAppsLocked(smap, active.mHideTime);
942 void updateScreenStateLocked(boolean screenOn) {
943 if (mScreenOn != screenOn) {
944 mScreenOn = screenOn;
946 // If screen is turning on, then we now reset the start time of any foreground
947 // services that were started while the screen was off.
949 final long nowElapsed = SystemClock.elapsedRealtime();
950 if (DEBUG_FOREGROUND_SERVICE) Slog.d(TAG, "Screen turned on");
951 for (int i = mServiceMap.size()-1; i >= 0; i--) {
952 ServiceMap smap = mServiceMap.valueAt(i);
953 long nextUpdateTime = Long.MAX_VALUE;
954 boolean changed = false;
955 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
956 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
957 if (active.mEndTime == 0) {
958 if (!active.mShownWhileScreenOn) {
959 active.mShownWhileScreenOn = true;
960 active.mStartVisibleTime = nowElapsed;
963 if (!active.mShownWhileScreenOn
964 && active.mStartVisibleTime == active.mStartTime) {
965 // If this was never shown while the screen was on, then we will
966 // count the time it started being visible as now, to tell the user
967 // about it now that they have a screen to look at.
968 active.mEndTime = active.mStartVisibleTime = nowElapsed;
970 if (foregroundAppShownEnoughLocked(active, nowElapsed)) {
971 // Have been active for long enough that we will remove it
973 smap.mActiveForegroundApps.remove(active.mPackageName);
974 smap.mActiveForegroundAppsChanged = true;
977 if (active.mHideTime < nextUpdateTime) {
978 nextUpdateTime = active.mHideTime;
984 // Need to immediately update.
985 requestUpdateActiveForegroundAppsLocked(smap, 0);
986 } else if (nextUpdateTime < Long.MAX_VALUE) {
987 requestUpdateActiveForegroundAppsLocked(smap, nextUpdateTime);
994 void foregroundServiceProcStateChangedLocked(UidRecord uidRec) {
995 ServiceMap smap = mServiceMap.get(UserHandle.getUserId(uidRec.uid));
997 boolean changed = false;
998 for (int j = smap.mActiveForegroundApps.size()-1; j >= 0; j--) {
999 ActiveForegroundApp active = smap.mActiveForegroundApps.valueAt(j);
1000 if (active.mUid == uidRec.uid) {
1001 if (uidRec.curProcState <= ActivityManager.PROCESS_STATE_TOP) {
1002 if (!active.mAppOnTop) {
1003 active.mAppOnTop = true;
1006 active.mShownWhileTop = true;
1007 } else if (active.mAppOnTop) {
1008 active.mAppOnTop = false;
1014 requestUpdateActiveForegroundAppsLocked(smap, 0);
1019 private void setServiceForegroundInnerLocked(ServiceRecord r, int id,
1020 Notification notification, int flags) {
1022 if (notification == null) {
1023 throw new IllegalArgumentException("null notification");
1025 // Instant apps need permission to create foreground services.
1026 if (r.appInfo.isInstantApp()) {
1027 final int mode = mAm.mAppOpsService.checkOperation(
1028 AppOpsManager.OP_INSTANT_APP_START_FOREGROUND,
1030 r.appInfo.packageName);
1032 case AppOpsManager.MODE_ALLOWED:
1034 case AppOpsManager.MODE_IGNORED:
1035 Slog.w(TAG, "Instant app " + r.appInfo.packageName
1036 + " does not have permission to create foreground services"
1039 case AppOpsManager.MODE_ERRORED:
1040 throw new SecurityException("Instant app " + r.appInfo.packageName
1041 + " does not have permission to create foreground services");
1044 if (AppGlobals.getPackageManager().checkPermission(
1045 android.Manifest.permission.INSTANT_APP_FOREGROUND_SERVICE,
1046 r.appInfo.packageName, UserHandle.getUserId(r.appInfo.uid))
1047 != PackageManager.PERMISSION_GRANTED) {
1048 throw new SecurityException("Instant app " + r.appInfo.packageName
1049 + " does not have permission to create foreground"
1052 } catch (RemoteException e) {
1053 throw new SecurityException("Failed to check instant app permission." ,
1059 if (DEBUG_SERVICE || DEBUG_BACKGROUND_CHECK) {
1060 Slog.i(TAG, "Service called startForeground() as required: " + r);
1062 r.fgRequired = false;
1063 r.fgWaiting = false;
1064 mAm.mHandler.removeMessages(
1065 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
1067 if (r.foregroundId != id) {
1068 cancelForegroundNotificationLocked(r);
1069 r.foregroundId = id;
1071 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
1072 r.foregroundNoti = notification;
1073 if (!r.isForeground) {
1074 final ServiceMap smap = getServiceMapLocked(r.userId);
1076 ActiveForegroundApp active = smap.mActiveForegroundApps.get(r.packageName);
1077 if (active == null) {
1078 active = new ActiveForegroundApp();
1079 active.mPackageName = r.packageName;
1080 active.mUid = r.appInfo.uid;
1081 active.mShownWhileScreenOn = mScreenOn;
1082 if (r.app != null) {
1083 active.mAppOnTop = active.mShownWhileTop =
1084 r.app.uidRecord.curProcState
1085 <= ActivityManager.PROCESS_STATE_TOP;
1087 active.mStartTime = active.mStartVisibleTime
1088 = SystemClock.elapsedRealtime();
1089 smap.mActiveForegroundApps.put(r.packageName, active);
1090 requestUpdateActiveForegroundAppsLocked(smap, 0);
1092 active.mNumActive++;
1094 r.isForeground = true;
1096 r.postNotification();
1097 if (r.app != null) {
1098 updateServiceForegroundLocked(r.app, true);
1100 getServiceMapLocked(r.userId).ensureNotStartingBackgroundLocked(r);
1101 mAm.notifyPackageUse(r.serviceInfo.packageName,
1102 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
1104 if (r.isForeground) {
1105 final ServiceMap smap = getServiceMapLocked(r.userId);
1107 decActiveForegroundAppLocked(smap, r);
1109 r.isForeground = false;
1110 if (r.app != null) {
1111 mAm.updateLruProcessLocked(r.app, false, null);
1112 updateServiceForegroundLocked(r.app, true);
1115 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
1116 cancelForegroundNotificationLocked(r);
1118 r.foregroundNoti = null;
1119 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
1120 r.stripForegroundServiceFlagFromNotification();
1121 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
1123 r.foregroundNoti = null;
1129 private void cancelForegroundNotificationLocked(ServiceRecord r) {
1130 if (r.foregroundId != 0) {
1131 // First check to see if this app has any other active foreground services
1132 // with the same notification ID. If so, we shouldn't actually cancel it,
1133 // because that would wipe away the notification that still needs to be shown
1134 // due the other service.
1135 ServiceMap sm = getServiceMapLocked(r.userId);
1137 for (int i = sm.mServicesByName.size()-1; i >= 0; i--) {
1138 ServiceRecord other = sm.mServicesByName.valueAt(i);
1139 if (other != r && other.foregroundId == r.foregroundId
1140 && other.packageName.equals(r.packageName)) {
1141 // Found one! Abort the cancel.
1146 r.cancelNotification();
1150 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
1151 boolean anyForeground = false;
1152 for (int i=proc.services.size()-1; i>=0; i--) {
1153 ServiceRecord sr = proc.services.valueAt(i);
1154 if (sr.isForeground || sr.fgRequired) {
1155 anyForeground = true;
1159 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
1162 private void updateWhitelistManagerLocked(ProcessRecord proc) {
1163 proc.whitelistManager = false;
1164 for (int i=proc.services.size()-1; i>=0; i--) {
1165 ServiceRecord sr = proc.services.valueAt(i);
1166 if (sr.whitelistManager) {
1167 proc.whitelistManager = true;
1173 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
1174 ArraySet<ProcessRecord> updatedProcesses = null;
1175 for (int i = 0; i < clientProc.connections.size(); i++) {
1176 final ConnectionRecord conn = clientProc.connections.valueAt(i);
1177 final ProcessRecord proc = conn.binding.service.app;
1178 if (proc == null || proc == clientProc) {
1180 } else if (updatedProcesses == null) {
1181 updatedProcesses = new ArraySet<>();
1182 } else if (updatedProcesses.contains(proc)) {
1185 updatedProcesses.add(proc);
1186 updateServiceClientActivitiesLocked(proc, null, false);
1190 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
1191 ConnectionRecord modCr, boolean updateLru) {
1192 if (modCr != null && modCr.binding.client != null) {
1193 if (modCr.binding.client.activities.size() <= 0) {
1194 // This connection is from a client without activities, so adding
1195 // and removing is not interesting.
1200 boolean anyClientActivities = false;
1201 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
1202 ServiceRecord sr = proc.services.valueAt(i);
1203 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
1204 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
1205 for (int cri=clist.size()-1; cri>=0; cri--) {
1206 ConnectionRecord cr = clist.get(cri);
1207 if (cr.binding.client == null || cr.binding.client == proc) {
1208 // Binding to ourself is not interesting.
1211 if (cr.binding.client.activities.size() > 0) {
1212 anyClientActivities = true;
1218 if (anyClientActivities != proc.hasClientActivities) {
1219 proc.hasClientActivities = anyClientActivities;
1221 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
1228 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
1229 String resolvedType, final IServiceConnection connection, int flags,
1230 String callingPackage, final int userId) throws TransactionTooLargeException {
1231 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
1232 + " type=" + resolvedType + " conn=" + connection.asBinder()
1233 + " flags=0x" + Integer.toHexString(flags));
1234 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
1235 if (callerApp == null) {
1236 throw new SecurityException(
1237 "Unable to find app for caller " + caller
1238 + " (pid=" + Binder.getCallingPid()
1239 + ") when binding service " + service);
1242 ActivityRecord activity = null;
1243 if (token != null) {
1244 activity = ActivityRecord.isInStackLocked(token);
1245 if (activity == null) {
1246 Slog.w(TAG, "Binding with unknown activity: " + token);
1251 int clientLabel = 0;
1252 PendingIntent clientIntent = null;
1253 final boolean isCallerSystem = callerApp.info.uid == Process.SYSTEM_UID;
1255 if (isCallerSystem) {
1256 // Hacky kind of thing -- allow system stuff to tell us
1257 // what they are, so we can report this elsewhere for
1258 // others to know why certain services are running.
1259 service.setDefusable(true);
1260 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
1261 if (clientIntent != null) {
1262 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
1263 if (clientLabel != 0) {
1264 // There are no useful extras in the intent, trash them.
1265 // System code calling with this stuff just needs to know
1266 // this will happen.
1267 service = service.cloneFilter();
1272 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1273 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
1274 "BIND_TREAT_LIKE_ACTIVITY");
1277 if ((flags & Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0 && !isCallerSystem) {
1278 throw new SecurityException(
1279 "Non-system caller " + caller + " (pid=" + Binder.getCallingPid()
1280 + ") set BIND_ALLOW_WHITELIST_MANAGEMENT when binding service " + service);
1283 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
1284 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
1286 ServiceLookupResult res =
1287 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
1288 Binder.getCallingUid(), userId, true, callerFg, isBindExternal);
1292 if (res.record == null) {
1295 ServiceRecord s = res.record;
1297 boolean permissionsReviewRequired = false;
1299 // If permissions need a review before any of the app components can run,
1300 // we schedule binding to the service but do not start its process, then
1301 // we launch a review activity to which is passed a callback to invoke
1302 // when done to start the bound service's process to completing the binding.
1303 if (mAm.mPermissionReviewRequired) {
1304 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
1305 s.packageName, s.userId)) {
1307 permissionsReviewRequired = true;
1309 // Show a permission review UI only for binding from a foreground app
1311 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
1312 + s.packageName + " requires a permissions review");
1316 final ServiceRecord serviceRecord = s;
1317 final Intent serviceIntent = service;
1319 RemoteCallback callback = new RemoteCallback(
1320 new RemoteCallback.OnResultListener() {
1322 public void onResult(Bundle result) {
1324 final long identity = Binder.clearCallingIdentity();
1326 if (!mPendingServices.contains(serviceRecord)) {
1329 // If there is still a pending record, then the service
1330 // binding request is still valid, so hook them up. We
1331 // proceed only if the caller cleared the review requirement
1332 // otherwise we unbind because the user didn't approve.
1333 if (!mAm.getPackageManagerInternalLocked()
1334 .isPermissionsReviewRequired(
1335 serviceRecord.packageName,
1336 serviceRecord.userId)) {
1338 bringUpServiceLocked(serviceRecord,
1339 serviceIntent.getFlags(),
1340 callerFg, false, false);
1341 } catch (RemoteException e) {
1342 /* ignore - local call */
1345 unbindServiceLocked(connection);
1348 Binder.restoreCallingIdentity(identity);
1354 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
1355 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
1356 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
1357 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
1358 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
1360 if (DEBUG_PERMISSIONS_REVIEW) {
1361 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
1365 mAm.mHandler.post(new Runnable() {
1368 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
1374 final long origId = Binder.clearCallingIdentity();
1377 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
1378 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
1382 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1383 s.lastActivity = SystemClock.uptimeMillis();
1384 if (!s.hasAutoCreateConnections()) {
1385 // This is the first binding, let the tracker know.
1386 ServiceState stracker = s.getTracker();
1387 if (stracker != null) {
1388 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
1394 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
1395 s.appInfo.uid, s.name, s.processName);
1396 // Once the apps have become associated, if one of them is caller is ephemeral
1397 // the target app should now be able to see the calling app
1398 mAm.grantEphemeralAccessLocked(callerApp.userId, service,
1399 s.appInfo.uid, UserHandle.getAppId(callerApp.uid));
1401 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
1402 ConnectionRecord c = new ConnectionRecord(b, activity,
1403 connection, flags, clientLabel, clientIntent);
1405 IBinder binder = connection.asBinder();
1406 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
1407 if (clist == null) {
1408 clist = new ArrayList<ConnectionRecord>();
1409 s.connections.put(binder, clist);
1412 b.connections.add(c);
1413 if (activity != null) {
1414 if (activity.connections == null) {
1415 activity.connections = new HashSet<ConnectionRecord>();
1417 activity.connections.add(c);
1419 b.client.connections.add(c);
1420 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
1421 b.client.hasAboveClient = true;
1423 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
1424 s.whitelistManager = true;
1426 if (s.app != null) {
1427 updateServiceClientActivitiesLocked(s.app, c, true);
1429 clist = mServiceConnections.get(binder);
1430 if (clist == null) {
1431 clist = new ArrayList<ConnectionRecord>();
1432 mServiceConnections.put(binder, clist);
1436 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1437 s.lastActivity = SystemClock.uptimeMillis();
1438 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1439 permissionsReviewRequired) != null) {
1444 if (s.app != null) {
1445 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1446 s.app.treatLikeActivity = true;
1448 if (s.whitelistManager) {
1449 s.app.whitelistManager = true;
1451 // This could have made the service more important.
1452 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1453 || s.app.treatLikeActivity, b.client);
1454 mAm.updateOomAdjLocked(s.app, true);
1457 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
1458 + ": received=" + b.intent.received
1459 + " apps=" + b.intent.apps.size()
1460 + " doRebind=" + b.intent.doRebind);
1462 if (s.app != null && b.intent.received) {
1463 // Service is already running, so we can immediately
1464 // publish the connection.
1466 c.conn.connected(s.name, b.intent.binder, false);
1467 } catch (Exception e) {
1468 Slog.w(TAG, "Failure sending service " + s.shortName
1469 + " to connection " + c.conn.asBinder()
1470 + " (in " + c.binding.client.processName + ")", e);
1473 // If this is the first app connected back to this binding,
1474 // and the service had previously asked to be told when
1475 // rebound, then do so.
1476 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
1477 requestServiceBindingLocked(s, b.intent, callerFg, true);
1479 } else if (!b.intent.requested) {
1480 requestServiceBindingLocked(s, b.intent, callerFg, false);
1483 getServiceMapLocked(s.userId).ensureNotStartingBackgroundLocked(s);
1486 Binder.restoreCallingIdentity(origId);
1492 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1493 final long origId = Binder.clearCallingIdentity();
1495 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
1496 + " " + intent + ": " + service);
1498 Intent.FilterComparison filter
1499 = new Intent.FilterComparison(intent);
1500 IntentBindRecord b = r.bindings.get(filter);
1501 if (b != null && !b.received) {
1505 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1506 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1507 for (int i=0; i<clist.size(); i++) {
1508 ConnectionRecord c = clist.get(i);
1509 if (!filter.equals(c.binding.intent.intent)) {
1510 if (DEBUG_SERVICE) Slog.v(
1511 TAG_SERVICE, "Not publishing to: " + c);
1512 if (DEBUG_SERVICE) Slog.v(
1513 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
1514 if (DEBUG_SERVICE) Slog.v(
1515 TAG_SERVICE, "Published intent: " + intent);
1518 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
1520 c.conn.connected(r.name, service, false);
1521 } catch (Exception e) {
1522 Slog.w(TAG, "Failure sending service " + r.name +
1523 " to connection " + c.conn.asBinder() +
1524 " (in " + c.binding.client.processName + ")", e);
1530 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
1533 Binder.restoreCallingIdentity(origId);
1537 boolean unbindServiceLocked(IServiceConnection connection) {
1538 IBinder binder = connection.asBinder();
1539 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
1540 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1541 if (clist == null) {
1542 Slog.w(TAG, "Unbind failed: could not find connection for "
1543 + connection.asBinder());
1547 final long origId = Binder.clearCallingIdentity();
1549 while (clist.size() > 0) {
1550 ConnectionRecord r = clist.get(0);
1551 removeConnectionLocked(r, null, null);
1552 if (clist.size() > 0 && clist.get(0) == r) {
1553 // In case it didn't get removed above, do it now.
1554 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1558 if (r.binding.service.app != null) {
1559 if (r.binding.service.app.whitelistManager) {
1560 updateWhitelistManagerLocked(r.binding.service.app);
1562 // This could have made the service less important.
1563 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1564 r.binding.service.app.treatLikeActivity = true;
1565 mAm.updateLruProcessLocked(r.binding.service.app,
1566 r.binding.service.app.hasClientActivities
1567 || r.binding.service.app.treatLikeActivity, null);
1569 mAm.updateOomAdjLocked(r.binding.service.app, false);
1573 mAm.updateOomAdjLocked();
1576 Binder.restoreCallingIdentity(origId);
1582 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1583 final long origId = Binder.clearCallingIdentity();
1586 Intent.FilterComparison filter
1587 = new Intent.FilterComparison(intent);
1588 IntentBindRecord b = r.bindings.get(filter);
1589 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
1590 + " at " + b + ": apps="
1591 + (b != null ? b.apps.size() : 0));
1593 boolean inDestroying = mDestroyingServices.contains(r);
1595 if (b.apps.size() > 0 && !inDestroying) {
1596 // Applications have already bound since the last
1597 // unbind, so just rebind right here.
1598 boolean inFg = false;
1599 for (int i=b.apps.size()-1; i>=0; i--) {
1600 ProcessRecord client = b.apps.valueAt(i).client;
1601 if (client != null && client.setSchedGroup
1602 != ProcessList.SCHED_GROUP_BACKGROUND) {
1608 requestServiceBindingLocked(r, b, inFg, true);
1609 } catch (TransactionTooLargeException e) {
1610 // Don't pass this back to ActivityThread, it's unrelated.
1613 // Note to tell the service the next time there is
1619 serviceDoneExecutingLocked(r, inDestroying, false);
1622 Binder.restoreCallingIdentity(origId);
1626 private final ServiceRecord findServiceLocked(ComponentName name,
1627 IBinder token, int userId) {
1628 ServiceRecord r = getServiceByNameLocked(name, userId);
1629 return r == token ? r : null;
1632 private final class ServiceLookupResult {
1633 final ServiceRecord record;
1634 final String permission;
1636 ServiceLookupResult(ServiceRecord _record, String _permission) {
1638 permission = _permission;
1642 private class ServiceRestarter implements Runnable {
1643 private ServiceRecord mService;
1645 void setService(ServiceRecord service) {
1651 performServiceRestartLocked(mService);
1656 private ServiceLookupResult retrieveServiceLocked(Intent service,
1657 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
1658 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal) {
1659 ServiceRecord r = null;
1660 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
1661 + " type=" + resolvedType + " callingUid=" + callingUid);
1663 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1664 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
1666 ServiceMap smap = getServiceMapLocked(userId);
1667 final ComponentName comp = service.getComponent();
1669 r = smap.mServicesByName.get(comp);
1670 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by component: " + r);
1672 if (r == null && !isBindExternal) {
1673 Intent.FilterComparison filter = new Intent.FilterComparison(service);
1674 r = smap.mServicesByIntent.get(filter);
1675 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE, "Retrieved by intent: " + r);
1677 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1678 && !callingPackage.equals(r.packageName)) {
1679 // If an external service is running within its own package, other packages
1680 // should not bind to that instance.
1682 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Whoops, can't use existing external service");
1686 // TODO: come back and remove this assumption to triage all services
1687 ResolveInfo rInfo = mAm.getPackageManagerInternalLocked().resolveService(service,
1688 resolvedType, ActivityManagerService.STOCK_PM_FLAGS
1689 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1690 userId, callingUid);
1692 rInfo != null ? rInfo.serviceInfo : null;
1693 if (sInfo == null) {
1694 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
1698 ComponentName name = new ComponentName(
1699 sInfo.applicationInfo.packageName, sInfo.name);
1700 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1701 if (isBindExternal) {
1702 if (!sInfo.exported) {
1703 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1704 " is not exported");
1706 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1707 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1708 " is not an isolatedProcess");
1710 // Run the service under the calling package's application.
1711 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1712 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1713 if (aInfo == null) {
1714 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1715 "could not resolve client package " + callingPackage);
1717 sInfo = new ServiceInfo(sInfo);
1718 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1719 sInfo.applicationInfo.packageName = aInfo.packageName;
1720 sInfo.applicationInfo.uid = aInfo.uid;
1721 name = new ComponentName(aInfo.packageName, name.getClassName());
1722 service.setComponent(name);
1724 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1727 } else if (isBindExternal) {
1728 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1729 " is not an externalService");
1732 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
1733 sInfo.name, sInfo.flags)
1734 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
1736 smap = getServiceMapLocked(0);
1738 sInfo = new ServiceInfo(sInfo);
1739 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1741 r = smap.mServicesByName.get(name);
1742 if (DEBUG_SERVICE && r != null) Slog.v(TAG_SERVICE,
1743 "Retrieved via pm by intent: " + r);
1744 if (r == null && createIfNeeded) {
1745 final Intent.FilterComparison filter
1746 = new Intent.FilterComparison(service.cloneFilter());
1747 final ServiceRestarter res = new ServiceRestarter();
1748 final BatteryStatsImpl.Uid.Pkg.Serv ss;
1749 final BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
1750 synchronized (stats) {
1751 ss = stats.getServiceStatsLocked(
1752 sInfo.applicationInfo.uid, sInfo.packageName,
1755 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
1757 smap.mServicesByName.put(name, r);
1758 smap.mServicesByIntent.put(filter, r);
1760 // Make sure this component isn't in the pending list.
1761 for (int i=mPendingServices.size()-1; i>=0; i--) {
1762 final ServiceRecord pr = mPendingServices.get(i);
1763 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1764 && pr.name.equals(name)) {
1765 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Remove pending: " + pr);
1766 mPendingServices.remove(i);
1769 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Retrieve created new service: " + r);
1771 } catch (RemoteException ex) {
1772 // pm is in same process, this will never happen.
1776 if (mAm.checkComponentPermission(r.permission,
1777 callingPid, callingUid, r.appInfo.uid, r.exported) != PERMISSION_GRANTED) {
1779 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1780 + " from pid=" + callingPid
1781 + ", uid=" + callingUid
1782 + " that is not exported from uid " + r.appInfo.uid);
1783 return new ServiceLookupResult(null, "not exported from uid "
1786 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1787 + " from pid=" + callingPid
1788 + ", uid=" + callingUid
1789 + " requires " + r.permission);
1790 return new ServiceLookupResult(null, r.permission);
1791 } else if (r.permission != null && callingPackage != null) {
1792 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1793 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1794 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1795 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1796 + " from pid=" + callingPid
1797 + ", uid=" + callingUid
1798 + " requires appop " + AppOpsManager.opToName(opCode));
1803 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1804 resolvedType, r.appInfo)) {
1807 return new ServiceLookupResult(r, null);
1812 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
1813 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
1814 + why + " of " + r + " in app " + r.app);
1815 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
1816 + why + " of " + r.shortName);
1817 long now = SystemClock.uptimeMillis();
1818 if (r.executeNesting == 0) {
1820 ServiceState stracker = r.getTracker();
1821 if (stracker != null) {
1822 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
1824 if (r.app != null) {
1825 r.app.executingServices.add(r);
1826 r.app.execServicesFg |= fg;
1827 if (r.app.executingServices.size() == 1) {
1828 scheduleServiceTimeoutLocked(r.app);
1831 } else if (r.app != null && fg && !r.app.execServicesFg) {
1832 r.app.execServicesFg = true;
1833 scheduleServiceTimeoutLocked(r.app);
1837 r.executingStart = now;
1840 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
1841 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
1842 if (r.app == null || r.app.thread == null) {
1843 // If service is not currently running, can't yet bind.
1846 if (DEBUG_SERVICE) Slog.d(TAG_SERVICE, "requestBind " + i + ": requested=" + i.requested
1847 + " rebind=" + rebind);
1848 if ((!i.requested || rebind) && i.apps.size() > 0) {
1850 bumpServiceExecutingLocked(r, execInFg, "bind");
1851 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1852 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1853 r.app.repProcState);
1859 } catch (TransactionTooLargeException e) {
1860 // Keep the executeNesting count accurate.
1861 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
1862 final boolean inDestroying = mDestroyingServices.contains(r);
1863 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1865 } catch (RemoteException e) {
1866 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
1867 // Keep the executeNesting count accurate.
1868 final boolean inDestroying = mDestroyingServices.contains(r);
1869 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1876 private final boolean scheduleServiceRestartLocked(ServiceRecord r, boolean allowCancel) {
1877 boolean canceled = false;
1879 if (mAm.isShuttingDownLocked()) {
1880 Slog.w(TAG, "Not scheduling restart of crashed service " + r.shortName
1881 + " - system is shutting down");
1885 ServiceMap smap = getServiceMapLocked(r.userId);
1886 if (smap.mServicesByName.get(r.name) != r) {
1887 ServiceRecord cur = smap.mServicesByName.get(r.name);
1888 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1889 + " when found in map: " + cur);
1893 final long now = SystemClock.uptimeMillis();
1895 if ((r.serviceInfo.applicationInfo.flags
1896 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
1897 long minDuration = mAm.mConstants.SERVICE_RESTART_DURATION;
1898 long resetTime = mAm.mConstants.SERVICE_RESET_RUN_DURATION;
1900 // Any delivered but not yet finished starts should be put back
1901 // on the pending list.
1902 final int N = r.deliveredStarts.size();
1904 for (int i=N-1; i>=0; i--) {
1905 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1906 si.removeUriPermissionsLocked();
1907 if (si.intent == null) {
1908 // We'll generate this again if needed.
1909 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1910 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1911 r.pendingStarts.add(0, si);
1912 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1914 if (minDuration < dur) minDuration = dur;
1915 if (resetTime < dur) resetTime = dur;
1917 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1922 r.deliveredStarts.clear();
1925 r.totalRestartCount++;
1926 if (r.restartDelay == 0) {
1928 r.restartDelay = minDuration;
1929 } else if (r.crashCount > 1) {
1930 r.restartDelay = mAm.mConstants.BOUND_SERVICE_CRASH_RESTART_DURATION
1931 * (r.crashCount - 1);
1933 // If it has been a "reasonably long time" since the service
1934 // was started, then reset our restart duration back to
1935 // the beginning, so we don't infinitely increase the duration
1936 // on a service that just occasionally gets killed (which is
1937 // a normal case, due to process being killed to reclaim memory).
1938 if (now > (r.restartTime+resetTime)) {
1940 r.restartDelay = minDuration;
1942 r.restartDelay *= mAm.mConstants.SERVICE_RESTART_DURATION_FACTOR;
1943 if (r.restartDelay < minDuration) {
1944 r.restartDelay = minDuration;
1949 r.nextRestartTime = now + r.restartDelay;
1951 // Make sure that we don't end up restarting a bunch of services
1952 // all at the same time.
1956 final long restartTimeBetween = mAm.mConstants.SERVICE_MIN_RESTART_TIME_BETWEEN;
1957 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1958 ServiceRecord r2 = mRestartingServices.get(i);
1959 if (r2 != r && r.nextRestartTime >= (r2.nextRestartTime-restartTimeBetween)
1960 && r.nextRestartTime < (r2.nextRestartTime+restartTimeBetween)) {
1961 r.nextRestartTime = r2.nextRestartTime + restartTimeBetween;
1962 r.restartDelay = r.nextRestartTime - now;
1970 // Persistent processes are immediately restarted, so there is no
1971 // reason to hold of on restarting their services.
1972 r.totalRestartCount++;
1975 r.nextRestartTime = now;
1978 if (!mRestartingServices.contains(r)) {
1979 r.createdFromFg = false;
1980 mRestartingServices.add(r);
1981 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
1984 cancelForegroundNotificationLocked(r);
1986 mAm.mHandler.removeCallbacks(r.restarter);
1987 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
1988 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
1989 Slog.w(TAG, "Scheduling restart of crashed service "
1990 + r.shortName + " in " + r.restartDelay + "ms");
1991 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
1992 r.userId, r.shortName, r.restartDelay);
1997 final void performServiceRestartLocked(ServiceRecord r) {
1998 if (!mRestartingServices.contains(r)) {
2001 if (!isServiceNeededLocked(r, false, false)) {
2002 // Paranoia: is this service actually needed? In theory a service that is not
2003 // needed should never remain on the restart list. In practice... well, there
2004 // have been bugs where this happens, and bad things happen because the process
2005 // ends up just being cached, so quickly killed, then restarted again and again.
2006 // Let's not let that happen.
2007 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
2011 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
2012 } catch (TransactionTooLargeException e) {
2013 // Ignore, it's been logged and nothing upstack cares.
2017 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
2019 if (!force && r.restartDelay == 0) {
2022 // Remove from the restarting list; if the service is currently on the
2023 // restarting list, or the call is coming from another app, then this
2024 // service has become of much more interest so we reset the restart interval.
2025 boolean removed = mRestartingServices.remove(r);
2026 if (removed || callingUid != r.appInfo.uid) {
2027 r.resetRestartCounter();
2030 clearRestartingIfNeededLocked(r);
2032 mAm.mHandler.removeCallbacks(r.restarter);
2036 private void clearRestartingIfNeededLocked(ServiceRecord r) {
2037 if (r.restartTracker != null) {
2038 // If this is the last restarting record with this tracker, then clear
2039 // the tracker's restarting state.
2040 boolean stillTracking = false;
2041 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2042 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
2043 stillTracking = true;
2047 if (!stillTracking) {
2048 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
2049 SystemClock.uptimeMillis());
2050 r.restartTracker = null;
2055 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
2056 boolean whileRestarting, boolean permissionsReviewRequired)
2057 throws TransactionTooLargeException {
2058 //Slog.i(TAG, "Bring up service:");
2061 if (r.app != null && r.app.thread != null) {
2062 sendServiceArgsLocked(r, execInFg, false);
2066 if (!whileRestarting && mRestartingServices.contains(r)) {
2067 // If waiting for a restart, then do nothing.
2071 if (DEBUG_SERVICE) {
2072 Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent + " fg=" + r.fgRequired);
2075 // We are now bringing the service up, so no longer in the
2076 // restarting state.
2077 if (mRestartingServices.remove(r)) {
2078 clearRestartingIfNeededLocked(r);
2081 // Make sure this service is no longer considered delayed, we are starting it now.
2083 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
2084 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
2088 // Make sure that the user who owns this service is started. If not,
2089 // we don't want to allow it to run.
2090 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
2091 String msg = "Unable to launch app "
2092 + r.appInfo.packageName + "/"
2093 + r.appInfo.uid + " for service "
2094 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
2096 bringDownServiceLocked(r);
2100 // Service is now being launched, its package can't be stopped.
2102 AppGlobals.getPackageManager().setPackageStoppedState(
2103 r.packageName, false, r.userId);
2104 } catch (RemoteException e) {
2105 } catch (IllegalArgumentException e) {
2106 Slog.w(TAG, "Failed trying to unstop package "
2107 + r.packageName + ": " + e);
2110 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
2111 final String procName = r.processName;
2112 String hostingType = "service";
2116 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
2117 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
2119 if (app != null && app.thread != null) {
2121 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
2122 realStartServiceLocked(r, app, execInFg);
2124 } catch (TransactionTooLargeException e) {
2126 } catch (RemoteException e) {
2127 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
2130 // If a dead object exception was thrown -- fall through to
2131 // restart the application.
2134 // If this service runs in an isolated process, then each time
2135 // we call startProcessLocked() we will get a new isolated
2136 // process, starting another process if we are currently waiting
2137 // for a previous process to come up. To deal with this, we store
2138 // in the service any current isolated process it is running in or
2139 // waiting to have come up.
2140 app = r.isolatedProc;
2141 if (WebViewZygote.isMultiprocessEnabled()
2142 && r.serviceInfo.packageName.equals(WebViewZygote.getPackageName())) {
2143 hostingType = "webview_service";
2147 // Not running -- get it started, and enqueue this service record
2148 // to be executed when the app comes up.
2149 if (app == null && !permissionsReviewRequired) {
2150 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
2151 hostingType, r.name, false, isolated, false)) == null) {
2152 String msg = "Unable to launch app "
2153 + r.appInfo.packageName + "/"
2154 + r.appInfo.uid + " for service "
2155 + r.intent.getIntent() + ": process is bad";
2157 bringDownServiceLocked(r);
2161 r.isolatedProc = app;
2166 if (DEBUG_FOREGROUND_SERVICE) {
2167 Slog.v(TAG, "Whitelisting " + UserHandle.formatUid(r.appInfo.uid)
2168 + " for fg-service launch");
2170 mAm.tempWhitelistUidLocked(r.appInfo.uid,
2171 SERVICE_START_FOREGROUND_TIMEOUT, "fg-service-launch");
2174 if (!mPendingServices.contains(r)) {
2175 mPendingServices.add(r);
2178 if (r.delayedStop) {
2179 // Oh and hey we've already been asked to stop!
2180 r.delayedStop = false;
2181 if (r.startRequested) {
2182 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2183 "Applying delayed stop (in bring up): " + r);
2184 stopServiceLocked(r);
2191 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
2192 throws TransactionTooLargeException {
2193 for (int i=r.bindings.size()-1; i>=0; i--) {
2194 IntentBindRecord ibr = r.bindings.valueAt(i);
2195 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
2201 private final void realStartServiceLocked(ServiceRecord r,
2202 ProcessRecord app, boolean execInFg) throws RemoteException {
2203 if (app.thread == null) {
2204 throw new RemoteException();
2207 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
2208 + ", ProcessRecord.uid = " + app.uid);
2210 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
2212 final boolean newService = app.services.add(r);
2213 bumpServiceExecutingLocked(r, execInFg, "create");
2214 mAm.updateLruProcessLocked(app, false, null);
2215 updateServiceForegroundLocked(r.app, /* oomAdj= */ false);
2216 mAm.updateOomAdjLocked();
2218 boolean created = false;
2220 if (LOG_SERVICE_START_STOP) {
2222 int lastPeriod = r.shortName.lastIndexOf('.');
2223 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
2224 EventLogTags.writeAmCreateService(
2225 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
2227 synchronized (r.stats.getBatteryStats()) {
2228 r.stats.startLaunchedLocked();
2230 mAm.notifyPackageUse(r.serviceInfo.packageName,
2231 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
2232 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
2233 app.thread.scheduleCreateService(r, r.serviceInfo,
2234 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
2236 r.postNotification();
2238 } catch (DeadObjectException e) {
2239 Slog.w(TAG, "Application dead when creating service " + r);
2240 mAm.appDiedLocked(app);
2244 // Keep the executeNesting count accurate.
2245 final boolean inDestroying = mDestroyingServices.contains(r);
2246 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2250 app.services.remove(r);
2255 if (!inDestroying) {
2256 scheduleServiceRestartLocked(r, false);
2261 if (r.whitelistManager) {
2262 app.whitelistManager = true;
2265 requestServiceBindingsLocked(r, execInFg);
2267 updateServiceClientActivitiesLocked(app, null, true);
2269 // If the service is in the started state, and there are no
2270 // pending arguments, then fake up one so its onStartCommand() will
2272 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
2273 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
2277 sendServiceArgsLocked(r, execInFg, true);
2280 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
2281 getServiceMapLocked(r.userId).mDelayedStartList.remove(r);
2285 if (r.delayedStop) {
2286 // Oh and hey we've already been asked to stop!
2287 r.delayedStop = false;
2288 if (r.startRequested) {
2289 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
2290 "Applying delayed stop (from start): " + r);
2291 stopServiceLocked(r);
2296 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
2297 boolean oomAdjusted) throws TransactionTooLargeException {
2298 final int N = r.pendingStarts.size();
2303 ArrayList<ServiceStartArgs> args = new ArrayList<>();
2305 while (r.pendingStarts.size() > 0) {
2306 ServiceRecord.StartItem si = r.pendingStarts.remove(0);
2307 if (DEBUG_SERVICE) {
2308 Slog.v(TAG_SERVICE, "Sending arguments to: "
2309 + r + " " + r.intent + " args=" + si.intent);
2311 if (si.intent == null && N > 1) {
2312 // If somehow we got a dummy null intent in the middle,
2313 // then skip it. DO NOT skip a null intent when it is
2314 // the only one in the list -- this is to support the
2315 // onStartCommand(null) case.
2318 si.deliveredTime = SystemClock.uptimeMillis();
2319 r.deliveredStarts.add(si);
2321 if (si.neededGrants != null) {
2322 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
2323 si.getUriPermissionsLocked());
2325 mAm.grantEphemeralAccessLocked(r.userId, si.intent,
2326 r.appInfo.uid, UserHandle.getAppId(si.callingId));
2327 bumpServiceExecutingLocked(r, execInFg, "start");
2330 mAm.updateOomAdjLocked(r.app, true);
2332 if (r.fgRequired && !r.fgWaiting) {
2333 if (!r.isForeground) {
2334 if (DEBUG_BACKGROUND_CHECK) {
2335 Slog.i(TAG, "Launched service must call startForeground() within timeout: " + r);
2337 scheduleServiceForegroundTransitionTimeoutLocked(r);
2339 if (DEBUG_BACKGROUND_CHECK) {
2340 Slog.i(TAG, "Service already foreground; no new timeout: " + r);
2342 r.fgRequired = false;
2346 if (si.deliveryCount > 1) {
2347 flags |= Service.START_FLAG_RETRY;
2349 if (si.doneExecutingCount > 0) {
2350 flags |= Service.START_FLAG_REDELIVERY;
2352 args.add(new ServiceStartArgs(si.taskRemoved, si.id, flags, si.intent));
2355 ParceledListSlice<ServiceStartArgs> slice = new ParceledListSlice<>(args);
2356 slice.setInlineCountLimit(4);
2357 Exception caughtException = null;
2359 r.app.thread.scheduleServiceArgs(r, slice);
2360 } catch (TransactionTooLargeException e) {
2361 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large for " + args.size()
2362 + " args, first: " + args.get(0).args);
2363 Slog.w(TAG, "Failed delivering service starts", e);
2364 caughtException = e;
2365 } catch (RemoteException e) {
2366 // Remote process gone... we'll let the normal cleanup take care of this.
2367 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
2368 Slog.w(TAG, "Failed delivering service starts", e);
2369 caughtException = e;
2370 } catch (Exception e) {
2371 Slog.w(TAG, "Unexpected exception", e);
2372 caughtException = e;
2375 if (caughtException != null) {
2376 // Keep nesting count correct
2377 final boolean inDestroying = mDestroyingServices.contains(r);
2378 for (int i = 0; i < args.size(); i++) {
2379 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2381 if (caughtException instanceof TransactionTooLargeException) {
2382 throw (TransactionTooLargeException)caughtException;
2387 private final boolean isServiceNeededLocked(ServiceRecord r, boolean knowConn,
2389 // Are we still explicitly being asked to run?
2390 if (r.startRequested) {
2394 // Is someone still bound to us keeping us running?
2396 hasConn = r.hasAutoCreateConnections();
2405 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
2407 //Slog.i(TAG, "Bring down service:");
2410 if (isServiceNeededLocked(r, knowConn, hasConn)) {
2414 // Are we in the process of launching?
2415 if (mPendingServices.contains(r)) {
2419 bringDownServiceLocked(r);
2422 private final void bringDownServiceLocked(ServiceRecord r) {
2423 //Slog.i(TAG, "Bring down service:");
2426 // Report to all of the connections that the service is no longer
2428 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2429 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
2430 for (int i=0; i<c.size(); i++) {
2431 ConnectionRecord cr = c.get(i);
2432 // There is still a connection to the service that is
2433 // being brought down. Mark it as dead.
2434 cr.serviceDead = true;
2436 cr.conn.connected(r.name, null, true);
2437 } catch (Exception e) {
2438 Slog.w(TAG, "Failure disconnecting service " + r.name +
2439 " to connection " + c.get(i).conn.asBinder() +
2440 " (in " + c.get(i).binding.client.processName + ")", e);
2445 // Tell the service that it has been unbound.
2446 if (r.app != null && r.app.thread != null) {
2447 for (int i=r.bindings.size()-1; i>=0; i--) {
2448 IntentBindRecord ibr = r.bindings.valueAt(i);
2449 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
2450 + ": hasBound=" + ibr.hasBound);
2453 bumpServiceExecutingLocked(r, false, "bring down unbind");
2454 mAm.updateOomAdjLocked(r.app, true);
2455 ibr.hasBound = false;
2456 ibr.requested = false;
2457 r.app.thread.scheduleUnbindService(r,
2458 ibr.intent.getIntent());
2459 } catch (Exception e) {
2460 Slog.w(TAG, "Exception when unbinding service "
2462 serviceProcessGoneLocked(r);
2468 // Check to see if the service had been started as foreground, but being
2469 // brought down before actually showing a notification. That is not allowed.
2471 Slog.w(TAG_SERVICE, "Bringing down service while still waiting for start foreground: "
2473 r.fgRequired = false;
2474 r.fgWaiting = false;
2475 mAm.mHandler.removeMessages(
2476 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG, r);
2477 if (r.app != null) {
2478 Message msg = mAm.mHandler.obtainMessage(
2479 ActivityManagerService.SERVICE_FOREGROUND_CRASH_MSG);
2481 mAm.mHandler.sendMessage(msg);
2485 if (DEBUG_SERVICE) {
2486 RuntimeException here = new RuntimeException();
2487 here.fillInStackTrace();
2488 Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent, here);
2490 r.destroyTime = SystemClock.uptimeMillis();
2491 if (LOG_SERVICE_START_STOP) {
2492 EventLogTags.writeAmDestroyService(
2493 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
2496 final ServiceMap smap = getServiceMapLocked(r.userId);
2497 ServiceRecord found = smap.mServicesByName.remove(r.name);
2499 // Note when this method is called by bringUpServiceLocked(), the service is not found
2500 // in mServicesByName and found will be null.
2501 if (found != null && found != r) {
2502 // This is not actually the service we think is running... this should not happen,
2503 // but if it does, fail hard.
2504 smap.mServicesByName.put(r.name, found);
2505 throw new IllegalStateException("Bringing down " + r + " but actually running "
2508 smap.mServicesByIntent.remove(r.intent);
2509 r.totalRestartCount = 0;
2510 unscheduleServiceRestartLocked(r, 0, true);
2512 // Also make sure it is not on the pending list.
2513 for (int i=mPendingServices.size()-1; i>=0; i--) {
2514 if (mPendingServices.get(i) == r) {
2515 mPendingServices.remove(i);
2516 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
2520 cancelForegroundNotificationLocked(r);
2521 if (r.isForeground) {
2522 decActiveForegroundAppLocked(smap, r);
2524 r.isForeground = false;
2526 r.foregroundNoti = null;
2528 // Clear start entries.
2529 r.clearDeliveredStartsLocked();
2530 r.pendingStarts.clear();
2532 if (r.app != null) {
2533 synchronized (r.stats.getBatteryStats()) {
2534 r.stats.stopLaunchedLocked();
2536 r.app.services.remove(r);
2537 if (r.whitelistManager) {
2538 updateWhitelistManagerLocked(r.app);
2540 if (r.app.thread != null) {
2541 updateServiceForegroundLocked(r.app, false);
2543 bumpServiceExecutingLocked(r, false, "destroy");
2544 mDestroyingServices.add(r);
2545 r.destroying = true;
2546 mAm.updateOomAdjLocked(r.app, true);
2547 r.app.thread.scheduleStopService(r);
2548 } catch (Exception e) {
2549 Slog.w(TAG, "Exception when destroying service "
2551 serviceProcessGoneLocked(r);
2554 if (DEBUG_SERVICE) Slog.v(
2555 TAG_SERVICE, "Removed service that has no process: " + r);
2558 if (DEBUG_SERVICE) Slog.v(
2559 TAG_SERVICE, "Removed service that is not running: " + r);
2562 if (r.bindings.size() > 0) {
2566 if (r.restarter instanceof ServiceRestarter) {
2567 ((ServiceRestarter)r.restarter).setService(null);
2570 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2571 long now = SystemClock.uptimeMillis();
2572 if (r.tracker != null) {
2573 r.tracker.setStarted(false, memFactor, now);
2574 r.tracker.setBound(false, memFactor, now);
2575 if (r.executeNesting == 0) {
2576 r.tracker.clearCurrentOwner(r, false);
2581 smap.ensureNotStartingBackgroundLocked(r);
2584 void removeConnectionLocked(
2585 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2586 IBinder binder = c.conn.asBinder();
2587 AppBindRecord b = c.binding;
2588 ServiceRecord s = b.service;
2589 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2590 if (clist != null) {
2592 if (clist.size() == 0) {
2593 s.connections.remove(binder);
2596 b.connections.remove(c);
2597 if (c.activity != null && c.activity != skipAct) {
2598 if (c.activity.connections != null) {
2599 c.activity.connections.remove(c);
2602 if (b.client != skipApp) {
2603 b.client.connections.remove(c);
2604 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2605 b.client.updateHasAboveClientLocked();
2607 // If this connection requested whitelist management, see if we should
2608 // now clear that state.
2609 if ((c.flags&Context.BIND_ALLOW_WHITELIST_MANAGEMENT) != 0) {
2610 s.updateWhitelistManager();
2611 if (!s.whitelistManager && s.app != null) {
2612 updateWhitelistManagerLocked(s.app);
2615 if (s.app != null) {
2616 updateServiceClientActivitiesLocked(s.app, c, true);
2619 clist = mServiceConnections.get(binder);
2620 if (clist != null) {
2622 if (clist.size() == 0) {
2623 mServiceConnections.remove(binder);
2627 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2629 if (b.connections.size() == 0) {
2630 b.intent.apps.remove(b.client);
2633 if (!c.serviceDead) {
2634 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
2635 + ": shouldUnbind=" + b.intent.hasBound);
2636 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2637 && b.intent.hasBound) {
2639 bumpServiceExecutingLocked(s, false, "unbind");
2640 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
2641 && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
2642 // If this service's process is not already in the cached list,
2643 // then update it in the LRU list here because this may be causing
2644 // it to go down there and we want it to start out near the top.
2645 mAm.updateLruProcessLocked(s.app, false, null);
2647 mAm.updateOomAdjLocked(s.app, true);
2648 b.intent.hasBound = false;
2649 // Assume the client doesn't want to know about a rebind;
2650 // we will deal with that later if it asks for one.
2651 b.intent.doRebind = false;
2652 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2653 } catch (Exception e) {
2654 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
2655 serviceProcessGoneLocked(s);
2659 // If unbound while waiting to start, remove the pending service
2660 mPendingServices.remove(s);
2662 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
2663 boolean hasAutoCreate = s.hasAutoCreateConnections();
2664 if (!hasAutoCreate) {
2665 if (s.tracker != null) {
2666 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
2667 SystemClock.uptimeMillis());
2670 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
2675 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
2676 boolean inDestroying = mDestroyingServices.contains(r);
2678 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
2679 // This is a call from a service start... take care of
2683 case Service.START_STICKY_COMPATIBILITY:
2684 case Service.START_STICKY: {
2685 // We are done with the associated start arguments.
2686 r.findDeliveredStart(startId, true);
2687 // Don't stop if killed.
2688 r.stopIfKilled = false;
2691 case Service.START_NOT_STICKY: {
2692 // We are done with the associated start arguments.
2693 r.findDeliveredStart(startId, true);
2694 if (r.getLastStartId() == startId) {
2695 // There is no more work, and this service
2696 // doesn't want to hang around if killed.
2697 r.stopIfKilled = true;
2701 case Service.START_REDELIVER_INTENT: {
2702 // We'll keep this item until they explicitly
2703 // call stop for it, but keep track of the fact
2704 // that it was delivered.
2705 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2707 si.deliveryCount = 0;
2708 si.doneExecutingCount++;
2709 // Don't stop if killed.
2710 r.stopIfKilled = true;
2714 case Service.START_TASK_REMOVED_COMPLETE: {
2715 // Special processing for onTaskRemoved(). Don't
2716 // impact normal onStartCommand() processing.
2717 r.findDeliveredStart(startId, true);
2721 throw new IllegalArgumentException(
2722 "Unknown service start result: " + res);
2724 if (res == Service.START_STICKY_COMPATIBILITY) {
2725 r.callStart = false;
2727 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2728 // This is the final call from destroying the service... we should
2729 // actually be getting rid of the service at this point. Do some
2730 // validation of its state, and ensure it will be fully removed.
2731 if (!inDestroying) {
2732 // Not sure what else to do with this... if it is not actually in the
2733 // destroying list, we don't need to make sure to remove it from it.
2734 // If the app is null, then it was probably removed because the process died,
2736 if (r.app != null) {
2737 Slog.w(TAG, "Service done with onDestroy, but not inDestroying: "
2738 + r + ", app=" + r.app);
2740 } else if (r.executeNesting != 1) {
2741 Slog.w(TAG, "Service done with onDestroy, but executeNesting="
2742 + r.executeNesting + ": " + r);
2743 // Fake it to keep from ANR due to orphaned entry.
2744 r.executeNesting = 1;
2747 final long origId = Binder.clearCallingIdentity();
2748 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2749 Binder.restoreCallingIdentity(origId);
2751 Slog.w(TAG, "Done executing unknown service from pid "
2752 + Binder.getCallingPid());
2756 private void serviceProcessGoneLocked(ServiceRecord r) {
2757 if (r.tracker != null) {
2758 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2759 long now = SystemClock.uptimeMillis();
2760 r.tracker.setExecuting(false, memFactor, now);
2761 r.tracker.setBound(false, memFactor, now);
2762 r.tracker.setStarted(false, memFactor, now);
2764 serviceDoneExecutingLocked(r, true, true);
2767 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2768 boolean finishing) {
2769 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
2770 + ": nesting=" + r.executeNesting
2771 + ", inDestroying=" + inDestroying + ", app=" + r.app);
2772 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2773 "<<< DONE EXECUTING " + r.shortName);
2775 if (r.executeNesting <= 0) {
2776 if (r.app != null) {
2777 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
2778 "Nesting at 0 of " + r.shortName);
2779 r.app.execServicesFg = false;
2780 r.app.executingServices.remove(r);
2781 if (r.app.executingServices.size() == 0) {
2782 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2783 "No more executingServices of " + r.shortName);
2784 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
2785 } else if (r.executeFg) {
2786 // Need to re-evaluate whether the app still needs to be in the foreground.
2787 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2788 if (r.app.executingServices.valueAt(i).executeFg) {
2789 r.app.execServicesFg = true;
2795 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
2796 "doneExecuting remove destroying " + r);
2797 mDestroyingServices.remove(r);
2800 mAm.updateOomAdjLocked(r.app, true);
2802 r.executeFg = false;
2803 if (r.tracker != null) {
2804 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
2805 SystemClock.uptimeMillis());
2807 r.tracker.clearCurrentOwner(r, false);
2812 if (r.app != null && !r.app.persistent) {
2813 r.app.services.remove(r);
2814 if (r.whitelistManager) {
2815 updateWhitelistManagerLocked(r.app);
2823 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2824 throws RemoteException {
2825 boolean didSomething = false;
2826 // Collect any services that are waiting for this process to come up.
2827 if (mPendingServices.size() > 0) {
2828 ServiceRecord sr = null;
2830 for (int i=0; i<mPendingServices.size(); i++) {
2831 sr = mPendingServices.get(i);
2832 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2833 || !processName.equals(sr.processName))) {
2837 mPendingServices.remove(i);
2839 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2841 realStartServiceLocked(sr, proc, sr.createdFromFg);
2842 didSomething = true;
2843 if (!isServiceNeededLocked(sr, false, false)) {
2844 // We were waiting for this service to start, but it is actually no
2845 // longer needed. This could happen because bringDownServiceIfNeeded
2846 // won't bring down a service that is pending... so now the pending
2847 // is done, so let's drop it.
2848 bringDownServiceLocked(sr);
2851 } catch (RemoteException e) {
2852 Slog.w(TAG, "Exception in new application when starting service "
2857 // Also, if there are any services that are waiting to restart and
2858 // would run in this process, now is a good time to start them. It would
2859 // be weird to bring up the process but arbitrarily not let the services
2860 // run at this point just because their restart time hasn't come up.
2861 if (mRestartingServices.size() > 0) {
2863 for (int i=0; i<mRestartingServices.size(); i++) {
2864 sr = mRestartingServices.get(i);
2865 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2866 || !processName.equals(sr.processName))) {
2869 mAm.mHandler.removeCallbacks(sr.restarter);
2870 mAm.mHandler.post(sr.restarter);
2873 return didSomething;
2876 void processStartTimedOutLocked(ProcessRecord proc) {
2877 for (int i=0; i<mPendingServices.size(); i++) {
2878 ServiceRecord sr = mPendingServices.get(i);
2879 if ((proc.uid == sr.appInfo.uid
2880 && proc.processName.equals(sr.processName))
2881 || sr.isolatedProc == proc) {
2882 Slog.w(TAG, "Forcing bringing down service: " + sr);
2883 sr.isolatedProc = null;
2884 mPendingServices.remove(i);
2886 bringDownServiceLocked(sr);
2891 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
2892 boolean evenPersistent, boolean doit, boolean killProcess,
2893 ArrayMap<ComponentName, ServiceRecord> services) {
2894 boolean didSomething = false;
2895 for (int i = services.size() - 1; i >= 0; i--) {
2896 ServiceRecord service = services.valueAt(i);
2897 final boolean sameComponent = packageName == null
2898 || (service.packageName.equals(packageName)
2899 && (filterByClasses == null
2900 || filterByClasses.contains(service.name.getClassName())));
2902 && (service.app == null || evenPersistent || !service.app.persistent)) {
2906 didSomething = true;
2907 Slog.i(TAG, " Force stopping service " + service);
2908 if (service.app != null) {
2909 service.app.removed = killProcess;
2910 if (!service.app.persistent) {
2911 service.app.services.remove(service);
2912 if (service.whitelistManager) {
2913 updateWhitelistManagerLocked(service.app);
2918 service.isolatedProc = null;
2919 if (mTmpCollectionResults == null) {
2920 mTmpCollectionResults = new ArrayList<>();
2922 mTmpCollectionResults.add(service);
2925 return didSomething;
2928 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
2929 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
2930 boolean didSomething = false;
2932 if (mTmpCollectionResults != null) {
2933 mTmpCollectionResults.clear();
2936 if (userId == UserHandle.USER_ALL) {
2937 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2938 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
2939 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
2940 if (!doit && didSomething) {
2943 if (doit && filterByClasses == null) {
2944 forceStopPackageLocked(packageName, mServiceMap.valueAt(i).mUserId);
2948 ServiceMap smap = mServiceMap.get(userId);
2950 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
2951 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
2952 evenPersistent, doit, killProcess, items);
2954 if (doit && filterByClasses == null) {
2955 forceStopPackageLocked(packageName, userId);
2959 if (mTmpCollectionResults != null) {
2960 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2961 bringDownServiceLocked(mTmpCollectionResults.get(i));
2963 mTmpCollectionResults.clear();
2966 return didSomething;
2969 void forceStopPackageLocked(String packageName, int userId) {
2970 ServiceMap smap = mServiceMap.get(userId);
2971 if (smap != null && smap.mActiveForegroundApps.size() > 0) {
2972 for (int i = smap.mActiveForegroundApps.size()-1; i >= 0; i--) {
2973 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
2974 if (aa.mPackageName.equals(packageName)) {
2975 smap.mActiveForegroundApps.removeAt(i);
2976 smap.mActiveForegroundAppsChanged = true;
2979 if (smap.mActiveForegroundAppsChanged) {
2980 requestUpdateActiveForegroundAppsLocked(smap, 0);
2985 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
2986 ArrayList<ServiceRecord> services = new ArrayList<>();
2987 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(tr.userId);
2988 for (int i = alls.size() - 1; i >= 0; i--) {
2989 ServiceRecord sr = alls.valueAt(i);
2990 if (sr.packageName.equals(component.getPackageName())) {
2995 // Take care of any running services associated with the app.
2996 for (int i = services.size() - 1; i >= 0; i--) {
2997 ServiceRecord sr = services.get(i);
2998 if (sr.startRequested) {
2999 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
3000 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
3001 stopServiceLocked(sr);
3003 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
3004 sr.makeNextStartId(), baseIntent, null, 0));
3005 if (sr.app != null && sr.app.thread != null) {
3006 // We always run in the foreground, since this is called as
3007 // part of the "remove task" UI operation.
3009 sendServiceArgsLocked(sr, true, false);
3010 } catch (TransactionTooLargeException e) {
3011 // Ignore, keep going.
3019 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
3020 // Report disconnected services.
3022 // XXX we are letting the client link to the service for
3023 // death notifications.
3024 if (app.services.size() > 0) {
3025 Iterator<ServiceRecord> it = app.services.iterator();
3026 while (it.hasNext()) {
3027 ServiceRecord r = it.next();
3028 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3029 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
3030 for (int i=0; i<cl.size(); i++) {
3031 ConnectionRecord c = cl.get(i);
3032 if (c.binding.client != app) {
3034 //c.conn.connected(r.className, null);
3035 } catch (Exception e) {
3036 // todo: this should be asynchronous!
3037 Slog.w(TAG, "Exception thrown disconnected servce "
3039 + " from app " + app.processName, e);
3048 // Clean up any connections this application has to other services.
3049 for (int i = app.connections.size() - 1; i >= 0; i--) {
3050 ConnectionRecord r = app.connections.valueAt(i);
3051 removeConnectionLocked(r, app, null);
3053 updateServiceConnectionActivitiesLocked(app);
3054 app.connections.clear();
3056 app.whitelistManager = false;
3058 // Clear app state from services.
3059 for (int i = app.services.size() - 1; i >= 0; i--) {
3060 ServiceRecord sr = app.services.valueAt(i);
3061 synchronized (sr.stats.getBatteryStats()) {
3062 sr.stats.stopLaunchedLocked();
3064 if (sr.app != app && sr.app != null && !sr.app.persistent) {
3065 sr.app.services.remove(sr);
3068 sr.isolatedProc = null;
3069 sr.executeNesting = 0;
3070 sr.forceClearTracker();
3071 if (mDestroyingServices.remove(sr)) {
3072 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
3075 final int numClients = sr.bindings.size();
3076 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
3077 IntentBindRecord b = sr.bindings.valueAt(bindingi);
3078 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
3079 + ": shouldUnbind=" + b.hasBound);
3081 b.requested = b.received = b.hasBound = false;
3082 // If this binding is coming from a cached process and is asking to keep
3083 // the service created, then we'll kill the cached process as well -- we
3084 // don't want to be thrashing around restarting processes that are only
3085 // there to be cached.
3086 for (int appi=b.apps.size()-1; appi>=0; appi--) {
3087 final ProcessRecord proc = b.apps.keyAt(appi);
3088 // If the process is already gone, skip it.
3089 if (proc.killedByAm || proc.thread == null) {
3092 // Only do this for processes that have an auto-create binding;
3093 // otherwise the binding can be left, because it won't cause the
3094 // service to restart.
3095 final AppBindRecord abind = b.apps.valueAt(appi);
3096 boolean hasCreate = false;
3097 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
3098 ConnectionRecord conn = abind.connections.valueAt(conni);
3099 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
3100 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
3108 // XXX turned off for now until we have more time to get a better policy.
3109 if (false && proc != null && !proc.persistent && proc.thread != null
3110 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
3111 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
3112 proc.kill("bound to service " + sr.name.flattenToShortString()
3113 + " in dying proc " + (app != null ? app.processName : "??"), true);
3119 ServiceMap smap = getServiceMapLocked(app.userId);
3121 // Now do remaining service cleanup.
3122 for (int i=app.services.size()-1; i>=0; i--) {
3123 ServiceRecord sr = app.services.valueAt(i);
3125 // Unless the process is persistent, this process record is going away,
3126 // so make sure the service is cleaned out of it.
3127 if (!app.persistent) {
3128 app.services.removeAt(i);
3131 // Sanity check: if the service listed for the app is not one
3132 // we actually are maintaining, just let it drop.
3133 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
3135 if (curRec != null) {
3136 Slog.wtf(TAG, "Service " + sr + " in process " + app
3137 + " not same as in map: " + curRec);
3142 // Any services running in the application may need to be placed
3143 // back in the pending list.
3144 if (allowRestart && sr.crashCount >= mAm.mConstants.BOUND_SERVICE_MAX_CRASH_RETRY
3145 && (sr.serviceInfo.applicationInfo.flags
3146 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
3147 Slog.w(TAG, "Service crashed " + sr.crashCount
3148 + " times, stopping: " + sr);
3149 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
3150 sr.userId, sr.crashCount, sr.shortName, app.pid);
3151 bringDownServiceLocked(sr);
3152 } else if (!allowRestart
3153 || !mAm.mUserController.isUserRunningLocked(sr.userId, 0)) {
3154 bringDownServiceLocked(sr);
3156 boolean canceled = scheduleServiceRestartLocked(sr, true);
3158 // Should the service remain running? Note that in the
3159 // extreme case of so many attempts to deliver a command
3160 // that it failed we also will stop it here.
3161 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
3162 if (sr.pendingStarts.size() == 0) {
3163 sr.startRequested = false;
3164 if (sr.tracker != null) {
3165 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
3166 SystemClock.uptimeMillis());
3168 if (!sr.hasAutoCreateConnections()) {
3169 // Whoops, no reason to restart!
3170 bringDownServiceLocked(sr);
3177 if (!allowRestart) {
3178 app.services.clear();
3180 // Make sure there are no more restarting services for this process.
3181 for (int i=mRestartingServices.size()-1; i>=0; i--) {
3182 ServiceRecord r = mRestartingServices.get(i);
3183 if (r.processName.equals(app.processName) &&
3184 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3185 mRestartingServices.remove(i);
3186 clearRestartingIfNeededLocked(r);
3189 for (int i=mPendingServices.size()-1; i>=0; i--) {
3190 ServiceRecord r = mPendingServices.get(i);
3191 if (r.processName.equals(app.processName) &&
3192 r.serviceInfo.applicationInfo.uid == app.info.uid) {
3193 mPendingServices.remove(i);
3198 // Make sure we have no more records on the stopping list.
3199 int i = mDestroyingServices.size();
3202 ServiceRecord sr = mDestroyingServices.get(i);
3203 if (sr.app == app) {
3204 sr.forceClearTracker();
3205 mDestroyingServices.remove(i);
3206 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
3210 app.executingServices.clear();
3213 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
3214 ActivityManager.RunningServiceInfo info =
3215 new ActivityManager.RunningServiceInfo();
3216 info.service = r.name;
3217 if (r.app != null) {
3218 info.pid = r.app.pid;
3220 info.uid = r.appInfo.uid;
3221 info.process = r.processName;
3222 info.foreground = r.isForeground;
3223 info.activeSince = r.createTime;
3224 info.started = r.startRequested;
3225 info.clientCount = r.connections.size();
3226 info.crashCount = r.crashCount;
3227 info.lastActivityTime = r.lastActivity;
3228 if (r.isForeground) {
3229 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
3231 if (r.startRequested) {
3232 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
3234 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
3235 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
3237 if (r.app != null && r.app.persistent) {
3238 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
3241 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3242 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
3243 for (int i=0; i<connl.size(); i++) {
3244 ConnectionRecord conn = connl.get(i);
3245 if (conn.clientLabel != 0) {
3246 info.clientPackage = conn.binding.client.info.packageName;
3247 info.clientLabel = conn.clientLabel;
3255 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum, int flags,
3256 int callingUid, boolean allowed, boolean canInteractAcrossUsers) {
3257 ArrayList<ActivityManager.RunningServiceInfo> res
3258 = new ArrayList<ActivityManager.RunningServiceInfo>();
3260 final long ident = Binder.clearCallingIdentity();
3262 if (canInteractAcrossUsers) {
3263 int[] users = mAm.mUserController.getUsers();
3264 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
3265 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(users[ui]);
3266 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3267 ServiceRecord sr = alls.valueAt(i);
3268 res.add(makeRunningServiceInfoLocked(sr));
3272 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3273 ServiceRecord r = mRestartingServices.get(i);
3274 ActivityManager.RunningServiceInfo info =
3275 makeRunningServiceInfoLocked(r);
3276 info.restarting = r.nextRestartTime;
3280 int userId = UserHandle.getUserId(callingUid);
3281 ArrayMap<ComponentName, ServiceRecord> alls = getServicesLocked(userId);
3282 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
3283 ServiceRecord sr = alls.valueAt(i);
3285 if (allowed || (sr.app != null && sr.app.uid == callingUid)) {
3286 res.add(makeRunningServiceInfoLocked(sr));
3290 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
3291 ServiceRecord r = mRestartingServices.get(i);
3292 if (r.userId == userId
3293 && (allowed || (r.app != null && r.app.uid == callingUid))) {
3294 ActivityManager.RunningServiceInfo info =
3295 makeRunningServiceInfoLocked(r);
3296 info.restarting = r.nextRestartTime;
3302 Binder.restoreCallingIdentity(ident);
3308 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
3309 int userId = UserHandle.getUserId(Binder.getCallingUid());
3310 ServiceRecord r = getServiceByNameLocked(name, userId);
3312 for (int conni=r.connections.size()-1; conni>=0; conni--) {
3313 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
3314 for (int i=0; i<conn.size(); i++) {
3315 if (conn.get(i).clientIntent != null) {
3316 return conn.get(i).clientIntent;
3324 void serviceTimeout(ProcessRecord proc) {
3325 String anrMessage = null;
3328 if (proc.executingServices.size() == 0 || proc.thread == null) {
3331 final long now = SystemClock.uptimeMillis();
3332 final long maxTime = now -
3333 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3334 ServiceRecord timeout = null;
3336 for (int i=proc.executingServices.size()-1; i>=0; i--) {
3337 ServiceRecord sr = proc.executingServices.valueAt(i);
3338 if (sr.executingStart < maxTime) {
3342 if (sr.executingStart > nextTime) {
3343 nextTime = sr.executingStart;
3346 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
3347 Slog.w(TAG, "Timeout executing service: " + timeout);
3348 StringWriter sw = new StringWriter();
3349 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
3350 pw.println(timeout);
3351 timeout.dump(pw, " ");
3353 mLastAnrDump = sw.toString();
3354 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
3355 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
3356 anrMessage = "executing service " + timeout.shortName;
3358 Message msg = mAm.mHandler.obtainMessage(
3359 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3361 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
3362 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
3366 if (anrMessage != null) {
3367 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
3371 void serviceForegroundTimeout(ServiceRecord r) {
3373 synchronized (mAm) {
3374 if (!r.fgRequired || r.destroying) {
3378 if (DEBUG_BACKGROUND_CHECK) {
3379 Slog.i(TAG, "Service foreground-required timeout for " + r);
3382 r.fgWaiting = false;
3383 stopServiceLocked(r);
3387 mAm.mAppErrors.appNotResponding(app, null, null, false,
3388 "Context.startForegroundService() did not then call Service.startForeground()");
3392 void serviceForegroundCrash(ProcessRecord app) {
3393 mAm.crashApplication(app.uid, app.pid, app.info.packageName, app.userId,
3394 "Context.startForegroundService() did not then call Service.startForeground()");
3397 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
3398 if (proc.executingServices.size() == 0 || proc.thread == null) {
3401 Message msg = mAm.mHandler.obtainMessage(
3402 ActivityManagerService.SERVICE_TIMEOUT_MSG);
3404 mAm.mHandler.sendMessageDelayed(msg,
3405 proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
3408 void scheduleServiceForegroundTransitionTimeoutLocked(ServiceRecord r) {
3409 if (r.app.executingServices.size() == 0 || r.app.thread == null) {
3412 Message msg = mAm.mHandler.obtainMessage(
3413 ActivityManagerService.SERVICE_FOREGROUND_TIMEOUT_MSG);
3416 mAm.mHandler.sendMessageDelayed(msg, SERVICE_START_FOREGROUND_TIMEOUT);
3419 final class ServiceDumper {
3420 private final FileDescriptor fd;
3421 private final PrintWriter pw;
3422 private final String[] args;
3423 private final boolean dumpAll;
3424 private final String dumpPackage;
3425 private final ItemMatcher matcher;
3426 private final ArrayList<ServiceRecord> services = new ArrayList<>();
3428 private final long nowReal = SystemClock.elapsedRealtime();
3430 private boolean needSep = false;
3431 private boolean printedAnything = false;
3432 private boolean printed = false;
3435 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
3436 * must be called with the lock held).
3438 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
3439 int opti, boolean dumpAll, String dumpPackage) {
3443 this.dumpAll = dumpAll;
3444 this.dumpPackage = dumpPackage;
3445 matcher = new ItemMatcher();
3446 matcher.build(args, opti);
3448 final int[] users = mAm.mUserController.getUsers();
3449 for (int user : users) {
3450 ServiceMap smap = getServiceMapLocked(user);
3451 if (smap.mServicesByName.size() > 0) {
3452 for (int si=0; si<smap.mServicesByName.size(); si++) {
3453 ServiceRecord r = smap.mServicesByName.valueAt(si);
3454 if (!matcher.match(r, r.name)) {
3457 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3466 private void dumpHeaderLocked() {
3467 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
3468 if (mLastAnrDump != null) {
3469 pw.println(" Last ANR service:");
3470 pw.print(mLastAnrDump);
3479 int[] users = mAm.mUserController.getUsers();
3480 for (int user : users) {
3481 // Find the first service for this user.
3483 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3487 if (serviceIdx < services.size()) {
3489 while (serviceIdx < services.size()) {
3490 ServiceRecord r = services.get(serviceIdx);
3492 if (r.userId != user) {
3495 dumpServiceLocalLocked(r);
3500 dumpUserRemainsLocked(user);
3502 } catch (Exception e) {
3503 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3506 dumpRemainsLocked();
3509 void dumpWithClient() {
3515 int[] users = mAm.mUserController.getUsers();
3516 for (int user : users) {
3517 // Find the first service for this user.
3519 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
3523 if (serviceIdx < services.size()) {
3525 while (serviceIdx < services.size()) {
3526 ServiceRecord r = services.get(serviceIdx);
3528 if (r.userId != user) {
3532 dumpServiceLocalLocked(r);
3534 dumpServiceClient(r);
3540 dumpUserRemainsLocked(user);
3543 } catch (Exception e) {
3544 Slog.w(TAG, "Exception in dumpServicesLocked", e);
3548 dumpRemainsLocked();
3552 private void dumpUserHeaderLocked(int user) {
3554 if (printedAnything) {
3557 pw.println(" User " + user + " active services:");
3560 printedAnything = true;
3566 private void dumpServiceLocalLocked(ServiceRecord r) {
3567 dumpUserHeaderLocked(r.userId);
3576 pw.print(" created=");
3577 TimeUtils.formatDuration(r.createTime, nowReal, pw);
3578 pw.print(" started=");
3579 pw.print(r.startRequested);
3580 pw.print(" connections=");
3581 pw.println(r.connections.size());
3582 if (r.connections.size() > 0) {
3583 pw.println(" Connections:");
3584 for (int conni=0; conni<r.connections.size(); conni++) {
3585 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
3586 for (int i = 0; i < clist.size(); i++) {
3587 ConnectionRecord conn = clist.get(i);
3589 pw.print(conn.binding.intent.intent.getIntent()
3590 .toShortString(false, false, false, false));
3592 ProcessRecord proc = conn.binding.client;
3593 pw.println(proc != null ? proc.toShortString() : "null");
3600 private void dumpServiceClient(ServiceRecord r) {
3601 final ProcessRecord proc = r.app;
3605 final IApplicationThread thread = proc.thread;
3606 if (thread == null) {
3609 pw.println(" Client:");
3612 TransferPipe tp = new TransferPipe();
3614 thread.dumpService(tp.getWriteFd(), r, args);
3615 tp.setBufferPrefix(" ");
3616 // Short timeout, since blocking here can
3617 // deadlock with the application.
3622 } catch (IOException e) {
3623 pw.println(" Failure while dumping the service: " + e);
3624 } catch (RemoteException e) {
3625 pw.println(" Got a RemoteException while dumping the service");
3630 private void dumpUserRemainsLocked(int user) {
3631 ServiceMap smap = getServiceMapLocked(user);
3633 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3634 ServiceRecord r = smap.mDelayedStartList.get(si);
3635 if (!matcher.match(r, r.name)) {
3638 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3642 if (printedAnything) {
3645 pw.println(" User " + user + " delayed start services:");
3648 printedAnything = true;
3649 pw.print(" * Delayed start "); pw.println(r);
3652 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3653 ServiceRecord r = smap.mStartingBackground.get(si);
3654 if (!matcher.match(r, r.name)) {
3657 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3661 if (printedAnything) {
3664 pw.println(" User " + user + " starting in background:");
3667 printedAnything = true;
3668 pw.print(" * Starting bg "); pw.println(r);
3672 private void dumpRemainsLocked() {
3673 if (mPendingServices.size() > 0) {
3675 for (int i=0; i<mPendingServices.size(); i++) {
3676 ServiceRecord r = mPendingServices.get(i);
3677 if (!matcher.match(r, r.name)) {
3680 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3683 printedAnything = true;
3685 if (needSep) pw.println();
3687 pw.println(" Pending services:");
3690 pw.print(" * Pending "); pw.println(r);
3696 if (mRestartingServices.size() > 0) {
3698 for (int i=0; i<mRestartingServices.size(); i++) {
3699 ServiceRecord r = mRestartingServices.get(i);
3700 if (!matcher.match(r, r.name)) {
3703 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3706 printedAnything = true;
3708 if (needSep) pw.println();
3710 pw.println(" Restarting services:");
3713 pw.print(" * Restarting "); pw.println(r);
3719 if (mDestroyingServices.size() > 0) {
3721 for (int i=0; i< mDestroyingServices.size(); i++) {
3722 ServiceRecord r = mDestroyingServices.get(i);
3723 if (!matcher.match(r, r.name)) {
3726 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3729 printedAnything = true;
3731 if (needSep) pw.println();
3733 pw.println(" Destroying services:");
3736 pw.print(" * Destroy "); pw.println(r);
3744 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3745 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3746 for (int i=0; i<r.size(); i++) {
3747 ConnectionRecord cr = r.get(i);
3748 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3751 if (dumpPackage != null && (cr.binding.client == null
3752 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3755 printedAnything = true;
3757 if (needSep) pw.println();
3759 pw.println(" Connection bindings to services:");
3762 pw.print(" * "); pw.println(cr);
3769 final long nowElapsed = SystemClock.elapsedRealtime();
3770 final int[] users = mAm.mUserController.getUsers();
3771 for (int user : users) {
3772 boolean printedUser = false;
3773 ServiceMap smap = mServiceMap.get(user);
3777 for (int i = smap.mActiveForegroundApps.size() - 1; i >= 0; i--) {
3778 ActiveForegroundApp aa = smap.mActiveForegroundApps.valueAt(i);
3779 if (dumpPackage != null && !dumpPackage.equals(aa.mPackageName)) {
3784 printedAnything = true;
3785 if (needSep) pw.println();
3787 pw.print("Active foreground apps - user ");
3794 pw.println(aa.mPackageName);
3795 if (aa.mLabel != null) {
3796 pw.print(" mLabel=");
3797 pw.println(aa.mLabel);
3799 pw.print(" mNumActive=");
3800 pw.print(aa.mNumActive);
3801 pw.print(" mAppOnTop=");
3802 pw.print(aa.mAppOnTop);
3803 pw.print(" mShownWhileTop=");
3804 pw.print(aa.mShownWhileTop);
3805 pw.print(" mShownWhileScreenOn=");
3806 pw.println(aa.mShownWhileScreenOn);
3807 pw.print(" mStartTime=");
3808 TimeUtils.formatDuration(aa.mStartTime - nowElapsed, pw);
3809 pw.print(" mStartVisibleTime=");
3810 TimeUtils.formatDuration(aa.mStartVisibleTime - nowElapsed, pw);
3812 if (aa.mEndTime != 0) {
3813 pw.print(" mEndTime=");
3814 TimeUtils.formatDuration(aa.mEndTime - nowElapsed, pw);
3818 if (smap.hasMessagesOrCallbacks()) {
3822 printedAnything = true;
3824 pw.print(" Handler - user ");
3827 smap.dumpMine(new PrintWriterPrinter(pw), " ");
3832 if (!printedAnything) {
3833 pw.println(" (nothing)");
3838 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
3839 int opti, boolean dumpAll, String dumpPackage) {
3840 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
3844 * There are three ways to call this:
3845 * - no service specified: dump all the services
3846 * - a flattened component name that matched an existing service was specified as the
3847 * first arg: dump that one service
3848 * - the first arg isn't the flattened component name of an existing service:
3849 * dump all services whose component contains the first arg as a substring
3851 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3852 int opti, boolean dumpAll) {
3853 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3855 synchronized (mAm) {
3856 int[] users = mAm.mUserController.getUsers();
3857 if ("all".equals(name)) {
3858 for (int user : users) {
3859 ServiceMap smap = mServiceMap.get(user);
3863 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3864 for (int i=0; i<alls.size(); i++) {
3865 ServiceRecord r1 = alls.valueAt(i);
3870 ComponentName componentName = name != null
3871 ? ComponentName.unflattenFromString(name) : null;
3873 if (componentName == null) {
3874 // Not a '/' separated full component name; maybe an object ID?
3876 objectId = Integer.parseInt(name, 16);
3878 componentName = null;
3879 } catch (RuntimeException e) {
3883 for (int user : users) {
3884 ServiceMap smap = mServiceMap.get(user);
3888 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3889 for (int i=0; i<alls.size(); i++) {
3890 ServiceRecord r1 = alls.valueAt(i);
3891 if (componentName != null) {
3892 if (r1.name.equals(componentName)) {
3895 } else if (name != null) {
3896 if (r1.name.flattenToString().contains(name)) {
3899 } else if (System.identityHashCode(r1) == objectId) {
3907 if (services.size() <= 0) {
3911 boolean needSep = false;
3912 for (int i=0; i<services.size(); i++) {
3917 dumpService("", fd, pw, services.get(i), args, dumpAll);
3923 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3924 * there is a thread associated with the service.
3926 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3927 final ServiceRecord r, String[] args, boolean dumpAll) {
3928 String innerPrefix = prefix + " ";
3929 synchronized (mAm) {
3930 pw.print(prefix); pw.print("SERVICE ");
3931 pw.print(r.shortName); pw.print(" ");
3932 pw.print(Integer.toHexString(System.identityHashCode(r)));
3934 if (r.app != null) pw.println(r.app.pid);
3935 else pw.println("(not running)");
3937 r.dump(pw, innerPrefix);
3940 if (r.app != null && r.app.thread != null) {
3941 pw.print(prefix); pw.println(" Client:");
3944 TransferPipe tp = new TransferPipe();
3946 r.app.thread.dumpService(tp.getWriteFd(), r, args);
3947 tp.setBufferPrefix(prefix + " ");
3952 } catch (IOException e) {
3953 pw.println(prefix + " Failure while dumping the service: " + e);
3954 } catch (RemoteException e) {
3955 pw.println(prefix + " Got a RemoteException while dumping the service");