ProcessRecord.java revision f0f94d129b6eb3c48624e915898d86d4f2de59ff
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
19import android.util.ArraySet;
20import com.android.internal.app.ProcessStats;
21import com.android.internal.os.BatteryStatsImpl;
22
23import android.app.ActivityManager;
24import android.app.Dialog;
25import android.app.IApplicationThread;
26import android.app.IInstrumentationWatcher;
27import android.app.IUiAutomationConnection;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.pm.ApplicationInfo;
31import android.content.res.CompatibilityInfo;
32import android.os.Bundle;
33import android.os.IBinder;
34import android.os.Process;
35import android.os.SystemClock;
36import android.os.UserHandle;
37import android.util.ArrayMap;
38import android.util.PrintWriterPrinter;
39import android.util.TimeUtils;
40
41import java.io.PrintWriter;
42import java.util.ArrayList;
43
44/**
45 * Full information about a particular process that
46 * is currently running.
47 */
48final class ProcessRecord {
49    private final BatteryStatsImpl mBatteryStats; // where to collect runtime statistics
50    final ApplicationInfo info; // all about the first app in the process
51    final boolean isolated;     // true if this is a special isolated process
52    final int uid;              // uid of process; may be different from 'info' if isolated
53    final int userId;           // user of process.
54    final String processName;   // name of the process
55    // List of packages running in the process
56    final ArrayMap<String, ProcessStats.ProcessState> pkgList
57            = new ArrayMap<String, ProcessStats.ProcessState>();
58    IApplicationThread thread;  // the actual proc...  may be null only if
59                                // 'persistent' is true (in which case we
60                                // are in the process of launching the app)
61    ProcessStats.ProcessState baseProcessTracker;
62    BatteryStatsImpl.Uid.Proc curProcBatteryStats;
63    int pid;                    // The process of this application; 0 if none
64    boolean starting;           // True if the process is being started
65    long lastActivityTime;      // For managing the LRU list
66    long lastPssTime;           // Last time we retrieved PSS data
67    long nextPssTime;           // Next time we want to request PSS data
68    long lastStateTime;         // Last time setProcState changed
69    long initialIdlePss;        // Initial memory pss of process for idle maintenance.
70    long lastPss;               // Last computed memory pss.
71    long lastCachedPss;         // Last computed pss when in cached state.
72    int maxAdj;                 // Maximum OOM adjustment for this process
73    int curRawAdj;              // Current OOM unlimited adjustment for this process
74    int setRawAdj;              // Last set OOM unlimited adjustment for this process
75    int curAdj;                 // Current OOM adjustment for this process
76    int setAdj;                 // Last set OOM adjustment for this process
77    int curSchedGroup;          // Currently desired scheduling class
78    int setSchedGroup;          // Last set to background scheduling class
79    int trimMemoryLevel;        // Last selected memory trimming level
80    int memImportance;          // Importance constant computed from curAdj
81    int curProcState = -1;      // Currently computed process state: ActivityManager.PROCESS_STATE_*
82    int repProcState = -1;      // Last reported process state
83    int setProcState = -1;      // Last set process state in process tracker
84    int pssProcState = -1;      // The proc state we are currently requesting pss for
85    boolean serviceb;           // Process currently is on the service B list
86    boolean serviceHighRam;     // We are forcing to service B list due to its RAM use
87    boolean keeping;            // Actively running code so don't kill due to that?
88    boolean setIsForeground;    // Running foreground UI when last set?
89    boolean notCachedSinceIdle; // Has this process not been in a cached state since last idle?
90    boolean hasClientActivities;  // Are there any client services with activities?
91    boolean hasStartedServices; // Are there any started services running in this process?
92    boolean foregroundServices; // Running any services that are foreground?
93    boolean foregroundActivities; // Running any activities that are foreground?
94    boolean systemNoUi;         // This is a system process, but not currently showing UI.
95    boolean hasShownUi;         // Has UI been shown in this process since it was started?
96    boolean pendingUiClean;     // Want to clean up resources from showing UI?
97    boolean hasAboveClient;     // Bound using BIND_ABOVE_CLIENT, so want to be lower
98    boolean treatLikeActivity;  // Bound using BIND_TREAT_LIKE_ACTIVITY
99    boolean bad;                // True if disabled in the bad process list
100    boolean killedByAm;         // True when proc has been killed by activity manager, not for RAM
101    boolean procStateChanged;   // Keep track of whether we changed 'setAdj'.
102    String waitingToKill;       // Process is waiting to be killed when in the bg, and reason
103    IBinder forcingToForeground;// Token that is forcing this process to be foreground
104    int adjSeq;                 // Sequence id for identifying oom_adj assignment cycles
105    int lruSeq;                 // Sequence id for identifying LRU update cycles
106    CompatibilityInfo compat;   // last used compatibility mode
107    IBinder.DeathRecipient deathRecipient; // Who is watching for the death.
108    ComponentName instrumentationClass;// class installed to instrument app
109    ApplicationInfo instrumentationInfo; // the application being instrumented
110    String instrumentationProfileFile; // where to save profiling
111    IInstrumentationWatcher instrumentationWatcher; // who is waiting
112    IUiAutomationConnection instrumentationUiAutomationConnection; // Connection to use the UI introspection APIs.
113    Bundle instrumentationArguments;// as given to us
114    ComponentName instrumentationResultClass;// copy of instrumentationClass
115    boolean usingWrapper;       // Set to true when process was launched with a wrapper attached
116    BroadcastRecord curReceiver;// receiver currently running in the app
117    long lastWakeTime;          // How long proc held wake lock at last check
118    long lastCpuTime;           // How long proc has run CPU at last check
119    long curCpuTime;            // How long proc has run CPU most recently
120    long lastRequestedGc;       // When we last asked the app to do a gc
121    long lastLowMemory;         // When we last told the app that memory is low
122    boolean reportLowMemory;    // Set to true when waiting to report low mem
123    boolean empty;              // Is this an empty background process?
124    boolean cached;             // Is this a cached process?
125    String adjType;             // Debugging: primary thing impacting oom_adj.
126    int adjTypeCode;            // Debugging: adj code to report to app.
127    Object adjSource;           // Debugging: option dependent object.
128    int adjSourceOom;           // Debugging: oom_adj of adjSource's process.
129    Object adjTarget;           // Debugging: target component impacting oom_adj.
130
131    // contains HistoryRecord objects
132    final ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
133    // all ServiceRecord running in this process
134    final ArraySet<ServiceRecord> services = new ArraySet<ServiceRecord>();
135    // services that are currently executing code (need to remain foreground).
136    final ArraySet<ServiceRecord> executingServices
137             = new ArraySet<ServiceRecord>();
138    // All ConnectionRecord this process holds
139    final ArraySet<ConnectionRecord> connections
140            = new ArraySet<ConnectionRecord>();
141    // all IIntentReceivers that are registered from this process.
142    final ArraySet<ReceiverList> receivers = new ArraySet<ReceiverList>();
143    // class (String) -> ContentProviderRecord
144    final ArrayMap<String, ContentProviderRecord> pubProviders
145            = new ArrayMap<String, ContentProviderRecord>();
146    // All ContentProviderRecord process is using
147    final ArrayList<ContentProviderConnection> conProviders
148            = new ArrayList<ContentProviderConnection>();
149
150    boolean execServicesFg;     // do we need to be executing services in the foreground?
151    boolean persistent;         // always keep this application running?
152    boolean crashing;           // are we in the process of crashing?
153    Dialog crashDialog;         // dialog being displayed due to crash.
154    boolean forceCrashReport;   // suppress normal auto-dismiss of crash dialog & report UI?
155    boolean notResponding;      // does the app have a not responding dialog?
156    Dialog anrDialog;           // dialog being displayed due to app not resp.
157    boolean removed;            // has app package been removed from device?
158    boolean debugging;          // was app launched for debugging?
159    boolean waitedForDebugger;  // has process show wait for debugger dialog?
160    Dialog waitDialog;          // current wait for debugger dialog
161
162    String shortStringName;     // caching of toShortString() result.
163    String stringName;          // caching of toString() result.
164
165    // These reports are generated & stored when an app gets into an error condition.
166    // They will be "null" when all is OK.
167    ActivityManager.ProcessErrorStateInfo crashingReport;
168    ActivityManager.ProcessErrorStateInfo notRespondingReport;
169
170    // Who will be notified of the error. This is usually an activity in the
171    // app that installed the package.
172    ComponentName errorReportReceiver;
173
174    void dump(PrintWriter pw, String prefix) {
175        final long now = SystemClock.uptimeMillis();
176
177        pw.print(prefix); pw.print("user #"); pw.print(userId);
178                pw.print(" uid="); pw.print(info.uid);
179        if (uid != info.uid) {
180            pw.print(" ISOLATED uid="); pw.print(uid);
181        }
182        pw.println();
183        if (info.className != null) {
184            pw.print(prefix); pw.print("class="); pw.println(info.className);
185        }
186        if (info.manageSpaceActivityName != null) {
187            pw.print(prefix); pw.print("manageSpaceActivityName=");
188            pw.println(info.manageSpaceActivityName);
189        }
190        pw.print(prefix); pw.print("dir="); pw.print(info.sourceDir);
191                pw.print(" publicDir="); pw.print(info.publicSourceDir);
192                pw.print(" data="); pw.println(info.dataDir);
193        pw.print(prefix); pw.print("packageList={");
194        for (int i=0; i<pkgList.size(); i++) {
195            if (i > 0) pw.print(", ");
196            pw.print(pkgList.keyAt(i));
197        }
198        pw.println("}");
199        pw.print(prefix); pw.print("compat="); pw.println(compat);
200        if (instrumentationClass != null || instrumentationProfileFile != null
201                || instrumentationArguments != null) {
202            pw.print(prefix); pw.print("instrumentationClass=");
203                    pw.print(instrumentationClass);
204                    pw.print(" instrumentationProfileFile=");
205                    pw.println(instrumentationProfileFile);
206            pw.print(prefix); pw.print("instrumentationArguments=");
207                    pw.println(instrumentationArguments);
208            pw.print(prefix); pw.print("instrumentationInfo=");
209                    pw.println(instrumentationInfo);
210            if (instrumentationInfo != null) {
211                instrumentationInfo.dump(new PrintWriterPrinter(pw), prefix + "  ");
212            }
213        }
214        pw.print(prefix); pw.print("thread="); pw.println(thread);
215        pw.print(prefix); pw.print("pid="); pw.print(pid); pw.print(" starting=");
216                pw.println(starting);
217        pw.print(prefix); pw.print("lastActivityTime=");
218                TimeUtils.formatDuration(lastActivityTime, now, pw);
219                pw.print(" lastPssTime=");
220                TimeUtils.formatDuration(lastPssTime, now, pw);
221                pw.print(" nextPssTime=");
222                TimeUtils.formatDuration(nextPssTime, now, pw);
223                pw.println();
224        pw.print(prefix); pw.print("adjSeq="); pw.print(adjSeq);
225                pw.print(" lruSeq="); pw.print(lruSeq);
226                pw.print(" lastPss="); pw.print(lastPss);
227                pw.print(" lastCachedPss="); pw.println(lastCachedPss);
228        pw.print(prefix); pw.print("keeping="); pw.print(keeping);
229                pw.print(" cached="); pw.print(cached);
230                pw.print(" empty="); pw.println(empty);
231        if (serviceb) {
232            pw.print(prefix); pw.print("serviceb="); pw.print(serviceb);
233                    pw.print(" serviceHighRam="); pw.println(serviceHighRam);
234        }
235        if (notCachedSinceIdle) {
236            pw.print(prefix); pw.print("notCachedSinceIdle="); pw.print(notCachedSinceIdle);
237                    pw.print(" initialIdlePss="); pw.println(initialIdlePss);
238        }
239        pw.print(prefix); pw.print("oom: max="); pw.print(maxAdj);
240                pw.print(" curRaw="); pw.print(curRawAdj);
241                pw.print(" setRaw="); pw.print(setRawAdj);
242                pw.print(" cur="); pw.print(curAdj);
243                pw.print(" set="); pw.println(setAdj);
244        pw.print(prefix); pw.print("curSchedGroup="); pw.print(curSchedGroup);
245                pw.print(" setSchedGroup="); pw.print(setSchedGroup);
246                pw.print(" systemNoUi="); pw.print(systemNoUi);
247                pw.print(" trimMemoryLevel="); pw.println(trimMemoryLevel);
248        pw.print(prefix); pw.print("curProcState="); pw.print(curProcState);
249                pw.print(" repProcState="); pw.print(repProcState);
250                pw.print(" pssProcState="); pw.print(pssProcState);
251                pw.print(" setProcState="); pw.print(setProcState);
252                pw.print(" lastStateTime=");
253                TimeUtils.formatDuration(lastStateTime, now, pw);
254                pw.println();
255        if (hasShownUi || pendingUiClean || hasAboveClient || treatLikeActivity) {
256            pw.print(prefix); pw.print("hasShownUi="); pw.print(hasShownUi);
257                    pw.print(" pendingUiClean="); pw.print(pendingUiClean);
258                    pw.print(" hasAboveClient="); pw.print(hasAboveClient);
259                    pw.print(" treatLikeActivity="); pw.println(treatLikeActivity);
260        }
261        if (setIsForeground || foregroundServices || forcingToForeground != null) {
262            pw.print(prefix); pw.print("setIsForeground="); pw.print(setIsForeground);
263                    pw.print(" foregroundServices="); pw.print(foregroundServices);
264                    pw.print(" forcingToForeground="); pw.println(forcingToForeground);
265        }
266        if (persistent || removed) {
267            pw.print(prefix); pw.print("persistent="); pw.print(persistent);
268                    pw.print(" removed="); pw.println(removed);
269        }
270        if (hasClientActivities || foregroundActivities) {
271            pw.print(prefix); pw.print("hasClientActivities="); pw.print(hasClientActivities);
272                    pw.print(" foregroundActivities="); pw.println(foregroundActivities);
273        }
274        if (hasStartedServices) {
275            pw.print(prefix); pw.print("hasStartedServices="); pw.println(hasStartedServices);
276        }
277        if (!keeping) {
278            long wtime;
279            synchronized (mBatteryStats) {
280                wtime = mBatteryStats.getProcessWakeTime(info.uid,
281                        pid, SystemClock.elapsedRealtime());
282            }
283            long timeUsed = wtime - lastWakeTime;
284            pw.print(prefix); pw.print("lastWakeTime="); pw.print(lastWakeTime);
285                    pw.print(" timeUsed=");
286                    TimeUtils.formatDuration(timeUsed, pw); pw.println("");
287            pw.print(prefix); pw.print("lastCpuTime="); pw.print(lastCpuTime);
288                    pw.print(" timeUsed=");
289                    TimeUtils.formatDuration(curCpuTime-lastCpuTime, pw); pw.println("");
290        }
291        pw.print(prefix); pw.print("lastRequestedGc=");
292                TimeUtils.formatDuration(lastRequestedGc, now, pw);
293                pw.print(" lastLowMemory=");
294                TimeUtils.formatDuration(lastLowMemory, now, pw);
295                pw.print(" reportLowMemory="); pw.println(reportLowMemory);
296        if (killedByAm || waitingToKill != null) {
297            pw.print(prefix); pw.print("killedByAm="); pw.print(killedByAm);
298                    pw.print(" waitingToKill="); pw.println(waitingToKill);
299        }
300        if (debugging || crashing || crashDialog != null || notResponding
301                || anrDialog != null || bad) {
302            pw.print(prefix); pw.print("debugging="); pw.print(debugging);
303                    pw.print(" crashing="); pw.print(crashing);
304                    pw.print(" "); pw.print(crashDialog);
305                    pw.print(" notResponding="); pw.print(notResponding);
306                    pw.print(" " ); pw.print(anrDialog);
307                    pw.print(" bad="); pw.print(bad);
308
309                    // crashing or notResponding is always set before errorReportReceiver
310                    if (errorReportReceiver != null) {
311                        pw.print(" errorReportReceiver=");
312                        pw.print(errorReportReceiver.flattenToShortString());
313                    }
314                    pw.println();
315        }
316        if (activities.size() > 0) {
317            pw.print(prefix); pw.println("Activities:");
318            for (int i=0; i<activities.size(); i++) {
319                pw.print(prefix); pw.print("  - "); pw.println(activities.get(i));
320            }
321        }
322        if (services.size() > 0) {
323            pw.print(prefix); pw.println("Services:");
324            for (int i=0; i<services.size(); i++) {
325                pw.print(prefix); pw.print("  - "); pw.println(services.valueAt(i));
326            }
327        }
328        if (executingServices.size() > 0) {
329            pw.print(prefix); pw.print("Executing Services (fg=");
330            pw.print(execServicesFg); pw.println(")");
331            for (int i=0; i<executingServices.size(); i++) {
332                pw.print(prefix); pw.print("  - "); pw.println(executingServices.valueAt(i));
333            }
334        }
335        if (connections.size() > 0) {
336            pw.print(prefix); pw.println("Connections:");
337            for (int i=0; i<connections.size(); i++) {
338                pw.print(prefix); pw.print("  - "); pw.println(connections.valueAt(i));
339            }
340        }
341        if (pubProviders.size() > 0) {
342            pw.print(prefix); pw.println("Published Providers:");
343            for (int i=0; i<pubProviders.size(); i++) {
344                pw.print(prefix); pw.print("  - "); pw.println(pubProviders.keyAt(i));
345                pw.print(prefix); pw.print("    -> "); pw.println(pubProviders.valueAt(i));
346            }
347        }
348        if (conProviders.size() > 0) {
349            pw.print(prefix); pw.println("Connected Providers:");
350            for (int i=0; i<conProviders.size(); i++) {
351                pw.print(prefix); pw.print("  - "); pw.println(conProviders.get(i).toShortString());
352            }
353        }
354        if (curReceiver != null) {
355            pw.print(prefix); pw.print("curReceiver="); pw.println(curReceiver);
356        }
357        if (receivers.size() > 0) {
358            pw.print(prefix); pw.println("Receivers:");
359            for (int i=0; i<receivers.size(); i++) {
360                pw.print(prefix); pw.print("  - "); pw.println(receivers.valueAt(i));
361            }
362        }
363    }
364
365    ProcessRecord(BatteryStatsImpl _batteryStats, ApplicationInfo _info,
366            String _processName, int _uid) {
367        mBatteryStats = _batteryStats;
368        info = _info;
369        isolated = _info.uid != _uid;
370        uid = _uid;
371        userId = UserHandle.getUserId(_uid);
372        processName = _processName;
373        pkgList.put(_info.packageName, null);
374        maxAdj = ProcessList.UNKNOWN_ADJ;
375        curRawAdj = setRawAdj = -100;
376        curAdj = setAdj = -100;
377        persistent = false;
378        removed = false;
379        lastStateTime = lastPssTime = nextPssTime = SystemClock.uptimeMillis();
380    }
381
382    public void setPid(int _pid) {
383        pid = _pid;
384        shortStringName = null;
385        stringName = null;
386    }
387
388    public void makeActive(IApplicationThread _thread, ProcessStatsService tracker) {
389        if (thread == null) {
390            final ProcessStats.ProcessState origBase = baseProcessTracker;
391            if (origBase != null) {
392                origBase.setState(ProcessStats.STATE_NOTHING,
393                        tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
394                origBase.makeInactive();
395            }
396            baseProcessTracker = tracker.getProcessStateLocked(info.packageName, info.uid,
397                    info.versionCode, processName);
398            baseProcessTracker.makeActive();
399            for (int i=0; i<pkgList.size(); i++) {
400                ProcessStats.ProcessState ps = pkgList.valueAt(i);
401                if (ps != null && ps != origBase) {
402                    ps.makeInactive();
403                }
404                ps = tracker.getProcessStateLocked(pkgList.keyAt(i), info.uid,
405                        info.versionCode, processName);
406                if (ps != baseProcessTracker) {
407                    ps.makeActive();
408                }
409                pkgList.setValueAt(i, ps);
410            }
411        }
412        thread = _thread;
413    }
414
415    public void makeInactive(ProcessStatsService tracker) {
416        thread = null;
417        final ProcessStats.ProcessState origBase = baseProcessTracker;
418        if (origBase != null) {
419            if (origBase != null) {
420                origBase.setState(ProcessStats.STATE_NOTHING,
421                        tracker.getMemFactorLocked(), SystemClock.uptimeMillis(), pkgList);
422                origBase.makeInactive();
423            }
424            baseProcessTracker = null;
425            for (int i=0; i<pkgList.size(); i++) {
426                ProcessStats.ProcessState ps = pkgList.valueAt(i);
427                if (ps != null && ps != origBase) {
428                    ps.makeInactive();
429                }
430                pkgList.setValueAt(i, null);
431            }
432        }
433    }
434
435    /**
436     * This method returns true if any of the activities within the process record are interesting
437     * to the user. See HistoryRecord.isInterestingToUserLocked()
438     */
439    public boolean isInterestingToUserLocked() {
440        final int size = activities.size();
441        for (int i = 0 ; i < size ; i++) {
442            ActivityRecord r = activities.get(i);
443            if (r.isInterestingToUserLocked()) {
444                return true;
445            }
446        }
447        return false;
448    }
449
450    public void stopFreezingAllLocked() {
451        int i = activities.size();
452        while (i > 0) {
453            i--;
454            activities.get(i).stopFreezingScreenLocked(true);
455        }
456    }
457
458    public void unlinkDeathRecipient() {
459        if (deathRecipient != null && thread != null) {
460            thread.asBinder().unlinkToDeath(deathRecipient, 0);
461        }
462        deathRecipient = null;
463    }
464
465    void updateHasAboveClientLocked() {
466        hasAboveClient = false;
467        for (int i=connections.size()-1; i>=0; i--) {
468            ConnectionRecord cr = connections.valueAt(i);
469            if ((cr.flags&Context.BIND_ABOVE_CLIENT) != 0) {
470                hasAboveClient = true;
471                break;
472            }
473        }
474    }
475
476    int modifyRawOomAdj(int adj) {
477        if (hasAboveClient) {
478            // If this process has bound to any services with BIND_ABOVE_CLIENT,
479            // then we need to drop its adjustment to be lower than the service's
480            // in order to honor the request.  We want to drop it by one adjustment
481            // level...  but there is special meaning applied to various levels so
482            // we will skip some of them.
483            if (adj < ProcessList.FOREGROUND_APP_ADJ) {
484                // System process will not get dropped, ever
485            } else if (adj < ProcessList.VISIBLE_APP_ADJ) {
486                adj = ProcessList.VISIBLE_APP_ADJ;
487            } else if (adj < ProcessList.PERCEPTIBLE_APP_ADJ) {
488                adj = ProcessList.PERCEPTIBLE_APP_ADJ;
489            } else if (adj < ProcessList.CACHED_APP_MIN_ADJ) {
490                adj = ProcessList.CACHED_APP_MIN_ADJ;
491            } else if (adj < ProcessList.CACHED_APP_MAX_ADJ) {
492                adj++;
493            }
494        }
495        return adj;
496    }
497
498    public String toShortString() {
499        if (shortStringName != null) {
500            return shortStringName;
501        }
502        StringBuilder sb = new StringBuilder(128);
503        toShortString(sb);
504        return shortStringName = sb.toString();
505    }
506
507    void toShortString(StringBuilder sb) {
508        sb.append(pid);
509        sb.append(':');
510        sb.append(processName);
511        sb.append('/');
512        if (info.uid < Process.FIRST_APPLICATION_UID) {
513            sb.append(uid);
514        } else {
515            sb.append('u');
516            sb.append(userId);
517            int appId = UserHandle.getAppId(info.uid);
518            if (appId >= Process.FIRST_APPLICATION_UID) {
519                sb.append('a');
520                sb.append(appId - Process.FIRST_APPLICATION_UID);
521            } else {
522                sb.append('s');
523                sb.append(appId);
524            }
525            if (uid != info.uid) {
526                sb.append('i');
527                sb.append(UserHandle.getAppId(uid) - Process.FIRST_ISOLATED_UID);
528            }
529        }
530    }
531
532    public String toString() {
533        if (stringName != null) {
534            return stringName;
535        }
536        StringBuilder sb = new StringBuilder(128);
537        sb.append("ProcessRecord{");
538        sb.append(Integer.toHexString(System.identityHashCode(this)));
539        sb.append(' ');
540        toShortString(sb);
541        sb.append('}');
542        return stringName = sb.toString();
543    }
544
545    public String makeAdjReason() {
546        if (adjSource != null || adjTarget != null) {
547            StringBuilder sb = new StringBuilder(128);
548            sb.append(' ');
549            if (adjTarget instanceof ComponentName) {
550                sb.append(((ComponentName)adjTarget).flattenToShortString());
551            } else if (adjTarget != null) {
552                sb.append(adjTarget.toString());
553            } else {
554                sb.append("{null}");
555            }
556            sb.append("<=");
557            if (adjSource instanceof ProcessRecord) {
558                sb.append("Proc{");
559                sb.append(((ProcessRecord)adjSource).toShortString());
560                sb.append("}");
561            } else if (adjSource != null) {
562                sb.append(adjSource.toString());
563            } else {
564                sb.append("{null}");
565            }
566            return sb.toString();
567        }
568        return null;
569    }
570
571    /*
572     *  Return true if package has been added false if not
573     */
574    public boolean addPackage(String pkg, ProcessStatsService tracker) {
575        if (!pkgList.containsKey(pkg)) {
576            if (baseProcessTracker != null) {
577                ProcessStats.ProcessState state = tracker.getProcessStateLocked(
578                        pkg, info.uid, info.versionCode, processName);
579                pkgList.put(pkg, state);
580                if (state != baseProcessTracker) {
581                    state.makeActive();
582                }
583            } else {
584                pkgList.put(pkg, null);
585            }
586            return true;
587        }
588        return false;
589    }
590
591    public int getSetAdjWithServices() {
592        if (setAdj >= ProcessList.CACHED_APP_MIN_ADJ) {
593            if (hasStartedServices) {
594                return ProcessList.SERVICE_B_ADJ;
595            }
596        }
597        return setAdj;
598    }
599
600    public void forceProcessStateUpTo(int newState) {
601        if (repProcState > newState) {
602            curProcState = repProcState = newState;
603        }
604    }
605
606    /*
607     *  Delete all packages from list except the package indicated in info
608     */
609    public void resetPackageList(ProcessStatsService tracker) {
610        final int N = pkgList.size();
611        if (baseProcessTracker != null) {
612            long now = SystemClock.uptimeMillis();
613            baseProcessTracker.setState(ProcessStats.STATE_NOTHING,
614                    tracker.getMemFactorLocked(), now, pkgList);
615            if (N != 1) {
616                for (int i=0; i<N; i++) {
617                    ProcessStats.ProcessState ps = pkgList.valueAt(i);
618                    if (ps != null && ps != baseProcessTracker) {
619                        ps.makeInactive();
620                    }
621
622                }
623                pkgList.clear();
624                ProcessStats.ProcessState ps = tracker.getProcessStateLocked(
625                        info.packageName, info.uid, info.versionCode, processName);
626                pkgList.put(info.packageName, ps);
627                if (ps != baseProcessTracker) {
628                    ps.makeActive();
629                }
630            }
631        } else if (N != 1) {
632            pkgList.clear();
633            pkgList.put(info.packageName, null);
634        }
635    }
636
637    public String[] getPackageList() {
638        int size = pkgList.size();
639        if (size == 0) {
640            return null;
641        }
642        String list[] = new String[size];
643        for (int i=0; i<pkgList.size(); i++) {
644            list[i] = pkgList.keyAt(i);
645        }
646        return list;
647    }
648}
649