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 com.android.server.am.ActivityManagerDebugConfig.*;
21 import java.io.FileDescriptor;
22 import java.io.IOException;
23 import java.io.PrintWriter;
24 import java.io.StringWriter;
25 import java.util.ArrayList;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.List;
31 import android.app.ActivityThread;
32 import android.app.AppOpsManager;
33 import android.content.IIntentSender;
34 import android.content.IntentSender;
35 import android.os.Build;
36 import android.os.Bundle;
37 import android.os.DeadObjectException;
38 import android.os.Handler;
39 import android.os.Looper;
40 import android.os.RemoteCallback;
41 import android.os.SystemProperties;
42 import android.os.TransactionTooLargeException;
43 import android.util.ArrayMap;
44 import android.util.ArraySet;
46 import com.android.internal.app.procstats.ProcessStats;
47 import com.android.internal.app.procstats.ServiceState;
48 import com.android.internal.os.BatteryStatsImpl;
49 import com.android.internal.os.TransferPipe;
50 import com.android.internal.util.FastPrintWriter;
51 import com.android.server.am.ActivityManagerService.ItemMatcher;
52 import com.android.server.am.ActivityManagerService.NeededUriGrants;
54 import android.app.ActivityManager;
55 import android.app.AppGlobals;
56 import android.app.IApplicationThread;
57 import android.app.IServiceConnection;
58 import android.app.Notification;
59 import android.app.PendingIntent;
60 import android.app.Service;
61 import android.content.ComponentName;
62 import android.content.Context;
63 import android.content.Intent;
64 import android.content.pm.ApplicationInfo;
65 import android.content.pm.PackageManager;
66 import android.content.pm.ResolveInfo;
67 import android.content.pm.ServiceInfo;
68 import android.os.Binder;
69 import android.os.IBinder;
70 import android.os.Message;
71 import android.os.Process;
72 import android.os.RemoteException;
73 import android.os.SystemClock;
74 import android.os.UserHandle;
75 import android.util.EventLog;
76 import android.util.Slog;
77 import android.util.SparseArray;
78 import android.util.TimeUtils;
80 public final class ActiveServices {
81 private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
82 private static final String TAG_MU = TAG + POSTFIX_MU;
83 private static final String TAG_SERVICE = TAG + POSTFIX_SERVICE;
84 private static final String TAG_SERVICE_EXECUTING = TAG + POSTFIX_SERVICE_EXECUTING;
86 private static final boolean DEBUG_DELAYED_SERVICE = DEBUG_SERVICE;
87 private static final boolean DEBUG_DELAYED_STARTS = DEBUG_DELAYED_SERVICE;
89 private static final boolean LOG_SERVICE_START_STOP = false;
91 // How long we wait for a service to finish executing.
92 static final int SERVICE_TIMEOUT = 20*1000;
94 // How long we wait for a service to finish executing.
95 static final int SERVICE_BACKGROUND_TIMEOUT = SERVICE_TIMEOUT * 10;
97 // How long a service needs to be running until restarting its process
98 // is no longer considered to be a relaunch of the service.
99 static final int SERVICE_RESTART_DURATION = 1*1000;
101 // How long a service needs to be running until it will start back at
102 // SERVICE_RESTART_DURATION after being killed.
103 static final int SERVICE_RESET_RUN_DURATION = 60*1000;
105 // Multiplying factor to increase restart duration time by, for each time
106 // a service is killed before it has run for SERVICE_RESET_RUN_DURATION.
107 static final int SERVICE_RESTART_DURATION_FACTOR = 4;
109 // The minimum amount of time between restarting services that we allow.
110 // That is, when multiple services are restarting, we won't allow each
111 // to restart less than this amount of time from the last one.
112 static final int SERVICE_MIN_RESTART_TIME_BETWEEN = 10*1000;
114 // Maximum amount of time for there to be no activity on a service before
115 // we consider it non-essential and allow its process to go on the
116 // LRU background list.
117 static final int MAX_SERVICE_INACTIVITY = 30*60*1000;
119 // How long we wait for a background started service to stop itself before
120 // allowing the next pending start to run.
121 static final int BG_START_TIMEOUT = 15*1000;
123 final ActivityManagerService mAm;
125 // Maximum number of services that we allow to start in the background
127 final int mMaxStartingBackground;
129 final SparseArray<ServiceMap> mServiceMap = new SparseArray<>();
132 * All currently bound service connections. Keys are the IBinder of
133 * the client's IServiceConnection.
135 final ArrayMap<IBinder, ArrayList<ConnectionRecord>> mServiceConnections = new ArrayMap<>();
138 * List of services that we have been asked to start,
139 * but haven't yet been able to. It is used to hold start requests
140 * while waiting for their corresponding application thread to get
143 final ArrayList<ServiceRecord> mPendingServices = new ArrayList<>();
146 * List of services that are scheduled to restart following a crash.
148 final ArrayList<ServiceRecord> mRestartingServices = new ArrayList<>();
151 * List of services that are in the process of being destroyed.
153 final ArrayList<ServiceRecord> mDestroyingServices = new ArrayList<>();
155 /** Temporary list for holding the results of calls to {@link #collectPackageServicesLocked} */
156 private ArrayList<ServiceRecord> mTmpCollectionResults = null;
158 /** Amount of time to allow a last ANR message to exist before freeing the memory. */
159 static final int LAST_ANR_LIFETIME_DURATION_MSECS = 2 * 60 * 60 * 1000; // Two hours
163 final Runnable mLastAnrDumpClearer = new Runnable() {
164 @Override public void run() {
172 * Information about services for a single user.
174 class ServiceMap extends Handler {
176 final ArrayMap<ComponentName, ServiceRecord> mServicesByName = new ArrayMap<>();
177 final ArrayMap<Intent.FilterComparison, ServiceRecord> mServicesByIntent = new ArrayMap<>();
179 final ArrayList<ServiceRecord> mDelayedStartList = new ArrayList<>();
180 /* XXX eventually I'd like to have this based on processes instead of services.
181 * That is, if we try to start two services in a row both running in the same
182 * process, this should be one entry in mStartingBackground for that one process
183 * that remains until all services in it are done.
184 final ArrayMap<ProcessRecord, DelayingProcess> mStartingBackgroundMap
185 = new ArrayMap<ProcessRecord, DelayingProcess>();
186 final ArrayList<DelayingProcess> mStartingProcessList
187 = new ArrayList<DelayingProcess>();
190 final ArrayList<ServiceRecord> mStartingBackground = new ArrayList<>();
192 static final int MSG_BG_START_TIMEOUT = 1;
194 ServiceMap(Looper looper, int userId) {
200 public void handleMessage(Message msg) {
202 case MSG_BG_START_TIMEOUT: {
204 rescheduleDelayedStarts();
210 void ensureNotStartingBackground(ServiceRecord r) {
211 if (mStartingBackground.remove(r)) {
212 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
213 "No longer background starting: " + r);
214 rescheduleDelayedStarts();
216 if (mDelayedStartList.remove(r)) {
217 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "No longer delaying start: " + r);
221 void rescheduleDelayedStarts() {
222 removeMessages(MSG_BG_START_TIMEOUT);
223 final long now = SystemClock.uptimeMillis();
224 for (int i=0, N=mStartingBackground.size(); i<N; i++) {
225 ServiceRecord r = mStartingBackground.get(i);
226 if (r.startingBgTimeout <= now) {
227 Slog.i(TAG, "Waited long enough for: " + r);
228 mStartingBackground.remove(i);
233 while (mDelayedStartList.size() > 0
234 && mStartingBackground.size() < mMaxStartingBackground) {
235 ServiceRecord r = mDelayedStartList.remove(0);
236 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
237 "REM FR DELAY LIST (exec next): " + r);
238 if (r.pendingStarts.size() <= 0) {
239 Slog.w(TAG, "**** NO PENDING STARTS! " + r + " startReq=" + r.startRequested
240 + " delayedStop=" + r.delayedStop);
242 if (DEBUG_DELAYED_SERVICE) {
243 if (mDelayedStartList.size() > 0) {
244 Slog.v(TAG_SERVICE, "Remaining delayed list:");
245 for (int i=0; i<mDelayedStartList.size(); i++) {
246 Slog.v(TAG_SERVICE, " #" + i + ": " + mDelayedStartList.get(i));
252 startServiceInnerLocked(this, r.pendingStarts.get(0).intent, r, false, true);
253 } catch (TransactionTooLargeException e) {
254 // Ignore, nobody upstack cares.
257 if (mStartingBackground.size() > 0) {
258 ServiceRecord next = mStartingBackground.get(0);
259 long when = next.startingBgTimeout > now ? next.startingBgTimeout : now;
260 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Top bg start is " + next
261 + ", can delay others up to " + when);
262 Message msg = obtainMessage(MSG_BG_START_TIMEOUT);
263 sendMessageAtTime(msg, when);
265 if (mStartingBackground.size() < mMaxStartingBackground) {
266 mAm.backgroundServicesFinishedLocked(mUserId);
271 public ActiveServices(ActivityManagerService service) {
275 maxBg = Integer.parseInt(SystemProperties.get("ro.config.max_starting_bg", "0"));
276 } catch(RuntimeException e) {
278 mMaxStartingBackground = maxBg > 0
279 ? maxBg : ActivityManager.isLowRamDeviceStatic() ? 1 : 8;
282 ServiceRecord getServiceByName(ComponentName name, int callingUser) {
283 // TODO: Deal with global services
285 Slog.v(TAG_MU, "getServiceByName(" + name + "), callingUser = " + callingUser);
286 return getServiceMap(callingUser).mServicesByName.get(name);
289 boolean hasBackgroundServices(int callingUser) {
290 ServiceMap smap = mServiceMap.get(callingUser);
291 return smap != null ? smap.mStartingBackground.size() >= mMaxStartingBackground : false;
294 private ServiceMap getServiceMap(int callingUser) {
295 ServiceMap smap = mServiceMap.get(callingUser);
297 smap = new ServiceMap(mAm.mHandler.getLooper(), callingUser);
298 mServiceMap.put(callingUser, smap);
303 ArrayMap<ComponentName, ServiceRecord> getServices(int callingUser) {
304 return getServiceMap(callingUser).mServicesByName;
307 ComponentName startServiceLocked(IApplicationThread caller, Intent service, String resolvedType,
308 int callingPid, int callingUid, String callingPackage, final int userId)
309 throws TransactionTooLargeException {
310 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "startService: " + service
311 + " type=" + resolvedType + " args=" + service.getExtras());
313 final boolean callerFg;
314 if (caller != null) {
315 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
316 if (callerApp == null) {
317 throw new SecurityException(
318 "Unable to find app for caller " + caller
319 + " (pid=" + Binder.getCallingPid()
320 + ") when starting service " + service);
322 callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
328 ServiceLookupResult res =
329 retrieveServiceLocked(service, resolvedType, callingPackage,
330 callingPid, callingUid, userId, true, callerFg, false);
334 if (res.record == null) {
335 return new ComponentName("!", res.permission != null
336 ? res.permission : "private to package");
339 ServiceRecord r = res.record;
341 if (!mAm.mUserController.exists(r.userId)) {
342 Slog.w(TAG, "Trying to start service with non-existent user! " + r.userId);
346 if (!r.startRequested) {
347 final long token = Binder.clearCallingIdentity();
349 // Before going further -- if this app is not allowed to run in the
350 // background, then at this point we aren't going to let it period.
351 final int allowed = mAm.checkAllowBackgroundLocked(
352 r.appInfo.uid, r.packageName, callingPid, true);
353 if (allowed != ActivityManager.APP_START_MODE_NORMAL) {
354 Slog.w(TAG, "Background start not allowed: service "
355 + service + " to " + r.name.flattenToShortString()
356 + " from pid=" + callingPid + " uid=" + callingUid
357 + " pkg=" + callingPackage);
361 Binder.restoreCallingIdentity(token);
365 NeededUriGrants neededGrants = mAm.checkGrantUriPermissionFromIntentLocked(
366 callingUid, r.packageName, service, service.getFlags(), null, r.userId);
368 // If permissions need a review before any of the app components can run,
369 // we do not start the service and launch a review activity if the calling app
370 // is in the foreground passing it a pending intent to start the service when
371 // review is completed.
372 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
373 if (!requestStartTargetPermissionsReviewIfNeededLocked(r, callingPackage,
374 callingUid, service, callerFg, userId)) {
379 if (unscheduleServiceRestartLocked(r, callingUid, false)) {
380 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "START SERVICE WHILE RESTART PENDING: " + r);
382 r.lastActivity = SystemClock.uptimeMillis();
383 r.startRequested = true;
384 r.delayedStop = false;
385 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
386 service, neededGrants));
388 final ServiceMap smap = getServiceMap(r.userId);
389 boolean addToStarting = false;
390 if (!callerFg && r.app == null
391 && mAm.mUserController.hasStartedUserState(r.userId)) {
392 ProcessRecord proc = mAm.getProcessRecordLocked(r.processName, r.appInfo.uid, false);
393 if (proc == null || proc.curProcState > ActivityManager.PROCESS_STATE_RECEIVER) {
394 // If this is not coming from a foreground caller, then we may want
395 // to delay the start if there are already other background services
396 // that are starting. This is to avoid process start spam when lots
397 // of applications are all handling things like connectivity broadcasts.
398 // We only do this for cached processes, because otherwise an application
399 // can have assumptions about calling startService() for a service to run
400 // in its own process, and for that process to not be killed before the
401 // service is started. This is especially the case for receivers, which
402 // may start a service in onReceive() to do some additional work and have
403 // initialized some global state as part of that.
404 if (DEBUG_DELAYED_SERVICE) Slog.v(TAG_SERVICE, "Potential start delay of "
405 + r + " in " + proc);
407 // This service is already scheduled for a delayed start; just leave
409 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Continuing to delay: " + r);
412 if (smap.mStartingBackground.size() >= mMaxStartingBackground) {
413 // Something else is starting, delay!
414 Slog.i(TAG_SERVICE, "Delaying start of: " + r);
415 smap.mDelayedStartList.add(r);
419 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Not delaying: " + r);
420 addToStarting = true;
421 } else if (proc.curProcState >= ActivityManager.PROCESS_STATE_SERVICE) {
422 // We slightly loosen when we will enqueue this new service as a background
423 // starting service we are waiting for, to also include processes that are
424 // currently running other services or receivers.
425 addToStarting = true;
426 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
427 "Not delaying, but counting as bg: " + r);
428 } else if (DEBUG_DELAYED_STARTS) {
429 StringBuilder sb = new StringBuilder(128);
430 sb.append("Not potential delay (state=").append(proc.curProcState)
431 .append(' ').append(proc.adjType);
432 String reason = proc.makeAdjReason();
433 if (reason != null) {
438 sb.append(r.toString());
439 Slog.v(TAG_SERVICE, sb.toString());
441 } else if (DEBUG_DELAYED_STARTS) {
443 Slog.v(TAG_SERVICE, "Not potential delay (callerFg=" + callerFg + " uid="
444 + callingUid + " pid=" + callingPid + "): " + r);
445 } else if (r.app != null) {
446 Slog.v(TAG_SERVICE, "Not potential delay (cur app=" + r.app + "): " + r);
449 "Not potential delay (user " + r.userId + " not started): " + r);
453 return startServiceInnerLocked(smap, service, r, callerFg, addToStarting);
456 private boolean requestStartTargetPermissionsReviewIfNeededLocked(ServiceRecord r,
457 String callingPackage, int callingUid, Intent service, boolean callerFg,
459 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
460 r.packageName, r.userId)) {
462 // Show a permission review UI only for starting from a foreground app
464 Slog.w(TAG, "u" + r.userId + " Starting a service in package"
465 + r.packageName + " requires a permissions review");
469 IIntentSender target = mAm.getIntentSenderLocked(
470 ActivityManager.INTENT_SENDER_SERVICE, callingPackage,
471 callingUid, userId, null, null, 0, new Intent[]{service},
472 new String[]{service.resolveType(mAm.mContext.getContentResolver())},
473 PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_ONE_SHOT
474 | PendingIntent.FLAG_IMMUTABLE, null);
476 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
477 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
478 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
479 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, r.packageName);
480 intent.putExtra(Intent.EXTRA_INTENT, new IntentSender(target));
482 if (DEBUG_PERMISSIONS_REVIEW) {
483 Slog.i(TAG, "u" + r.userId + " Launching permission review for package "
487 mAm.mHandler.post(new Runnable() {
490 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
500 ComponentName startServiceInnerLocked(ServiceMap smap, Intent service, ServiceRecord r,
501 boolean callerFg, boolean addToStarting) throws TransactionTooLargeException {
502 ServiceState stracker = r.getTracker();
503 if (stracker != null) {
504 stracker.setStarted(true, mAm.mProcessStats.getMemFactorLocked(), r.lastActivity);
507 synchronized (r.stats.getBatteryStats()) {
508 r.stats.startRunningLocked();
510 String error = bringUpServiceLocked(r, service.getFlags(), callerFg, false, false);
512 return new ComponentName("!!", error);
515 if (r.startRequested && addToStarting) {
516 boolean first = smap.mStartingBackground.size() == 0;
517 smap.mStartingBackground.add(r);
518 r.startingBgTimeout = SystemClock.uptimeMillis() + BG_START_TIMEOUT;
519 if (DEBUG_DELAYED_SERVICE) {
520 RuntimeException here = new RuntimeException("here");
521 here.fillInStackTrace();
522 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r, here);
523 } else if (DEBUG_DELAYED_STARTS) {
524 Slog.v(TAG_SERVICE, "Starting background (first=" + first + "): " + r);
527 smap.rescheduleDelayedStarts();
529 } else if (callerFg) {
530 smap.ensureNotStartingBackground(r);
536 private void stopServiceLocked(ServiceRecord service) {
537 if (service.delayed) {
538 // If service isn't actually running, but is is being held in the
539 // delayed list, then we need to keep it started but note that it
540 // should be stopped once no longer delayed.
541 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
542 service.delayedStop = true;
545 synchronized (service.stats.getBatteryStats()) {
546 service.stats.stopRunningLocked();
548 service.startRequested = false;
549 if (service.tracker != null) {
550 service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
551 SystemClock.uptimeMillis());
553 service.callStart = false;
554 bringDownServiceIfNeededLocked(service, false, false);
557 int stopServiceLocked(IApplicationThread caller, Intent service,
558 String resolvedType, int userId) {
559 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopService: " + service
560 + " type=" + resolvedType);
562 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
563 if (caller != null && callerApp == null) {
564 throw new SecurityException(
565 "Unable to find app for caller " + caller
566 + " (pid=" + Binder.getCallingPid()
567 + ") when stopping service " + service);
570 // If this service is active, make sure it is stopped.
571 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, null,
572 Binder.getCallingPid(), Binder.getCallingUid(), userId, false, false, false);
574 if (r.record != null) {
575 final long origId = Binder.clearCallingIdentity();
577 stopServiceLocked(r.record);
579 Binder.restoreCallingIdentity(origId);
589 void stopInBackgroundLocked(int uid) {
590 // Stop all services associated with this uid due to it going to the background
592 ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
593 ArrayList<ServiceRecord> stopping = null;
594 if (services != null) {
595 for (int i=services.mServicesByName.size()-1; i>=0; i--) {
596 ServiceRecord service = services.mServicesByName.valueAt(i);
597 if (service.appInfo.uid == uid && service.startRequested) {
598 if (mAm.mAppOpsService.noteOperation(AppOpsManager.OP_RUN_IN_BACKGROUND,
599 uid, service.packageName) != AppOpsManager.MODE_ALLOWED) {
600 if (stopping == null) {
601 stopping = new ArrayList<>();
602 stopping.add(service);
607 if (stopping != null) {
608 for (int i=stopping.size()-1; i>=0; i--) {
609 ServiceRecord service = stopping.get(i);
610 service.delayed = false;
611 services.ensureNotStartingBackground(service);
612 stopServiceLocked(service);
618 IBinder peekServiceLocked(Intent service, String resolvedType, String callingPackage) {
619 ServiceLookupResult r = retrieveServiceLocked(service, resolvedType, callingPackage,
620 Binder.getCallingPid(), Binder.getCallingUid(),
621 UserHandle.getCallingUserId(), false, false, false);
625 // r.record is null if findServiceLocked() failed the caller permission check
626 if (r.record == null) {
627 throw new SecurityException(
628 "Permission Denial: Accessing service"
629 + " from pid=" + Binder.getCallingPid()
630 + ", uid=" + Binder.getCallingUid()
631 + " requires " + r.permission);
633 IntentBindRecord ib = r.record.bindings.get(r.record.intent);
642 boolean stopServiceTokenLocked(ComponentName className, IBinder token,
644 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "stopServiceToken: " + className
645 + " " + token + " startId=" + startId);
646 ServiceRecord r = findServiceLocked(className, token, UserHandle.getCallingUserId());
649 // Asked to only stop if done with all work. Note that
650 // to avoid leaks, we will take this as dropping all
651 // start items up to and including this one.
652 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
654 while (r.deliveredStarts.size() > 0) {
655 ServiceRecord.StartItem cur = r.deliveredStarts.remove(0);
656 cur.removeUriPermissionsLocked();
663 if (r.getLastStartId() != startId) {
667 if (r.deliveredStarts.size() > 0) {
668 Slog.w(TAG, "stopServiceToken startId " + startId
669 + " is last, but have " + r.deliveredStarts.size()
670 + " remaining args");
674 synchronized (r.stats.getBatteryStats()) {
675 r.stats.stopRunningLocked();
677 r.startRequested = false;
678 if (r.tracker != null) {
679 r.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
680 SystemClock.uptimeMillis());
683 final long origId = Binder.clearCallingIdentity();
684 bringDownServiceIfNeededLocked(r, false, false);
685 Binder.restoreCallingIdentity(origId);
691 public void setServiceForegroundLocked(ComponentName className, IBinder token,
692 int id, Notification notification, int flags) {
693 final int userId = UserHandle.getCallingUserId();
694 final long origId = Binder.clearCallingIdentity();
696 ServiceRecord r = findServiceLocked(className, token, userId);
699 if (notification == null) {
700 throw new IllegalArgumentException("null notification");
702 if (r.foregroundId != id) {
703 r.cancelNotification();
706 notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
707 r.foregroundNoti = notification;
708 r.isForeground = true;
709 r.postNotification();
711 updateServiceForegroundLocked(r.app, true);
713 getServiceMap(r.userId).ensureNotStartingBackground(r);
714 mAm.notifyPackageUse(r.serviceInfo.packageName,
715 PackageManager.NOTIFY_PACKAGE_USE_FOREGROUND_SERVICE);
717 if (r.isForeground) {
718 r.isForeground = false;
720 mAm.updateLruProcessLocked(r.app, false, null);
721 updateServiceForegroundLocked(r.app, true);
724 if ((flags & Service.STOP_FOREGROUND_REMOVE) != 0) {
725 r.cancelNotification();
727 r.foregroundNoti = null;
728 } else if (r.appInfo.targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
729 r.stripForegroundServiceFlagFromNotification();
730 if ((flags & Service.STOP_FOREGROUND_DETACH) != 0) {
732 r.foregroundNoti = null;
738 Binder.restoreCallingIdentity(origId);
742 private void updateServiceForegroundLocked(ProcessRecord proc, boolean oomAdj) {
743 boolean anyForeground = false;
744 for (int i=proc.services.size()-1; i>=0; i--) {
745 ServiceRecord sr = proc.services.valueAt(i);
746 if (sr.isForeground) {
747 anyForeground = true;
751 mAm.updateProcessForegroundLocked(proc, anyForeground, oomAdj);
754 public void updateServiceConnectionActivitiesLocked(ProcessRecord clientProc) {
755 ArraySet<ProcessRecord> updatedProcesses = null;
756 for (int i=0; i<clientProc.connections.size(); i++) {
757 final ConnectionRecord conn = clientProc.connections.valueAt(i);
758 final ProcessRecord proc = conn.binding.service.app;
759 if (proc == null || proc == clientProc) {
761 } else if (updatedProcesses == null) {
762 updatedProcesses = new ArraySet<>();
763 } else if (updatedProcesses.contains(proc)) {
766 updatedProcesses.add(proc);
767 updateServiceClientActivitiesLocked(proc, null, false);
771 private boolean updateServiceClientActivitiesLocked(ProcessRecord proc,
772 ConnectionRecord modCr, boolean updateLru) {
773 if (modCr != null && modCr.binding.client != null) {
774 if (modCr.binding.client.activities.size() <= 0) {
775 // This connection is from a client without activities, so adding
776 // and removing is not interesting.
781 boolean anyClientActivities = false;
782 for (int i=proc.services.size()-1; i>=0 && !anyClientActivities; i--) {
783 ServiceRecord sr = proc.services.valueAt(i);
784 for (int conni=sr.connections.size()-1; conni>=0 && !anyClientActivities; conni--) {
785 ArrayList<ConnectionRecord> clist = sr.connections.valueAt(conni);
786 for (int cri=clist.size()-1; cri>=0; cri--) {
787 ConnectionRecord cr = clist.get(cri);
788 if (cr.binding.client == null || cr.binding.client == proc) {
789 // Binding to ourself is not interesting.
792 if (cr.binding.client.activities.size() > 0) {
793 anyClientActivities = true;
799 if (anyClientActivities != proc.hasClientActivities) {
800 proc.hasClientActivities = anyClientActivities;
802 mAm.updateLruProcessLocked(proc, anyClientActivities, null);
809 int bindServiceLocked(IApplicationThread caller, IBinder token, Intent service,
810 String resolvedType, final IServiceConnection connection, int flags,
811 String callingPackage, final int userId) throws TransactionTooLargeException {
812 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "bindService: " + service
813 + " type=" + resolvedType + " conn=" + connection.asBinder()
814 + " flags=0x" + Integer.toHexString(flags));
815 final ProcessRecord callerApp = mAm.getRecordForAppLocked(caller);
816 if (callerApp == null) {
817 throw new SecurityException(
818 "Unable to find app for caller " + caller
819 + " (pid=" + Binder.getCallingPid()
820 + ") when binding service " + service);
823 ActivityRecord activity = null;
825 activity = ActivityRecord.isInStackLocked(token);
826 if (activity == null) {
827 Slog.w(TAG, "Binding with unknown activity: " + token);
833 PendingIntent clientIntent = null;
835 if (callerApp.info.uid == Process.SYSTEM_UID) {
836 // Hacky kind of thing -- allow system stuff to tell us
837 // what they are, so we can report this elsewhere for
838 // others to know why certain services are running.
839 service.setDefusable(true);
840 clientIntent = service.getParcelableExtra(Intent.EXTRA_CLIENT_INTENT);
841 if (clientIntent != null) {
842 clientLabel = service.getIntExtra(Intent.EXTRA_CLIENT_LABEL, 0);
843 if (clientLabel != 0) {
844 // There are no useful extras in the intent, trash them.
845 // System code calling with this stuff just needs to know
847 service = service.cloneFilter();
852 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
853 mAm.enforceCallingPermission(android.Manifest.permission.MANAGE_ACTIVITY_STACKS,
854 "BIND_TREAT_LIKE_ACTIVITY");
857 final boolean callerFg = callerApp.setSchedGroup != ProcessList.SCHED_GROUP_BACKGROUND;
858 final boolean isBindExternal = (flags & Context.BIND_EXTERNAL_SERVICE) != 0;
860 ServiceLookupResult res =
861 retrieveServiceLocked(service, resolvedType, callingPackage, Binder.getCallingPid(),
862 Binder.getCallingUid(), userId, true, callerFg, isBindExternal);
866 if (res.record == null) {
869 ServiceRecord s = res.record;
871 boolean permissionsReviewRequired = false;
873 // If permissions need a review before any of the app components can run,
874 // we schedule binding to the service but do not start its process, then
875 // we launch a review activity to which is passed a callback to invoke
876 // when done to start the bound service's process to completing the binding.
877 if (Build.PERMISSIONS_REVIEW_REQUIRED) {
878 if (mAm.getPackageManagerInternalLocked().isPermissionsReviewRequired(
879 s.packageName, s.userId)) {
881 permissionsReviewRequired = true;
883 // Show a permission review UI only for binding from a foreground app
885 Slog.w(TAG, "u" + s.userId + " Binding to a service in package"
886 + s.packageName + " requires a permissions review");
890 final ServiceRecord serviceRecord = s;
891 final Intent serviceIntent = service;
893 RemoteCallback callback = new RemoteCallback(
894 new RemoteCallback.OnResultListener() {
896 public void onResult(Bundle result) {
898 final long identity = Binder.clearCallingIdentity();
900 if (!mPendingServices.contains(serviceRecord)) {
903 // If there is still a pending record, then the service
904 // binding request is still valid, so hook them up. We
905 // proceed only if the caller cleared the review requirement
906 // otherwise we unbind because the user didn't approve.
907 if (!mAm.getPackageManagerInternalLocked()
908 .isPermissionsReviewRequired(
909 serviceRecord.packageName,
910 serviceRecord.userId)) {
912 bringUpServiceLocked(serviceRecord,
913 serviceIntent.getFlags(),
914 callerFg, false, false);
915 } catch (RemoteException e) {
916 /* ignore - local call */
919 unbindServiceLocked(connection);
922 Binder.restoreCallingIdentity(identity);
928 final Intent intent = new Intent(Intent.ACTION_REVIEW_PERMISSIONS);
929 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
930 | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
931 intent.putExtra(Intent.EXTRA_PACKAGE_NAME, s.packageName);
932 intent.putExtra(Intent.EXTRA_REMOTE_CALLBACK, callback);
934 if (DEBUG_PERMISSIONS_REVIEW) {
935 Slog.i(TAG, "u" + s.userId + " Launching permission review for package "
939 mAm.mHandler.post(new Runnable() {
942 mAm.mContext.startActivityAsUser(intent, new UserHandle(userId));
948 final long origId = Binder.clearCallingIdentity();
951 if (unscheduleServiceRestartLocked(s, callerApp.info.uid, false)) {
952 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "BIND SERVICE WHILE RESTART PENDING: "
956 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
957 s.lastActivity = SystemClock.uptimeMillis();
958 if (!s.hasAutoCreateConnections()) {
959 // This is the first binding, let the tracker know.
960 ServiceState stracker = s.getTracker();
961 if (stracker != null) {
962 stracker.setBound(true, mAm.mProcessStats.getMemFactorLocked(),
968 mAm.startAssociationLocked(callerApp.uid, callerApp.processName, callerApp.curProcState,
969 s.appInfo.uid, s.name, s.processName);
971 AppBindRecord b = s.retrieveAppBindingLocked(service, callerApp);
972 ConnectionRecord c = new ConnectionRecord(b, activity,
973 connection, flags, clientLabel, clientIntent);
975 IBinder binder = connection.asBinder();
976 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
978 clist = new ArrayList<ConnectionRecord>();
979 s.connections.put(binder, clist);
982 b.connections.add(c);
983 if (activity != null) {
984 if (activity.connections == null) {
985 activity.connections = new HashSet<ConnectionRecord>();
987 activity.connections.add(c);
989 b.client.connections.add(c);
990 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
991 b.client.hasAboveClient = true;
994 updateServiceClientActivitiesLocked(s.app, c, true);
996 clist = mServiceConnections.get(binder);
998 clist = new ArrayList<ConnectionRecord>();
999 mServiceConnections.put(binder, clist);
1003 if ((flags&Context.BIND_AUTO_CREATE) != 0) {
1004 s.lastActivity = SystemClock.uptimeMillis();
1005 if (bringUpServiceLocked(s, service.getFlags(), callerFg, false,
1006 permissionsReviewRequired) != null) {
1011 if (s.app != null) {
1012 if ((flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1013 s.app.treatLikeActivity = true;
1015 // This could have made the service more important.
1016 mAm.updateLruProcessLocked(s.app, s.app.hasClientActivities
1017 || s.app.treatLikeActivity, b.client);
1018 mAm.updateOomAdjLocked(s.app);
1021 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bind " + s + " with " + b
1022 + ": received=" + b.intent.received
1023 + " apps=" + b.intent.apps.size()
1024 + " doRebind=" + b.intent.doRebind);
1026 if (s.app != null && b.intent.received) {
1027 // Service is already running, so we can immediately
1028 // publish the connection.
1030 c.conn.connected(s.name, b.intent.binder);
1031 } catch (Exception e) {
1032 Slog.w(TAG, "Failure sending service " + s.shortName
1033 + " to connection " + c.conn.asBinder()
1034 + " (in " + c.binding.client.processName + ")", e);
1037 // If this is the first app connected back to this binding,
1038 // and the service had previously asked to be told when
1039 // rebound, then do so.
1040 if (b.intent.apps.size() == 1 && b.intent.doRebind) {
1041 requestServiceBindingLocked(s, b.intent, callerFg, true);
1043 } else if (!b.intent.requested) {
1044 requestServiceBindingLocked(s, b.intent, callerFg, false);
1047 getServiceMap(s.userId).ensureNotStartingBackground(s);
1050 Binder.restoreCallingIdentity(origId);
1056 private void foo() {
1060 void publishServiceLocked(ServiceRecord r, Intent intent, IBinder service) {
1061 final long origId = Binder.clearCallingIdentity();
1063 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "PUBLISHING " + r
1064 + " " + intent + ": " + service);
1066 Intent.FilterComparison filter
1067 = new Intent.FilterComparison(intent);
1068 IntentBindRecord b = r.bindings.get(filter);
1069 if (b != null && !b.received) {
1073 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1074 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
1075 for (int i=0; i<clist.size(); i++) {
1076 ConnectionRecord c = clist.get(i);
1077 if (!filter.equals(c.binding.intent.intent)) {
1078 if (DEBUG_SERVICE) Slog.v(
1079 TAG_SERVICE, "Not publishing to: " + c);
1080 if (DEBUG_SERVICE) Slog.v(
1081 TAG_SERVICE, "Bound intent: " + c.binding.intent.intent);
1082 if (DEBUG_SERVICE) Slog.v(
1083 TAG_SERVICE, "Published intent: " + intent);
1086 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Publishing to: " + c);
1088 c.conn.connected(r.name, service);
1089 } catch (Exception e) {
1090 Slog.w(TAG, "Failure sending service " + r.name +
1091 " to connection " + c.conn.asBinder() +
1092 " (in " + c.binding.client.processName + ")", e);
1098 serviceDoneExecutingLocked(r, mDestroyingServices.contains(r), false);
1101 Binder.restoreCallingIdentity(origId);
1105 boolean unbindServiceLocked(IServiceConnection connection) {
1106 IBinder binder = connection.asBinder();
1107 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindService: conn=" + binder);
1108 ArrayList<ConnectionRecord> clist = mServiceConnections.get(binder);
1109 if (clist == null) {
1110 Slog.w(TAG, "Unbind failed: could not find connection for "
1111 + connection.asBinder());
1115 final long origId = Binder.clearCallingIdentity();
1117 while (clist.size() > 0) {
1118 ConnectionRecord r = clist.get(0);
1119 removeConnectionLocked(r, null, null);
1120 if (clist.size() > 0 && clist.get(0) == r) {
1121 // In case it didn't get removed above, do it now.
1122 Slog.wtf(TAG, "Connection " + r + " not removed for binder " + binder);
1126 if (r.binding.service.app != null) {
1127 // This could have made the service less important.
1128 if ((r.flags&Context.BIND_TREAT_LIKE_ACTIVITY) != 0) {
1129 r.binding.service.app.treatLikeActivity = true;
1130 mAm.updateLruProcessLocked(r.binding.service.app,
1131 r.binding.service.app.hasClientActivities
1132 || r.binding.service.app.treatLikeActivity, null);
1134 mAm.updateOomAdjLocked(r.binding.service.app);
1138 Binder.restoreCallingIdentity(origId);
1144 void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
1145 final long origId = Binder.clearCallingIdentity();
1148 Intent.FilterComparison filter
1149 = new Intent.FilterComparison(intent);
1150 IntentBindRecord b = r.bindings.get(filter);
1151 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
1152 + " at " + b + ": apps="
1153 + (b != null ? b.apps.size() : 0));
1155 boolean inDestroying = mDestroyingServices.contains(r);
1157 if (b.apps.size() > 0 && !inDestroying) {
1158 // Applications have already bound since the last
1159 // unbind, so just rebind right here.
1160 boolean inFg = false;
1161 for (int i=b.apps.size()-1; i>=0; i--) {
1162 ProcessRecord client = b.apps.valueAt(i).client;
1163 if (client != null && client.setSchedGroup
1164 != ProcessList.SCHED_GROUP_BACKGROUND) {
1170 requestServiceBindingLocked(r, b, inFg, true);
1171 } catch (TransactionTooLargeException e) {
1172 // Don't pass this back to ActivityThread, it's unrelated.
1175 // Note to tell the service the next time there is
1181 serviceDoneExecutingLocked(r, inDestroying, false);
1184 Binder.restoreCallingIdentity(origId);
1188 private final ServiceRecord findServiceLocked(ComponentName name,
1189 IBinder token, int userId) {
1190 ServiceRecord r = getServiceByName(name, userId);
1191 return r == token ? r : null;
1194 private final class ServiceLookupResult {
1195 final ServiceRecord record;
1196 final String permission;
1198 ServiceLookupResult(ServiceRecord _record, String _permission) {
1200 permission = _permission;
1204 private class ServiceRestarter implements Runnable {
1205 private ServiceRecord mService;
1207 void setService(ServiceRecord service) {
1213 performServiceRestartLocked(mService);
1218 private ServiceLookupResult retrieveServiceLocked(Intent service,
1219 String resolvedType, String callingPackage, int callingPid, int callingUid, int userId,
1220 boolean createIfNeeded, boolean callingFromFg, boolean isBindExternal) {
1221 ServiceRecord r = null;
1222 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "retrieveServiceLocked: " + service
1223 + " type=" + resolvedType + " callingUid=" + callingUid);
1225 userId = mAm.mUserController.handleIncomingUser(callingPid, callingUid, userId, false,
1226 ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE, "service", null);
1228 ServiceMap smap = getServiceMap(userId);
1229 final ComponentName comp = service.getComponent();
1231 r = smap.mServicesByName.get(comp);
1233 if (r == null && !isBindExternal) {
1234 Intent.FilterComparison filter = new Intent.FilterComparison(service);
1235 r = smap.mServicesByIntent.get(filter);
1237 if (r != null && (r.serviceInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0
1238 && !callingPackage.equals(r.packageName)) {
1239 // If an external service is running within its own package, other packages
1240 // should not bind to that instance.
1245 // TODO: come back and remove this assumption to triage all services
1246 ResolveInfo rInfo = AppGlobals.getPackageManager().resolveService(service,
1247 resolvedType, ActivityManagerService.STOCK_PM_FLAGS
1248 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
1251 rInfo != null ? rInfo.serviceInfo : null;
1252 if (sInfo == null) {
1253 Slog.w(TAG_SERVICE, "Unable to start service " + service + " U=" + userId +
1257 ComponentName name = new ComponentName(
1258 sInfo.applicationInfo.packageName, sInfo.name);
1259 if ((sInfo.flags & ServiceInfo.FLAG_EXTERNAL_SERVICE) != 0) {
1260 if (isBindExternal) {
1261 if (!sInfo.exported) {
1262 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1263 " is not exported");
1265 if ((sInfo.flags & ServiceInfo.FLAG_ISOLATED_PROCESS) == 0) {
1266 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1267 " is not an isolatedProcess");
1269 // Run the service under the calling package's application.
1270 ApplicationInfo aInfo = AppGlobals.getPackageManager().getApplicationInfo(
1271 callingPackage, ActivityManagerService.STOCK_PM_FLAGS, userId);
1272 if (aInfo == null) {
1273 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " +
1274 "could not resolve client package " + callingPackage);
1276 sInfo = new ServiceInfo(sInfo);
1277 sInfo.applicationInfo = new ApplicationInfo(sInfo.applicationInfo);
1278 sInfo.applicationInfo.packageName = aInfo.packageName;
1279 sInfo.applicationInfo.uid = aInfo.uid;
1280 name = new ComponentName(aInfo.packageName, name.getClassName());
1281 service.setComponent(name);
1283 throw new SecurityException("BIND_EXTERNAL_SERVICE required for " +
1286 } else if (isBindExternal) {
1287 throw new SecurityException("BIND_EXTERNAL_SERVICE failed, " + name +
1288 " is not an externalService");
1291 if (mAm.isSingleton(sInfo.processName, sInfo.applicationInfo,
1292 sInfo.name, sInfo.flags)
1293 && mAm.isValidSingletonCall(callingUid, sInfo.applicationInfo.uid)) {
1295 smap = getServiceMap(0);
1297 sInfo = new ServiceInfo(sInfo);
1298 sInfo.applicationInfo = mAm.getAppInfoForUser(sInfo.applicationInfo, userId);
1300 r = smap.mServicesByName.get(name);
1301 if (r == null && createIfNeeded) {
1302 Intent.FilterComparison filter
1303 = new Intent.FilterComparison(service.cloneFilter());
1304 ServiceRestarter res = new ServiceRestarter();
1305 BatteryStatsImpl.Uid.Pkg.Serv ss = null;
1306 BatteryStatsImpl stats = mAm.mBatteryStatsService.getActiveStatistics();
1307 synchronized (stats) {
1308 ss = stats.getServiceStatsLocked(
1309 sInfo.applicationInfo.uid, sInfo.packageName,
1312 r = new ServiceRecord(mAm, ss, name, filter, sInfo, callingFromFg, res);
1314 smap.mServicesByName.put(name, r);
1315 smap.mServicesByIntent.put(filter, r);
1317 // Make sure this component isn't in the pending list.
1318 for (int i=mPendingServices.size()-1; i>=0; i--) {
1319 ServiceRecord pr = mPendingServices.get(i);
1320 if (pr.serviceInfo.applicationInfo.uid == sInfo.applicationInfo.uid
1321 && pr.name.equals(name)) {
1322 mPendingServices.remove(i);
1326 } catch (RemoteException ex) {
1327 // pm is in same process, this will never happen.
1331 if (mAm.checkComponentPermission(r.permission,
1332 callingPid, callingUid, r.appInfo.uid, r.exported)
1333 != PackageManager.PERMISSION_GRANTED) {
1335 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1336 + " from pid=" + callingPid
1337 + ", uid=" + callingUid
1338 + " that is not exported from uid " + r.appInfo.uid);
1339 return new ServiceLookupResult(null, "not exported from uid "
1342 Slog.w(TAG, "Permission Denial: Accessing service " + r.name
1343 + " from pid=" + callingPid
1344 + ", uid=" + callingUid
1345 + " requires " + r.permission);
1346 return new ServiceLookupResult(null, r.permission);
1347 } else if (r.permission != null && callingPackage != null) {
1348 final int opCode = AppOpsManager.permissionToOpCode(r.permission);
1349 if (opCode != AppOpsManager.OP_NONE && mAm.mAppOpsService.noteOperation(
1350 opCode, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
1351 Slog.w(TAG, "Appop Denial: Accessing service " + r.name
1352 + " from pid=" + callingPid
1353 + ", uid=" + callingUid
1354 + " requires appop " + AppOpsManager.opToName(opCode));
1359 if (!mAm.mIntentFirewall.checkService(r.name, service, callingUid, callingPid,
1360 resolvedType, r.appInfo)) {
1363 return new ServiceLookupResult(r, null);
1368 private final void bumpServiceExecutingLocked(ServiceRecord r, boolean fg, String why) {
1369 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, ">>> EXECUTING "
1370 + why + " of " + r + " in app " + r.app);
1371 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING, ">>> EXECUTING "
1372 + why + " of " + r.shortName);
1373 long now = SystemClock.uptimeMillis();
1374 if (r.executeNesting == 0) {
1376 ServiceState stracker = r.getTracker();
1377 if (stracker != null) {
1378 stracker.setExecuting(true, mAm.mProcessStats.getMemFactorLocked(), now);
1380 if (r.app != null) {
1381 r.app.executingServices.add(r);
1382 r.app.execServicesFg |= fg;
1383 if (r.app.executingServices.size() == 1) {
1384 scheduleServiceTimeoutLocked(r.app);
1387 } else if (r.app != null && fg && !r.app.execServicesFg) {
1388 r.app.execServicesFg = true;
1389 scheduleServiceTimeoutLocked(r.app);
1393 r.executingStart = now;
1396 private final boolean requestServiceBindingLocked(ServiceRecord r, IntentBindRecord i,
1397 boolean execInFg, boolean rebind) throws TransactionTooLargeException {
1398 if (r.app == null || r.app.thread == null) {
1399 // If service is not currently running, can't yet bind.
1402 if ((!i.requested || rebind) && i.apps.size() > 0) {
1404 bumpServiceExecutingLocked(r, execInFg, "bind");
1405 r.app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1406 r.app.thread.scheduleBindService(r, i.intent.getIntent(), rebind,
1407 r.app.repProcState);
1413 } catch (TransactionTooLargeException e) {
1414 // Keep the executeNesting count accurate.
1415 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r, e);
1416 final boolean inDestroying = mDestroyingServices.contains(r);
1417 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1419 } catch (RemoteException e) {
1420 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while binding " + r);
1421 // Keep the executeNesting count accurate.
1422 final boolean inDestroying = mDestroyingServices.contains(r);
1423 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1430 private final boolean scheduleServiceRestartLocked(ServiceRecord r,
1431 boolean allowCancel) {
1432 boolean canceled = false;
1434 ServiceMap smap = getServiceMap(r.userId);
1435 if (smap.mServicesByName.get(r.name) != r) {
1436 ServiceRecord cur = smap.mServicesByName.get(r.name);
1437 Slog.wtf(TAG, "Attempting to schedule restart of " + r
1438 + " when found in map: " + cur);
1442 final long now = SystemClock.uptimeMillis();
1444 if ((r.serviceInfo.applicationInfo.flags
1445 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
1446 long minDuration = SERVICE_RESTART_DURATION;
1447 long resetTime = SERVICE_RESET_RUN_DURATION;
1449 // Any delivered but not yet finished starts should be put back
1450 // on the pending list.
1451 final int N = r.deliveredStarts.size();
1453 for (int i=N-1; i>=0; i--) {
1454 ServiceRecord.StartItem si = r.deliveredStarts.get(i);
1455 si.removeUriPermissionsLocked();
1456 if (si.intent == null) {
1457 // We'll generate this again if needed.
1458 } else if (!allowCancel || (si.deliveryCount < ServiceRecord.MAX_DELIVERY_COUNT
1459 && si.doneExecutingCount < ServiceRecord.MAX_DONE_EXECUTING_COUNT)) {
1460 r.pendingStarts.add(0, si);
1461 long dur = SystemClock.uptimeMillis() - si.deliveredTime;
1463 if (minDuration < dur) minDuration = dur;
1464 if (resetTime < dur) resetTime = dur;
1466 Slog.w(TAG, "Canceling start item " + si.intent + " in service "
1471 r.deliveredStarts.clear();
1474 r.totalRestartCount++;
1475 if (r.restartDelay == 0) {
1477 r.restartDelay = minDuration;
1479 // If it has been a "reasonably long time" since the service
1480 // was started, then reset our restart duration back to
1481 // the beginning, so we don't infinitely increase the duration
1482 // on a service that just occasionally gets killed (which is
1483 // a normal case, due to process being killed to reclaim memory).
1484 if (now > (r.restartTime+resetTime)) {
1486 r.restartDelay = minDuration;
1488 r.restartDelay *= SERVICE_RESTART_DURATION_FACTOR;
1489 if (r.restartDelay < minDuration) {
1490 r.restartDelay = minDuration;
1495 r.nextRestartTime = now + r.restartDelay;
1497 // Make sure that we don't end up restarting a bunch of services
1498 // all at the same time.
1502 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1503 ServiceRecord r2 = mRestartingServices.get(i);
1504 if (r2 != r && r.nextRestartTime
1505 >= (r2.nextRestartTime-SERVICE_MIN_RESTART_TIME_BETWEEN)
1506 && r.nextRestartTime
1507 < (r2.nextRestartTime+SERVICE_MIN_RESTART_TIME_BETWEEN)) {
1508 r.nextRestartTime = r2.nextRestartTime + SERVICE_MIN_RESTART_TIME_BETWEEN;
1509 r.restartDelay = r.nextRestartTime - now;
1517 // Persistent processes are immediately restarted, so there is no
1518 // reason to hold of on restarting their services.
1519 r.totalRestartCount++;
1522 r.nextRestartTime = now;
1525 if (!mRestartingServices.contains(r)) {
1526 r.createdFromFg = false;
1527 mRestartingServices.add(r);
1528 r.makeRestarting(mAm.mProcessStats.getMemFactorLocked(), now);
1531 r.cancelNotification();
1533 mAm.mHandler.removeCallbacks(r.restarter);
1534 mAm.mHandler.postAtTime(r.restarter, r.nextRestartTime);
1535 r.nextRestartTime = SystemClock.uptimeMillis() + r.restartDelay;
1536 Slog.w(TAG, "Scheduling restart of crashed service "
1537 + r.shortName + " in " + r.restartDelay + "ms");
1538 EventLog.writeEvent(EventLogTags.AM_SCHEDULE_SERVICE_RESTART,
1539 r.userId, r.shortName, r.restartDelay);
1544 final void performServiceRestartLocked(ServiceRecord r) {
1545 if (!mRestartingServices.contains(r)) {
1548 if (!isServiceNeeded(r, false, false)) {
1549 // Paranoia: is this service actually needed? In theory a service that is not
1550 // needed should never remain on the restart list. In practice... well, there
1551 // have been bugs where this happens, and bad things happen because the process
1552 // ends up just being cached, so quickly killed, then restarted again and again.
1553 // Let's not let that happen.
1554 Slog.wtf(TAG, "Restarting service that is not needed: " + r);
1558 bringUpServiceLocked(r, r.intent.getIntent().getFlags(), r.createdFromFg, true, false);
1559 } catch (TransactionTooLargeException e) {
1560 // Ignore, it's been logged and nothing upstack cares.
1564 private final boolean unscheduleServiceRestartLocked(ServiceRecord r, int callingUid,
1566 if (!force && r.restartDelay == 0) {
1569 // Remove from the restarting list; if the service is currently on the
1570 // restarting list, or the call is coming from another app, then this
1571 // service has become of much more interest so we reset the restart interval.
1572 boolean removed = mRestartingServices.remove(r);
1573 if (removed || callingUid != r.appInfo.uid) {
1574 r.resetRestartCounter();
1577 clearRestartingIfNeededLocked(r);
1579 mAm.mHandler.removeCallbacks(r.restarter);
1583 private void clearRestartingIfNeededLocked(ServiceRecord r) {
1584 if (r.restartTracker != null) {
1585 // If this is the last restarting record with this tracker, then clear
1586 // the tracker's restarting state.
1587 boolean stillTracking = false;
1588 for (int i=mRestartingServices.size()-1; i>=0; i--) {
1589 if (mRestartingServices.get(i).restartTracker == r.restartTracker) {
1590 stillTracking = true;
1594 if (!stillTracking) {
1595 r.restartTracker.setRestarting(false, mAm.mProcessStats.getMemFactorLocked(),
1596 SystemClock.uptimeMillis());
1597 r.restartTracker = null;
1602 private String bringUpServiceLocked(ServiceRecord r, int intentFlags, boolean execInFg,
1603 boolean whileRestarting, boolean permissionsReviewRequired)
1604 throws TransactionTooLargeException {
1605 //Slog.i(TAG, "Bring up service:");
1608 if (r.app != null && r.app.thread != null) {
1609 sendServiceArgsLocked(r, execInFg, false);
1613 if (!whileRestarting && r.restartDelay > 0) {
1614 // If waiting for a restart, then do nothing.
1618 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing up " + r + " " + r.intent);
1620 // We are now bringing the service up, so no longer in the
1621 // restarting state.
1622 if (mRestartingServices.remove(r)) {
1623 r.resetRestartCounter();
1624 clearRestartingIfNeededLocked(r);
1627 // Make sure this service is no longer considered delayed, we are starting it now.
1629 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (bring up): " + r);
1630 getServiceMap(r.userId).mDelayedStartList.remove(r);
1634 // Make sure that the user who owns this service is started. If not,
1635 // we don't want to allow it to run.
1636 if (!mAm.mUserController.hasStartedUserState(r.userId)) {
1637 String msg = "Unable to launch app "
1638 + r.appInfo.packageName + "/"
1639 + r.appInfo.uid + " for service "
1640 + r.intent.getIntent() + ": user " + r.userId + " is stopped";
1642 bringDownServiceLocked(r);
1646 // Service is now being launched, its package can't be stopped.
1648 AppGlobals.getPackageManager().setPackageStoppedState(
1649 r.packageName, false, r.userId);
1650 } catch (RemoteException e) {
1651 } catch (IllegalArgumentException e) {
1652 Slog.w(TAG, "Failed trying to unstop package "
1653 + r.packageName + ": " + e);
1656 final boolean isolated = (r.serviceInfo.flags&ServiceInfo.FLAG_ISOLATED_PROCESS) != 0;
1657 final String procName = r.processName;
1661 app = mAm.getProcessRecordLocked(procName, r.appInfo.uid, false);
1662 if (DEBUG_MU) Slog.v(TAG_MU, "bringUpServiceLocked: appInfo.uid=" + r.appInfo.uid
1664 if (app != null && app.thread != null) {
1666 app.addPackage(r.appInfo.packageName, r.appInfo.versionCode, mAm.mProcessStats);
1667 realStartServiceLocked(r, app, execInFg);
1669 } catch (TransactionTooLargeException e) {
1671 } catch (RemoteException e) {
1672 Slog.w(TAG, "Exception when starting service " + r.shortName, e);
1675 // If a dead object exception was thrown -- fall through to
1676 // restart the application.
1679 // If this service runs in an isolated process, then each time
1680 // we call startProcessLocked() we will get a new isolated
1681 // process, starting another process if we are currently waiting
1682 // for a previous process to come up. To deal with this, we store
1683 // in the service any current isolated process it is running in or
1684 // waiting to have come up.
1685 app = r.isolatedProc;
1688 // Not running -- get it started, and enqueue this service record
1689 // to be executed when the app comes up.
1690 if (app == null && !permissionsReviewRequired) {
1691 if ((app=mAm.startProcessLocked(procName, r.appInfo, true, intentFlags,
1692 "service", r.name, false, isolated, false)) == null) {
1693 String msg = "Unable to launch app "
1694 + r.appInfo.packageName + "/"
1695 + r.appInfo.uid + " for service "
1696 + r.intent.getIntent() + ": process is bad";
1698 bringDownServiceLocked(r);
1702 r.isolatedProc = app;
1706 if (!mPendingServices.contains(r)) {
1707 mPendingServices.add(r);
1710 if (r.delayedStop) {
1711 // Oh and hey we've already been asked to stop!
1712 r.delayedStop = false;
1713 if (r.startRequested) {
1714 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1715 "Applying delayed stop (in bring up): " + r);
1716 stopServiceLocked(r);
1723 private final void requestServiceBindingsLocked(ServiceRecord r, boolean execInFg)
1724 throws TransactionTooLargeException {
1725 for (int i=r.bindings.size()-1; i>=0; i--) {
1726 IntentBindRecord ibr = r.bindings.valueAt(i);
1727 if (!requestServiceBindingLocked(r, ibr, execInFg, false)) {
1733 private final void realStartServiceLocked(ServiceRecord r,
1734 ProcessRecord app, boolean execInFg) throws RemoteException {
1735 if (app.thread == null) {
1736 throw new RemoteException();
1739 Slog.v(TAG_MU, "realStartServiceLocked, ServiceRecord.uid = " + r.appInfo.uid
1740 + ", ProcessRecord.uid = " + app.uid);
1742 r.restartTime = r.lastActivity = SystemClock.uptimeMillis();
1744 final boolean newService = app.services.add(r);
1745 bumpServiceExecutingLocked(r, execInFg, "create");
1746 mAm.updateLruProcessLocked(app, false, null);
1747 mAm.updateOomAdjLocked();
1749 boolean created = false;
1751 if (LOG_SERVICE_START_STOP) {
1753 int lastPeriod = r.shortName.lastIndexOf('.');
1754 nameTerm = lastPeriod >= 0 ? r.shortName.substring(lastPeriod) : r.shortName;
1755 EventLogTags.writeAmCreateService(
1756 r.userId, System.identityHashCode(r), nameTerm, r.app.uid, r.app.pid);
1758 synchronized (r.stats.getBatteryStats()) {
1759 r.stats.startLaunchedLocked();
1761 mAm.notifyPackageUse(r.serviceInfo.packageName,
1762 PackageManager.NOTIFY_PACKAGE_USE_SERVICE);
1763 app.forceProcessStateUpTo(ActivityManager.PROCESS_STATE_SERVICE);
1764 app.thread.scheduleCreateService(r, r.serviceInfo,
1765 mAm.compatibilityInfoForPackageLocked(r.serviceInfo.applicationInfo),
1767 r.postNotification();
1769 } catch (DeadObjectException e) {
1770 Slog.w(TAG, "Application dead when creating service " + r);
1771 mAm.appDiedLocked(app);
1775 // Keep the executeNesting count accurate.
1776 final boolean inDestroying = mDestroyingServices.contains(r);
1777 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1781 app.services.remove(r);
1786 if (!inDestroying) {
1787 scheduleServiceRestartLocked(r, false);
1792 requestServiceBindingsLocked(r, execInFg);
1794 updateServiceClientActivitiesLocked(app, null, true);
1796 // If the service is in the started state, and there are no
1797 // pending arguments, then fake up one so its onStartCommand() will
1799 if (r.startRequested && r.callStart && r.pendingStarts.size() == 0) {
1800 r.pendingStarts.add(new ServiceRecord.StartItem(r, false, r.makeNextStartId(),
1804 sendServiceArgsLocked(r, execInFg, true);
1807 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "REM FR DELAY LIST (new proc): " + r);
1808 getServiceMap(r.userId).mDelayedStartList.remove(r);
1812 if (r.delayedStop) {
1813 // Oh and hey we've already been asked to stop!
1814 r.delayedStop = false;
1815 if (r.startRequested) {
1816 if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE,
1817 "Applying delayed stop (from start): " + r);
1818 stopServiceLocked(r);
1823 private final void sendServiceArgsLocked(ServiceRecord r, boolean execInFg,
1824 boolean oomAdjusted) throws TransactionTooLargeException {
1825 final int N = r.pendingStarts.size();
1830 while (r.pendingStarts.size() > 0) {
1831 Exception caughtException = null;
1832 ServiceRecord.StartItem si = null;
1834 si = r.pendingStarts.remove(0);
1835 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Sending arguments to: "
1836 + r + " " + r.intent + " args=" + si.intent);
1837 if (si.intent == null && N > 1) {
1838 // If somehow we got a dummy null intent in the middle,
1839 // then skip it. DO NOT skip a null intent when it is
1840 // the only one in the list -- this is to support the
1841 // onStartCommand(null) case.
1844 si.deliveredTime = SystemClock.uptimeMillis();
1845 r.deliveredStarts.add(si);
1847 if (si.neededGrants != null) {
1848 mAm.grantUriPermissionUncheckedFromIntentLocked(si.neededGrants,
1849 si.getUriPermissionsLocked());
1851 bumpServiceExecutingLocked(r, execInFg, "start");
1854 mAm.updateOomAdjLocked(r.app);
1857 if (si.deliveryCount > 1) {
1858 flags |= Service.START_FLAG_RETRY;
1860 if (si.doneExecutingCount > 0) {
1861 flags |= Service.START_FLAG_REDELIVERY;
1863 r.app.thread.scheduleServiceArgs(r, si.taskRemoved, si.id, flags, si.intent);
1864 } catch (TransactionTooLargeException e) {
1865 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Transaction too large: intent="
1867 caughtException = e;
1868 } catch (RemoteException e) {
1869 // Remote process gone... we'll let the normal cleanup take care of this.
1870 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Crashed while sending args: " + r);
1871 caughtException = e;
1872 } catch (Exception e) {
1873 Slog.w(TAG, "Unexpected exception", e);
1874 caughtException = e;
1877 if (caughtException != null) {
1878 // Keep nesting count correct
1879 final boolean inDestroying = mDestroyingServices.contains(r);
1880 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
1881 if (caughtException instanceof TransactionTooLargeException) {
1882 throw (TransactionTooLargeException)caughtException;
1889 private final boolean isServiceNeeded(ServiceRecord r, boolean knowConn, boolean hasConn) {
1890 // Are we still explicitly being asked to run?
1891 if (r.startRequested) {
1895 // Is someone still bound to us keepign us running?
1897 hasConn = r.hasAutoCreateConnections();
1906 private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
1908 //Slog.i(TAG, "Bring down service:");
1911 if (isServiceNeeded(r, knowConn, hasConn)) {
1915 // Are we in the process of launching?
1916 if (mPendingServices.contains(r)) {
1920 bringDownServiceLocked(r);
1923 private final void bringDownServiceLocked(ServiceRecord r) {
1924 //Slog.i(TAG, "Bring down service:");
1927 // Report to all of the connections that the service is no longer
1929 for (int conni=r.connections.size()-1; conni>=0; conni--) {
1930 ArrayList<ConnectionRecord> c = r.connections.valueAt(conni);
1931 for (int i=0; i<c.size(); i++) {
1932 ConnectionRecord cr = c.get(i);
1933 // There is still a connection to the service that is
1934 // being brought down. Mark it as dead.
1935 cr.serviceDead = true;
1937 cr.conn.connected(r.name, null);
1938 } catch (Exception e) {
1939 Slog.w(TAG, "Failure disconnecting service " + r.name +
1940 " to connection " + c.get(i).conn.asBinder() +
1941 " (in " + c.get(i).binding.client.processName + ")", e);
1946 // Tell the service that it has been unbound.
1947 if (r.app != null && r.app.thread != null) {
1948 for (int i=r.bindings.size()-1; i>=0; i--) {
1949 IntentBindRecord ibr = r.bindings.valueAt(i);
1950 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down binding " + ibr
1951 + ": hasBound=" + ibr.hasBound);
1954 bumpServiceExecutingLocked(r, false, "bring down unbind");
1955 mAm.updateOomAdjLocked(r.app);
1956 ibr.hasBound = false;
1957 r.app.thread.scheduleUnbindService(r,
1958 ibr.intent.getIntent());
1959 } catch (Exception e) {
1960 Slog.w(TAG, "Exception when unbinding service "
1962 serviceProcessGoneLocked(r);
1968 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Bringing down " + r + " " + r.intent);
1969 r.destroyTime = SystemClock.uptimeMillis();
1970 if (LOG_SERVICE_START_STOP) {
1971 EventLogTags.writeAmDestroyService(
1972 r.userId, System.identityHashCode(r), (r.app != null) ? r.app.pid : -1);
1975 final ServiceMap smap = getServiceMap(r.userId);
1976 smap.mServicesByName.remove(r.name);
1977 smap.mServicesByIntent.remove(r.intent);
1978 r.totalRestartCount = 0;
1979 unscheduleServiceRestartLocked(r, 0, true);
1981 // Also make sure it is not on the pending list.
1982 for (int i=mPendingServices.size()-1; i>=0; i--) {
1983 if (mPendingServices.get(i) == r) {
1984 mPendingServices.remove(i);
1985 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Removed pending: " + r);
1989 r.cancelNotification();
1990 r.isForeground = false;
1992 r.foregroundNoti = null;
1994 // Clear start entries.
1995 r.clearDeliveredStartsLocked();
1996 r.pendingStarts.clear();
1998 if (r.app != null) {
1999 synchronized (r.stats.getBatteryStats()) {
2000 r.stats.stopLaunchedLocked();
2002 r.app.services.remove(r);
2003 if (r.app.thread != null) {
2004 updateServiceForegroundLocked(r.app, false);
2006 bumpServiceExecutingLocked(r, false, "destroy");
2007 mDestroyingServices.add(r);
2008 r.destroying = true;
2009 mAm.updateOomAdjLocked(r.app);
2010 r.app.thread.scheduleStopService(r);
2011 } catch (Exception e) {
2012 Slog.w(TAG, "Exception when destroying service "
2014 serviceProcessGoneLocked(r);
2017 if (DEBUG_SERVICE) Slog.v(
2018 TAG_SERVICE, "Removed service that has no process: " + r);
2021 if (DEBUG_SERVICE) Slog.v(
2022 TAG_SERVICE, "Removed service that is not running: " + r);
2025 if (r.bindings.size() > 0) {
2029 if (r.restarter instanceof ServiceRestarter) {
2030 ((ServiceRestarter)r.restarter).setService(null);
2033 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2034 long now = SystemClock.uptimeMillis();
2035 if (r.tracker != null) {
2036 r.tracker.setStarted(false, memFactor, now);
2037 r.tracker.setBound(false, memFactor, now);
2038 if (r.executeNesting == 0) {
2039 r.tracker.clearCurrentOwner(r, false);
2044 smap.ensureNotStartingBackground(r);
2047 void removeConnectionLocked(
2048 ConnectionRecord c, ProcessRecord skipApp, ActivityRecord skipAct) {
2049 IBinder binder = c.conn.asBinder();
2050 AppBindRecord b = c.binding;
2051 ServiceRecord s = b.service;
2052 ArrayList<ConnectionRecord> clist = s.connections.get(binder);
2053 if (clist != null) {
2055 if (clist.size() == 0) {
2056 s.connections.remove(binder);
2059 b.connections.remove(c);
2060 if (c.activity != null && c.activity != skipAct) {
2061 if (c.activity.connections != null) {
2062 c.activity.connections.remove(c);
2065 if (b.client != skipApp) {
2066 b.client.connections.remove(c);
2067 if ((c.flags&Context.BIND_ABOVE_CLIENT) != 0) {
2068 b.client.updateHasAboveClientLocked();
2070 if (s.app != null) {
2071 updateServiceClientActivitiesLocked(s.app, c, true);
2074 clist = mServiceConnections.get(binder);
2075 if (clist != null) {
2077 if (clist.size() == 0) {
2078 mServiceConnections.remove(binder);
2082 mAm.stopAssociationLocked(b.client.uid, b.client.processName, s.appInfo.uid, s.name);
2084 if (b.connections.size() == 0) {
2085 b.intent.apps.remove(b.client);
2088 if (!c.serviceDead) {
2089 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Disconnecting binding " + b.intent
2090 + ": shouldUnbind=" + b.intent.hasBound);
2091 if (s.app != null && s.app.thread != null && b.intent.apps.size() == 0
2092 && b.intent.hasBound) {
2094 bumpServiceExecutingLocked(s, false, "unbind");
2095 if (b.client != s.app && (c.flags&Context.BIND_WAIVE_PRIORITY) == 0
2096 && s.app.setProcState <= ActivityManager.PROCESS_STATE_RECEIVER) {
2097 // If this service's process is not already in the cached list,
2098 // then update it in the LRU list here because this may be causing
2099 // it to go down there and we want it to start out near the top.
2100 mAm.updateLruProcessLocked(s.app, false, null);
2102 mAm.updateOomAdjLocked(s.app);
2103 b.intent.hasBound = false;
2104 // Assume the client doesn't want to know about a rebind;
2105 // we will deal with that later if it asks for one.
2106 b.intent.doRebind = false;
2107 s.app.thread.scheduleUnbindService(s, b.intent.intent.getIntent());
2108 } catch (Exception e) {
2109 Slog.w(TAG, "Exception when unbinding service " + s.shortName, e);
2110 serviceProcessGoneLocked(s);
2114 // If unbound while waiting to start, remove the pending service
2115 mPendingServices.remove(s);
2117 if ((c.flags&Context.BIND_AUTO_CREATE) != 0) {
2118 boolean hasAutoCreate = s.hasAutoCreateConnections();
2119 if (!hasAutoCreate) {
2120 if (s.tracker != null) {
2121 s.tracker.setBound(false, mAm.mProcessStats.getMemFactorLocked(),
2122 SystemClock.uptimeMillis());
2125 bringDownServiceIfNeededLocked(s, true, hasAutoCreate);
2130 void serviceDoneExecutingLocked(ServiceRecord r, int type, int startId, int res) {
2131 boolean inDestroying = mDestroyingServices.contains(r);
2133 if (type == ActivityThread.SERVICE_DONE_EXECUTING_START) {
2134 // This is a call from a service start... take care of
2138 case Service.START_STICKY_COMPATIBILITY:
2139 case Service.START_STICKY: {
2140 // We are done with the associated start arguments.
2141 r.findDeliveredStart(startId, true);
2142 // Don't stop if killed.
2143 r.stopIfKilled = false;
2146 case Service.START_NOT_STICKY: {
2147 // We are done with the associated start arguments.
2148 r.findDeliveredStart(startId, true);
2149 if (r.getLastStartId() == startId) {
2150 // There is no more work, and this service
2151 // doesn't want to hang around if killed.
2152 r.stopIfKilled = true;
2156 case Service.START_REDELIVER_INTENT: {
2157 // We'll keep this item until they explicitly
2158 // call stop for it, but keep track of the fact
2159 // that it was delivered.
2160 ServiceRecord.StartItem si = r.findDeliveredStart(startId, false);
2162 si.deliveryCount = 0;
2163 si.doneExecutingCount++;
2164 // Don't stop if killed.
2165 r.stopIfKilled = true;
2169 case Service.START_TASK_REMOVED_COMPLETE: {
2170 // Special processing for onTaskRemoved(). Don't
2171 // impact normal onStartCommand() processing.
2172 r.findDeliveredStart(startId, true);
2176 throw new IllegalArgumentException(
2177 "Unknown service start result: " + res);
2179 if (res == Service.START_STICKY_COMPATIBILITY) {
2180 r.callStart = false;
2182 } else if (type == ActivityThread.SERVICE_DONE_EXECUTING_STOP) {
2183 // This is the final call from destroying the service... we should
2184 // actually be getting rid of the service at this point. Do some
2185 // validation of its state, and ensure it will be fully removed.
2186 if (!inDestroying) {
2187 // Not sure what else to do with this... if it is not actually in the
2188 // destroying list, we don't need to make sure to remove it from it.
2189 // If the app is null, then it was probably removed because the process died,
2191 if (r.app != null) {
2192 Slog.wtfStack(TAG, "Service done with onDestroy, but not inDestroying: "
2193 + r + ", app=" + r.app);
2195 } else if (r.executeNesting != 1) {
2196 Slog.wtfStack(TAG, "Service done with onDestroy, but executeNesting="
2197 + r.executeNesting + ": " + r);
2198 // Fake it to keep from ANR due to orphaned entry.
2199 r.executeNesting = 1;
2202 final long origId = Binder.clearCallingIdentity();
2203 serviceDoneExecutingLocked(r, inDestroying, inDestroying);
2204 Binder.restoreCallingIdentity(origId);
2206 Slog.w(TAG, "Done executing unknown service from pid "
2207 + Binder.getCallingPid());
2211 private void serviceProcessGoneLocked(ServiceRecord r) {
2212 if (r.tracker != null) {
2213 int memFactor = mAm.mProcessStats.getMemFactorLocked();
2214 long now = SystemClock.uptimeMillis();
2215 r.tracker.setExecuting(false, memFactor, now);
2216 r.tracker.setBound(false, memFactor, now);
2217 r.tracker.setStarted(false, memFactor, now);
2219 serviceDoneExecutingLocked(r, true, true);
2222 private void serviceDoneExecutingLocked(ServiceRecord r, boolean inDestroying,
2223 boolean finishing) {
2224 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "<<< DONE EXECUTING " + r
2225 + ": nesting=" + r.executeNesting
2226 + ", inDestroying=" + inDestroying + ", app=" + r.app);
2227 else if (DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2228 "<<< DONE EXECUTING " + r.shortName);
2230 if (r.executeNesting <= 0) {
2231 if (r.app != null) {
2232 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
2233 "Nesting at 0 of " + r.shortName);
2234 r.app.execServicesFg = false;
2235 r.app.executingServices.remove(r);
2236 if (r.app.executingServices.size() == 0) {
2237 if (DEBUG_SERVICE || DEBUG_SERVICE_EXECUTING) Slog.v(TAG_SERVICE_EXECUTING,
2238 "No more executingServices of " + r.shortName);
2239 mAm.mHandler.removeMessages(ActivityManagerService.SERVICE_TIMEOUT_MSG, r.app);
2240 } else if (r.executeFg) {
2241 // Need to re-evaluate whether the app still needs to be in the foreground.
2242 for (int i=r.app.executingServices.size()-1; i>=0; i--) {
2243 if (r.app.executingServices.valueAt(i).executeFg) {
2244 r.app.execServicesFg = true;
2250 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE,
2251 "doneExecuting remove destroying " + r);
2252 mDestroyingServices.remove(r);
2255 mAm.updateOomAdjLocked(r.app);
2257 r.executeFg = false;
2258 if (r.tracker != null) {
2259 r.tracker.setExecuting(false, mAm.mProcessStats.getMemFactorLocked(),
2260 SystemClock.uptimeMillis());
2262 r.tracker.clearCurrentOwner(r, false);
2267 if (r.app != null && !r.app.persistent) {
2268 r.app.services.remove(r);
2275 boolean attachApplicationLocked(ProcessRecord proc, String processName)
2276 throws RemoteException {
2277 boolean didSomething = false;
2278 // Collect any services that are waiting for this process to come up.
2279 if (mPendingServices.size() > 0) {
2280 ServiceRecord sr = null;
2282 for (int i=0; i<mPendingServices.size(); i++) {
2283 sr = mPendingServices.get(i);
2284 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2285 || !processName.equals(sr.processName))) {
2289 mPendingServices.remove(i);
2291 proc.addPackage(sr.appInfo.packageName, sr.appInfo.versionCode,
2293 realStartServiceLocked(sr, proc, sr.createdFromFg);
2294 didSomething = true;
2295 if (!isServiceNeeded(sr, false, false)) {
2296 // We were waiting for this service to start, but it is actually no
2297 // longer needed. This could happen because bringDownServiceIfNeeded
2298 // won't bring down a service that is pending... so now the pending
2299 // is done, so let's drop it.
2300 bringDownServiceLocked(sr);
2303 } catch (RemoteException e) {
2304 Slog.w(TAG, "Exception in new application when starting service "
2309 // Also, if there are any services that are waiting to restart and
2310 // would run in this process, now is a good time to start them. It would
2311 // be weird to bring up the process but arbitrarily not let the services
2312 // run at this point just because their restart time hasn't come up.
2313 if (mRestartingServices.size() > 0) {
2315 for (int i=0; i<mRestartingServices.size(); i++) {
2316 sr = mRestartingServices.get(i);
2317 if (proc != sr.isolatedProc && (proc.uid != sr.appInfo.uid
2318 || !processName.equals(sr.processName))) {
2321 mAm.mHandler.removeCallbacks(sr.restarter);
2322 mAm.mHandler.post(sr.restarter);
2325 return didSomething;
2328 void processStartTimedOutLocked(ProcessRecord proc) {
2329 for (int i=0; i<mPendingServices.size(); i++) {
2330 ServiceRecord sr = mPendingServices.get(i);
2331 if ((proc.uid == sr.appInfo.uid
2332 && proc.processName.equals(sr.processName))
2333 || sr.isolatedProc == proc) {
2334 Slog.w(TAG, "Forcing bringing down service: " + sr);
2335 sr.isolatedProc = null;
2336 mPendingServices.remove(i);
2338 bringDownServiceLocked(sr);
2343 private boolean collectPackageServicesLocked(String packageName, Set<String> filterByClasses,
2344 boolean evenPersistent, boolean doit, boolean killProcess,
2345 ArrayMap<ComponentName, ServiceRecord> services) {
2346 boolean didSomething = false;
2347 for (int i = services.size() - 1; i >= 0; i--) {
2348 ServiceRecord service = services.valueAt(i);
2349 final boolean sameComponent = packageName == null
2350 || (service.packageName.equals(packageName)
2351 && (filterByClasses == null
2352 || filterByClasses.contains(service.name.getClassName())));
2354 && (service.app == null || evenPersistent || !service.app.persistent)) {
2358 didSomething = true;
2359 Slog.i(TAG, " Force stopping service " + service);
2360 if (service.app != null) {
2361 service.app.removed = killProcess;
2362 if (!service.app.persistent) {
2363 service.app.services.remove(service);
2367 service.isolatedProc = null;
2368 if (mTmpCollectionResults == null) {
2369 mTmpCollectionResults = new ArrayList<>();
2371 mTmpCollectionResults.add(service);
2374 return didSomething;
2377 boolean bringDownDisabledPackageServicesLocked(String packageName, Set<String> filterByClasses,
2378 int userId, boolean evenPersistent, boolean killProcess, boolean doit) {
2379 boolean didSomething = false;
2381 if (mTmpCollectionResults != null) {
2382 mTmpCollectionResults.clear();
2385 if (userId == UserHandle.USER_ALL) {
2386 for (int i = mServiceMap.size() - 1; i >= 0; i--) {
2387 didSomething |= collectPackageServicesLocked(packageName, filterByClasses,
2388 evenPersistent, doit, killProcess, mServiceMap.valueAt(i).mServicesByName);
2389 if (!doit && didSomething) {
2394 ServiceMap smap = mServiceMap.get(userId);
2396 ArrayMap<ComponentName, ServiceRecord> items = smap.mServicesByName;
2397 didSomething = collectPackageServicesLocked(packageName, filterByClasses,
2398 evenPersistent, doit, killProcess, items);
2402 if (mTmpCollectionResults != null) {
2403 for (int i = mTmpCollectionResults.size() - 1; i >= 0; i--) {
2404 bringDownServiceLocked(mTmpCollectionResults.get(i));
2406 mTmpCollectionResults.clear();
2408 return didSomething;
2411 void cleanUpRemovedTaskLocked(TaskRecord tr, ComponentName component, Intent baseIntent) {
2412 ArrayList<ServiceRecord> services = new ArrayList<>();
2413 ArrayMap<ComponentName, ServiceRecord> alls = getServices(tr.userId);
2414 for (int i = alls.size() - 1; i >= 0; i--) {
2415 ServiceRecord sr = alls.valueAt(i);
2416 if (sr.packageName.equals(component.getPackageName())) {
2421 // Take care of any running services associated with the app.
2422 for (int i = services.size() - 1; i >= 0; i--) {
2423 ServiceRecord sr = services.get(i);
2424 if (sr.startRequested) {
2425 if ((sr.serviceInfo.flags&ServiceInfo.FLAG_STOP_WITH_TASK) != 0) {
2426 Slog.i(TAG, "Stopping service " + sr.shortName + ": remove task");
2427 stopServiceLocked(sr);
2429 sr.pendingStarts.add(new ServiceRecord.StartItem(sr, true,
2430 sr.makeNextStartId(), baseIntent, null));
2431 if (sr.app != null && sr.app.thread != null) {
2432 // We always run in the foreground, since this is called as
2433 // part of the "remove task" UI operation.
2435 sendServiceArgsLocked(sr, true, false);
2436 } catch (TransactionTooLargeException e) {
2437 // Ignore, keep going.
2445 final void killServicesLocked(ProcessRecord app, boolean allowRestart) {
2446 // Report disconnected services.
2448 // XXX we are letting the client link to the service for
2449 // death notifications.
2450 if (app.services.size() > 0) {
2451 Iterator<ServiceRecord> it = app.services.iterator();
2452 while (it.hasNext()) {
2453 ServiceRecord r = it.next();
2454 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2455 ArrayList<ConnectionRecord> cl = r.connections.valueAt(conni);
2456 for (int i=0; i<cl.size(); i++) {
2457 ConnectionRecord c = cl.get(i);
2458 if (c.binding.client != app) {
2460 //c.conn.connected(r.className, null);
2461 } catch (Exception e) {
2462 // todo: this should be asynchronous!
2463 Slog.w(TAG, "Exception thrown disconnected servce "
2465 + " from app " + app.processName, e);
2474 // Clean up any connections this application has to other services.
2475 for (int i = app.connections.size() - 1; i >= 0; i--) {
2476 ConnectionRecord r = app.connections.valueAt(i);
2477 removeConnectionLocked(r, app, null);
2479 updateServiceConnectionActivitiesLocked(app);
2480 app.connections.clear();
2482 // Clear app state from services.
2483 for (int i = app.services.size() - 1; i >= 0; i--) {
2484 ServiceRecord sr = app.services.valueAt(i);
2485 synchronized (sr.stats.getBatteryStats()) {
2486 sr.stats.stopLaunchedLocked();
2488 if (sr.app != app && sr.app != null && !sr.app.persistent) {
2489 sr.app.services.remove(sr);
2492 sr.isolatedProc = null;
2493 sr.executeNesting = 0;
2494 sr.forceClearTracker();
2495 if (mDestroyingServices.remove(sr)) {
2496 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
2499 final int numClients = sr.bindings.size();
2500 for (int bindingi=numClients-1; bindingi>=0; bindingi--) {
2501 IntentBindRecord b = sr.bindings.valueAt(bindingi);
2502 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "Killing binding " + b
2503 + ": shouldUnbind=" + b.hasBound);
2505 b.requested = b.received = b.hasBound = false;
2506 // If this binding is coming from a cached process and is asking to keep
2507 // the service created, then we'll kill the cached process as well -- we
2508 // don't want to be thrashing around restarting processes that are only
2509 // there to be cached.
2510 for (int appi=b.apps.size()-1; appi>=0; appi--) {
2511 final ProcessRecord proc = b.apps.keyAt(appi);
2512 // If the process is already gone, skip it.
2513 if (proc.killedByAm || proc.thread == null) {
2516 // Only do this for processes that have an auto-create binding;
2517 // otherwise the binding can be left, because it won't cause the
2518 // service to restart.
2519 final AppBindRecord abind = b.apps.valueAt(appi);
2520 boolean hasCreate = false;
2521 for (int conni=abind.connections.size()-1; conni>=0; conni--) {
2522 ConnectionRecord conn = abind.connections.valueAt(conni);
2523 if ((conn.flags&(Context.BIND_AUTO_CREATE|Context.BIND_ALLOW_OOM_MANAGEMENT
2524 |Context.BIND_WAIVE_PRIORITY)) == Context.BIND_AUTO_CREATE) {
2532 // XXX turned off for now until we have more time to get a better policy.
2533 if (false && proc != null && !proc.persistent && proc.thread != null
2534 && proc.pid != 0 && proc.pid != ActivityManagerService.MY_PID
2535 && proc.setProcState >= ActivityManager.PROCESS_STATE_LAST_ACTIVITY) {
2536 proc.kill("bound to service " + sr.name.flattenToShortString()
2537 + " in dying proc " + (app != null ? app.processName : "??"), true);
2543 ServiceMap smap = getServiceMap(app.userId);
2545 // Now do remaining service cleanup.
2546 for (int i=app.services.size()-1; i>=0; i--) {
2547 ServiceRecord sr = app.services.valueAt(i);
2549 // Unless the process is persistent, this process record is going away,
2550 // so make sure the service is cleaned out of it.
2551 if (!app.persistent) {
2552 app.services.removeAt(i);
2555 // Sanity check: if the service listed for the app is not one
2556 // we actually are maintaining, just let it drop.
2557 final ServiceRecord curRec = smap.mServicesByName.get(sr.name);
2559 if (curRec != null) {
2560 Slog.wtf(TAG, "Service " + sr + " in process " + app
2561 + " not same as in map: " + curRec);
2566 // Any services running in the application may need to be placed
2567 // back in the pending list.
2568 if (allowRestart && sr.crashCount >= 2 && (sr.serviceInfo.applicationInfo.flags
2569 &ApplicationInfo.FLAG_PERSISTENT) == 0) {
2570 Slog.w(TAG, "Service crashed " + sr.crashCount
2571 + " times, stopping: " + sr);
2572 EventLog.writeEvent(EventLogTags.AM_SERVICE_CRASHED_TOO_MUCH,
2573 sr.userId, sr.crashCount, sr.shortName, app.pid);
2574 bringDownServiceLocked(sr);
2575 } else if (!allowRestart
2576 || !mAm.mUserController.isUserRunningLocked(sr.userId, 0)) {
2577 bringDownServiceLocked(sr);
2579 boolean canceled = scheduleServiceRestartLocked(sr, true);
2581 // Should the service remain running? Note that in the
2582 // extreme case of so many attempts to deliver a command
2583 // that it failed we also will stop it here.
2584 if (sr.startRequested && (sr.stopIfKilled || canceled)) {
2585 if (sr.pendingStarts.size() == 0) {
2586 sr.startRequested = false;
2587 if (sr.tracker != null) {
2588 sr.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
2589 SystemClock.uptimeMillis());
2591 if (!sr.hasAutoCreateConnections()) {
2592 // Whoops, no reason to restart!
2593 bringDownServiceLocked(sr);
2600 if (!allowRestart) {
2601 app.services.clear();
2603 // Make sure there are no more restarting services for this process.
2604 for (int i=mRestartingServices.size()-1; i>=0; i--) {
2605 ServiceRecord r = mRestartingServices.get(i);
2606 if (r.processName.equals(app.processName) &&
2607 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2608 mRestartingServices.remove(i);
2609 clearRestartingIfNeededLocked(r);
2612 for (int i=mPendingServices.size()-1; i>=0; i--) {
2613 ServiceRecord r = mPendingServices.get(i);
2614 if (r.processName.equals(app.processName) &&
2615 r.serviceInfo.applicationInfo.uid == app.info.uid) {
2616 mPendingServices.remove(i);
2621 // Make sure we have no more records on the stopping list.
2622 int i = mDestroyingServices.size();
2625 ServiceRecord sr = mDestroyingServices.get(i);
2626 if (sr.app == app) {
2627 sr.forceClearTracker();
2628 mDestroyingServices.remove(i);
2629 if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "killServices remove destroying " + sr);
2633 app.executingServices.clear();
2636 ActivityManager.RunningServiceInfo makeRunningServiceInfoLocked(ServiceRecord r) {
2637 ActivityManager.RunningServiceInfo info =
2638 new ActivityManager.RunningServiceInfo();
2639 info.service = r.name;
2640 if (r.app != null) {
2641 info.pid = r.app.pid;
2643 info.uid = r.appInfo.uid;
2644 info.process = r.processName;
2645 info.foreground = r.isForeground;
2646 info.activeSince = r.createTime;
2647 info.started = r.startRequested;
2648 info.clientCount = r.connections.size();
2649 info.crashCount = r.crashCount;
2650 info.lastActivityTime = r.lastActivity;
2651 if (r.isForeground) {
2652 info.flags |= ActivityManager.RunningServiceInfo.FLAG_FOREGROUND;
2654 if (r.startRequested) {
2655 info.flags |= ActivityManager.RunningServiceInfo.FLAG_STARTED;
2657 if (r.app != null && r.app.pid == ActivityManagerService.MY_PID) {
2658 info.flags |= ActivityManager.RunningServiceInfo.FLAG_SYSTEM_PROCESS;
2660 if (r.app != null && r.app.persistent) {
2661 info.flags |= ActivityManager.RunningServiceInfo.FLAG_PERSISTENT_PROCESS;
2664 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2665 ArrayList<ConnectionRecord> connl = r.connections.valueAt(conni);
2666 for (int i=0; i<connl.size(); i++) {
2667 ConnectionRecord conn = connl.get(i);
2668 if (conn.clientLabel != 0) {
2669 info.clientPackage = conn.binding.client.info.packageName;
2670 info.clientLabel = conn.clientLabel;
2678 List<ActivityManager.RunningServiceInfo> getRunningServiceInfoLocked(int maxNum,
2680 ArrayList<ActivityManager.RunningServiceInfo> res
2681 = new ArrayList<ActivityManager.RunningServiceInfo>();
2683 final int uid = Binder.getCallingUid();
2684 final long ident = Binder.clearCallingIdentity();
2686 if (ActivityManager.checkUidPermission(
2687 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
2688 uid) == PackageManager.PERMISSION_GRANTED) {
2689 int[] users = mAm.mUserController.getUsers();
2690 for (int ui=0; ui<users.length && res.size() < maxNum; ui++) {
2691 ArrayMap<ComponentName, ServiceRecord> alls = getServices(users[ui]);
2692 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2693 ServiceRecord sr = alls.valueAt(i);
2694 res.add(makeRunningServiceInfoLocked(sr));
2698 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2699 ServiceRecord r = mRestartingServices.get(i);
2700 ActivityManager.RunningServiceInfo info =
2701 makeRunningServiceInfoLocked(r);
2702 info.restarting = r.nextRestartTime;
2706 int userId = UserHandle.getUserId(uid);
2707 ArrayMap<ComponentName, ServiceRecord> alls = getServices(userId);
2708 for (int i=0; i<alls.size() && res.size() < maxNum; i++) {
2709 ServiceRecord sr = alls.valueAt(i);
2710 res.add(makeRunningServiceInfoLocked(sr));
2713 for (int i=0; i<mRestartingServices.size() && res.size() < maxNum; i++) {
2714 ServiceRecord r = mRestartingServices.get(i);
2715 if (r.userId == userId) {
2716 ActivityManager.RunningServiceInfo info =
2717 makeRunningServiceInfoLocked(r);
2718 info.restarting = r.nextRestartTime;
2724 Binder.restoreCallingIdentity(ident);
2730 public PendingIntent getRunningServiceControlPanelLocked(ComponentName name) {
2731 int userId = UserHandle.getUserId(Binder.getCallingUid());
2732 ServiceRecord r = getServiceByName(name, userId);
2734 for (int conni=r.connections.size()-1; conni>=0; conni--) {
2735 ArrayList<ConnectionRecord> conn = r.connections.valueAt(conni);
2736 for (int i=0; i<conn.size(); i++) {
2737 if (conn.get(i).clientIntent != null) {
2738 return conn.get(i).clientIntent;
2746 void serviceTimeout(ProcessRecord proc) {
2747 String anrMessage = null;
2750 if (proc.executingServices.size() == 0 || proc.thread == null) {
2753 final long now = SystemClock.uptimeMillis();
2754 final long maxTime = now -
2755 (proc.execServicesFg ? SERVICE_TIMEOUT : SERVICE_BACKGROUND_TIMEOUT);
2756 ServiceRecord timeout = null;
2758 for (int i=proc.executingServices.size()-1; i>=0; i--) {
2759 ServiceRecord sr = proc.executingServices.valueAt(i);
2760 if (sr.executingStart < maxTime) {
2764 if (sr.executingStart > nextTime) {
2765 nextTime = sr.executingStart;
2768 if (timeout != null && mAm.mLruProcesses.contains(proc)) {
2769 Slog.w(TAG, "Timeout executing service: " + timeout);
2770 StringWriter sw = new StringWriter();
2771 PrintWriter pw = new FastPrintWriter(sw, false, 1024);
2772 pw.println(timeout);
2773 timeout.dump(pw, " ");
2775 mLastAnrDump = sw.toString();
2776 mAm.mHandler.removeCallbacks(mLastAnrDumpClearer);
2777 mAm.mHandler.postDelayed(mLastAnrDumpClearer, LAST_ANR_LIFETIME_DURATION_MSECS);
2778 anrMessage = "executing service " + timeout.shortName;
2780 Message msg = mAm.mHandler.obtainMessage(
2781 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2783 mAm.mHandler.sendMessageAtTime(msg, proc.execServicesFg
2784 ? (nextTime+SERVICE_TIMEOUT) : (nextTime + SERVICE_BACKGROUND_TIMEOUT));
2788 if (anrMessage != null) {
2789 mAm.mAppErrors.appNotResponding(proc, null, null, false, anrMessage);
2793 void scheduleServiceTimeoutLocked(ProcessRecord proc) {
2794 if (proc.executingServices.size() == 0 || proc.thread == null) {
2797 long now = SystemClock.uptimeMillis();
2798 Message msg = mAm.mHandler.obtainMessage(
2799 ActivityManagerService.SERVICE_TIMEOUT_MSG);
2801 mAm.mHandler.sendMessageAtTime(msg,
2802 proc.execServicesFg ? (now+SERVICE_TIMEOUT) : (now+ SERVICE_BACKGROUND_TIMEOUT));
2806 * Prints a list of ServiceRecords (dumpsys activity services)
2808 List<ServiceRecord> collectServicesToDumpLocked(ItemMatcher matcher, String dumpPackage) {
2809 final ArrayList<ServiceRecord> services = new ArrayList<>();
2810 final int[] users = mAm.mUserController.getUsers();
2811 for (int user : users) {
2812 ServiceMap smap = getServiceMap(user);
2813 if (smap.mServicesByName.size() > 0) {
2814 for (int si=0; si<smap.mServicesByName.size(); si++) {
2815 ServiceRecord r = smap.mServicesByName.valueAt(si);
2816 if (!matcher.match(r, r.name)) {
2819 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2830 final class ServiceDumper {
2831 private final FileDescriptor fd;
2832 private final PrintWriter pw;
2833 private final String[] args;
2834 private final int opti;
2835 private final boolean dumpAll;
2836 private final String dumpPackage;
2837 private final ItemMatcher matcher;
2838 private final ArrayList<ServiceRecord> services = new ArrayList<>();
2840 private final long nowReal = SystemClock.elapsedRealtime();
2842 private boolean needSep = false;
2843 private boolean printedAnything = false;
2844 private boolean printed = false;
2847 * Note: do not call directly, use {@link #newServiceDumperLocked} instead (this
2848 * must be called with the lock held).
2850 ServiceDumper(FileDescriptor fd, PrintWriter pw, String[] args,
2851 int opti, boolean dumpAll, String dumpPackage) {
2856 this.dumpAll = dumpAll;
2857 this.dumpPackage = dumpPackage;
2858 matcher = new ItemMatcher();
2859 matcher.build(args, opti);
2861 final int[] users = mAm.mUserController.getUsers();
2862 for (int user : users) {
2863 ServiceMap smap = getServiceMap(user);
2864 if (smap.mServicesByName.size() > 0) {
2865 for (int si=0; si<smap.mServicesByName.size(); si++) {
2866 ServiceRecord r = smap.mServicesByName.valueAt(si);
2867 if (!matcher.match(r, r.name)) {
2870 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
2879 private void dumpHeaderLocked() {
2880 pw.println("ACTIVITY MANAGER SERVICES (dumpsys activity services)");
2881 if (mLastAnrDump != null) {
2882 pw.println(" Last ANR service:");
2883 pw.print(mLastAnrDump);
2892 int[] users = mAm.mUserController.getUsers();
2893 for (int user : users) {
2894 // Find the first service for this user.
2896 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
2900 if (serviceIdx < services.size()) {
2902 while (serviceIdx < services.size()) {
2903 ServiceRecord r = services.get(serviceIdx);
2905 if (r.userId != user) {
2908 dumpServiceLocalLocked(r);
2913 dumpUserRemainsLocked(user);
2915 } catch (Exception e) {
2916 Slog.w(TAG, "Exception in dumpServicesLocked", e);
2919 dumpRemainsLocked();
2922 void dumpWithClient() {
2928 int[] users = mAm.mUserController.getUsers();
2929 for (int user : users) {
2930 // Find the first service for this user.
2932 while (serviceIdx < services.size() && services.get(serviceIdx).userId != user) {
2936 if (serviceIdx < services.size()) {
2938 while (serviceIdx < services.size()) {
2939 ServiceRecord r = services.get(serviceIdx);
2941 if (r.userId != user) {
2945 dumpServiceLocalLocked(r);
2947 dumpServiceClient(r);
2953 dumpUserRemainsLocked(user);
2956 } catch (Exception e) {
2957 Slog.w(TAG, "Exception in dumpServicesLocked", e);
2961 dumpRemainsLocked();
2965 private void dumpUserHeaderLocked(int user) {
2967 if (printedAnything) {
2970 pw.println(" User " + user + " active services:");
2973 printedAnything = true;
2979 private void dumpServiceLocalLocked(ServiceRecord r) {
2980 dumpUserHeaderLocked(r.userId);
2989 pw.print(" created=");
2990 TimeUtils.formatDuration(r.createTime, nowReal, pw);
2991 pw.print(" started=");
2992 pw.print(r.startRequested);
2993 pw.print(" connections=");
2994 pw.println(r.connections.size());
2995 if (r.connections.size() > 0) {
2996 pw.println(" Connections:");
2997 for (int conni=0; conni<r.connections.size(); conni++) {
2998 ArrayList<ConnectionRecord> clist = r.connections.valueAt(conni);
2999 for (int i = 0; i < clist.size(); i++) {
3000 ConnectionRecord conn = clist.get(i);
3002 pw.print(conn.binding.intent.intent.getIntent()
3003 .toShortString(false, false, false, false));
3005 ProcessRecord proc = conn.binding.client;
3006 pw.println(proc != null ? proc.toShortString() : "null");
3013 private void dumpServiceClient(ServiceRecord r) {
3014 final ProcessRecord proc = r.app;
3018 final IApplicationThread thread = proc.thread;
3019 if (thread == null) {
3022 pw.println(" Client:");
3025 TransferPipe tp = new TransferPipe();
3027 thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
3028 tp.setBufferPrefix(" ");
3029 // Short timeout, since blocking here can
3030 // deadlock with the application.
3035 } catch (IOException e) {
3036 pw.println(" Failure while dumping the service: " + e);
3037 } catch (RemoteException e) {
3038 pw.println(" Got a RemoteException while dumping the service");
3043 private void dumpUserRemainsLocked(int user) {
3044 ServiceMap smap = getServiceMap(user);
3046 for (int si=0, SN=smap.mDelayedStartList.size(); si<SN; si++) {
3047 ServiceRecord r = smap.mDelayedStartList.get(si);
3048 if (!matcher.match(r, r.name)) {
3051 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3055 if (printedAnything) {
3058 pw.println(" User " + user + " delayed start services:");
3061 printedAnything = true;
3062 pw.print(" * Delayed start "); pw.println(r);
3065 for (int si=0, SN=smap.mStartingBackground.size(); si<SN; si++) {
3066 ServiceRecord r = smap.mStartingBackground.get(si);
3067 if (!matcher.match(r, r.name)) {
3070 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3074 if (printedAnything) {
3077 pw.println(" User " + user + " starting in background:");
3080 printedAnything = true;
3081 pw.print(" * Starting bg "); pw.println(r);
3085 private void dumpRemainsLocked() {
3086 if (mPendingServices.size() > 0) {
3088 for (int i=0; i<mPendingServices.size(); i++) {
3089 ServiceRecord r = mPendingServices.get(i);
3090 if (!matcher.match(r, r.name)) {
3093 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3096 printedAnything = true;
3098 if (needSep) pw.println();
3100 pw.println(" Pending services:");
3103 pw.print(" * Pending "); pw.println(r);
3109 if (mRestartingServices.size() > 0) {
3111 for (int i=0; i<mRestartingServices.size(); i++) {
3112 ServiceRecord r = mRestartingServices.get(i);
3113 if (!matcher.match(r, r.name)) {
3116 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3119 printedAnything = true;
3121 if (needSep) pw.println();
3123 pw.println(" Restarting services:");
3126 pw.print(" * Restarting "); pw.println(r);
3132 if (mDestroyingServices.size() > 0) {
3134 for (int i=0; i< mDestroyingServices.size(); i++) {
3135 ServiceRecord r = mDestroyingServices.get(i);
3136 if (!matcher.match(r, r.name)) {
3139 if (dumpPackage != null && !dumpPackage.equals(r.appInfo.packageName)) {
3142 printedAnything = true;
3144 if (needSep) pw.println();
3146 pw.println(" Destroying services:");
3149 pw.print(" * Destroy "); pw.println(r);
3157 for (int ic=0; ic<mServiceConnections.size(); ic++) {
3158 ArrayList<ConnectionRecord> r = mServiceConnections.valueAt(ic);
3159 for (int i=0; i<r.size(); i++) {
3160 ConnectionRecord cr = r.get(i);
3161 if (!matcher.match(cr.binding.service, cr.binding.service.name)) {
3164 if (dumpPackage != null && (cr.binding.client == null
3165 || !dumpPackage.equals(cr.binding.client.info.packageName))) {
3168 printedAnything = true;
3170 if (needSep) pw.println();
3172 pw.println(" Connection bindings to services:");
3175 pw.print(" * "); pw.println(cr);
3181 if (!printedAnything) {
3182 pw.println(" (nothing)");
3187 ServiceDumper newServiceDumperLocked(FileDescriptor fd, PrintWriter pw, String[] args,
3188 int opti, boolean dumpAll, String dumpPackage) {
3189 return new ServiceDumper(fd, pw, args, opti, dumpAll, dumpPackage);
3193 * There are three ways to call this:
3194 * - no service specified: dump all the services
3195 * - a flattened component name that matched an existing service was specified as the
3196 * first arg: dump that one service
3197 * - the first arg isn't the flattened component name of an existing service:
3198 * dump all services whose component contains the first arg as a substring
3200 protected boolean dumpService(FileDescriptor fd, PrintWriter pw, String name, String[] args,
3201 int opti, boolean dumpAll) {
3202 ArrayList<ServiceRecord> services = new ArrayList<ServiceRecord>();
3204 synchronized (mAm) {
3205 int[] users = mAm.mUserController.getUsers();
3206 if ("all".equals(name)) {
3207 for (int user : users) {
3208 ServiceMap smap = mServiceMap.get(user);
3212 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3213 for (int i=0; i<alls.size(); i++) {
3214 ServiceRecord r1 = alls.valueAt(i);
3219 ComponentName componentName = name != null
3220 ? ComponentName.unflattenFromString(name) : null;
3222 if (componentName == null) {
3223 // Not a '/' separated full component name; maybe an object ID?
3225 objectId = Integer.parseInt(name, 16);
3227 componentName = null;
3228 } catch (RuntimeException e) {
3232 for (int user : users) {
3233 ServiceMap smap = mServiceMap.get(user);
3237 ArrayMap<ComponentName, ServiceRecord> alls = smap.mServicesByName;
3238 for (int i=0; i<alls.size(); i++) {
3239 ServiceRecord r1 = alls.valueAt(i);
3240 if (componentName != null) {
3241 if (r1.name.equals(componentName)) {
3244 } else if (name != null) {
3245 if (r1.name.flattenToString().contains(name)) {
3248 } else if (System.identityHashCode(r1) == objectId) {
3256 if (services.size() <= 0) {
3260 boolean needSep = false;
3261 for (int i=0; i<services.size(); i++) {
3266 dumpService("", fd, pw, services.get(i), args, dumpAll);
3272 * Invokes IApplicationThread.dumpService() on the thread of the specified service if
3273 * there is a thread associated with the service.
3275 private void dumpService(String prefix, FileDescriptor fd, PrintWriter pw,
3276 final ServiceRecord r, String[] args, boolean dumpAll) {
3277 String innerPrefix = prefix + " ";
3278 synchronized (mAm) {
3279 pw.print(prefix); pw.print("SERVICE ");
3280 pw.print(r.shortName); pw.print(" ");
3281 pw.print(Integer.toHexString(System.identityHashCode(r)));
3283 if (r.app != null) pw.println(r.app.pid);
3284 else pw.println("(not running)");
3286 r.dump(pw, innerPrefix);
3289 if (r.app != null && r.app.thread != null) {
3290 pw.print(prefix); pw.println(" Client:");
3293 TransferPipe tp = new TransferPipe();
3295 r.app.thread.dumpService(tp.getWriteFd().getFileDescriptor(), r, args);
3296 tp.setBufferPrefix(prefix + " ");
3301 } catch (IOException e) {
3302 pw.println(prefix + " Failure while dumping the service: " + e);
3303 } catch (RemoteException e) {
3304 pw.println(prefix + " Got a RemoteException while dumping the service");