ActivityRecord.java revision 846318a3250fa95f47a9decfbffb05a31dbd0006
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.os.Trace;
20import com.android.internal.R.styleable;
21import com.android.internal.app.ResolverActivity;
22import com.android.server.AttributeCache;
23import com.android.server.am.ActivityStack.ActivityState;
24import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
25
26import android.app.ActivityOptions;
27import android.app.ResultInfo;
28import android.content.ComponentName;
29import android.content.Intent;
30import android.content.pm.ActivityInfo;
31import android.content.pm.ApplicationInfo;
32import android.content.res.CompatibilityInfo;
33import android.content.res.Configuration;
34import android.graphics.Bitmap;
35import android.graphics.Rect;
36import android.os.Build;
37import android.os.Bundle;
38import android.os.IBinder;
39import android.os.Message;
40import android.os.Process;
41import android.os.RemoteException;
42import android.os.SystemClock;
43import android.os.UserHandle;
44import android.util.EventLog;
45import android.util.Log;
46import android.util.Slog;
47import android.util.TimeUtils;
48import android.view.IApplicationToken;
49import android.view.WindowManager;
50
51import java.io.PrintWriter;
52import java.lang.ref.WeakReference;
53import java.util.ArrayList;
54import java.util.HashSet;
55
56/**
57 * An entry in the history stack, representing an activity.
58 */
59final class ActivityRecord {
60    static final String TAG = ActivityManagerService.TAG;
61    static final boolean DEBUG_SAVED_STATE = ActivityStackSupervisor.DEBUG_SAVED_STATE;
62    final public static String RECENTS_PACKAGE_NAME = "com.android.systemui.recent";
63
64    final ActivityManagerService service; // owner
65    final IApplicationToken.Stub appToken; // window manager token
66    final ActivityInfo info; // all about me
67    final int launchedFromUid; // always the uid who started the activity.
68    final String launchedFromPackage; // always the package who started the activity.
69    final int userId;          // Which user is this running for?
70    final Intent intent;    // the original intent that generated us
71    final ComponentName realActivity;  // the intent component, or target of an alias.
72    final String shortComponentName; // the short component name of the intent
73    final String resolvedType; // as per original caller;
74    final String packageName; // the package implementing intent's component
75    final String processName; // process where this component wants to run
76    final String taskAffinity; // as per ActivityInfo.taskAffinity
77    final boolean stateNotNeeded; // As per ActivityInfo.flags
78    boolean fullscreen; // covers the full screen?
79    final boolean noDisplay;  // activity is not displayed?
80    final boolean componentSpecified;  // did caller specifiy an explicit component?
81
82    static final int APPLICATION_ACTIVITY_TYPE = 0;
83    static final int HOME_ACTIVITY_TYPE = 1;
84    static final int RECENTS_ACTIVITY_TYPE = 2;
85    int mActivityType;
86
87    final String baseDir;   // where activity source (resources etc) located
88    final String resDir;   // where public activity source (public resources etc) located
89    final String dataDir;   // where activity data should go
90    CharSequence nonLocalizedLabel;  // the label information from the package mgr.
91    int labelRes;           // the label information from the package mgr.
92    int icon;               // resource identifier of activity's icon.
93    int logo;               // resource identifier of activity's logo.
94    int theme;              // resource identifier of activity's theme.
95    int realTheme;          // actual theme resource we will use, never 0.
96    int windowFlags;        // custom window flags for preview window.
97    TaskRecord task;        // the task this is in.
98    ThumbnailHolder thumbHolder; // where our thumbnails should go.
99    long displayStartTime;  // when we started launching this activity
100    long fullyDrawnStartTime; // when we started launching this activity
101    long startTime;         // last time this activity was started
102    long lastVisibleTime;   // last time this activity became visible
103    long cpuTimeAtResume;   // the cpu time of host process at the time of resuming activity
104    long pauseTime;         // last time we started pausing the activity
105    long launchTickTime;    // base time for launch tick messages
106    Configuration configuration; // configuration activity was last running in
107    CompatibilityInfo compat;// last used compatibility mode
108    ActivityRecord resultTo; // who started this entry, so will get our reply
109    final String resultWho; // additional identifier for use by resultTo.
110    final int requestCode;  // code given by requester (resultTo)
111    ArrayList<ResultInfo> results; // pending ActivityResult objs we have received
112    HashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this act
113    ArrayList<Intent> newIntents; // any pending new intents for single-top mode
114    ActivityOptions pendingOptions; // most recently given options
115    HashSet<ConnectionRecord> connections; // All ConnectionRecord we hold
116    UriPermissionOwner uriPermissions; // current special URI access perms.
117    ProcessRecord app;      // if non-null, hosting application
118    ActivityState state;    // current state we are in
119    Bundle  icicle;         // last saved activity state
120    boolean frontOfTask;    // is this the root activity of its task?
121    boolean launchFailed;   // set if a launched failed, to abort on 2nd try
122    boolean haveState;      // have we gotten the last activity state?
123    boolean stopped;        // is activity pause finished?
124    boolean delayedResume;  // not yet resumed because of stopped app switches?
125    boolean finishing;      // activity in pending finish list?
126    boolean configDestroy;  // need to destroy due to config change?
127    int configChangeFlags;  // which config values have changed
128    boolean keysPaused;     // has key dispatching been paused for it?
129    int launchMode;         // the launch mode activity attribute.
130    boolean visible;        // does this activity's window need to be shown?
131    boolean sleeping;       // have we told the activity to sleep?
132    boolean waitingVisible; // true if waiting for a new act to become vis
133    boolean nowVisible;     // is this activity's window visible?
134    boolean thumbnailNeeded;// has someone requested a thumbnail?
135    boolean idle;           // has the activity gone idle?
136    boolean hasBeenLaunched;// has this activity ever been launched?
137    boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.
138    boolean immersive;      // immersive mode (don't interrupt if possible)
139    boolean forceNewConfig; // force re-create with new config next time
140    int launchCount;        // count of launches since last state
141    long lastLaunchTime;    // time of last lauch of this activity
142    ArrayList<ActivityContainer> mChildContainers = new ArrayList<ActivityContainer>();
143
144    String stringName;      // for caching of toString().
145
146    private boolean inHistory;  // are we in the history stack?
147    final ActivityStackSupervisor mStackSupervisor;
148    boolean mStartingWindowShown = false;
149    ActivityContainer mInitialActivityContainer;
150
151    String activityLabel;
152    Bitmap activityIcon;
153
154    void dump(PrintWriter pw, String prefix) {
155        final long now = SystemClock.uptimeMillis();
156        pw.print(prefix); pw.print("packageName="); pw.print(packageName);
157                pw.print(" processName="); pw.println(processName);
158        pw.print(prefix); pw.print("launchedFromUid="); pw.print(launchedFromUid);
159                pw.print(" launchedFromPackage="); pw.print(launchedFromPackage);
160                pw.print(" userId="); pw.println(userId);
161        pw.print(prefix); pw.print("app="); pw.println(app);
162        pw.print(prefix); pw.println(intent.toInsecureStringWithClip());
163        pw.print(prefix); pw.print("frontOfTask="); pw.print(frontOfTask);
164                pw.print(" task="); pw.println(task);
165        pw.print(prefix); pw.print("taskAffinity="); pw.println(taskAffinity);
166        pw.print(prefix); pw.print("realActivity=");
167                pw.println(realActivity.flattenToShortString());
168        pw.print(prefix); pw.print("baseDir="); pw.println(baseDir);
169        if (!resDir.equals(baseDir)) {
170            pw.print(prefix); pw.print("resDir="); pw.println(resDir);
171        }
172        pw.print(prefix); pw.print("dataDir="); pw.println(dataDir);
173        pw.print(prefix); pw.print("stateNotNeeded="); pw.print(stateNotNeeded);
174                pw.print(" componentSpecified="); pw.print(componentSpecified);
175                pw.print(" mActivityType="); pw.println(mActivityType);
176        pw.print(prefix); pw.print("compat="); pw.print(compat);
177                pw.print(" labelRes=0x"); pw.print(Integer.toHexString(labelRes));
178                pw.print(" icon=0x"); pw.print(Integer.toHexString(icon));
179                pw.print(" theme=0x"); pw.println(Integer.toHexString(theme));
180        pw.print(prefix); pw.print("config="); pw.println(configuration);
181        if (resultTo != null || resultWho != null) {
182            pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
183                    pw.print(" resultWho="); pw.print(resultWho);
184                    pw.print(" resultCode="); pw.println(requestCode);
185        }
186        if (results != null) {
187            pw.print(prefix); pw.print("results="); pw.println(results);
188        }
189        if (pendingResults != null && pendingResults.size() > 0) {
190            pw.print(prefix); pw.println("Pending Results:");
191            for (WeakReference<PendingIntentRecord> wpir : pendingResults) {
192                PendingIntentRecord pir = wpir != null ? wpir.get() : null;
193                pw.print(prefix); pw.print("  - ");
194                if (pir == null) {
195                    pw.println("null");
196                } else {
197                    pw.println(pir);
198                    pir.dump(pw, prefix + "    ");
199                }
200            }
201        }
202        if (newIntents != null && newIntents.size() > 0) {
203            pw.print(prefix); pw.println("Pending New Intents:");
204            for (int i=0; i<newIntents.size(); i++) {
205                Intent intent = newIntents.get(i);
206                pw.print(prefix); pw.print("  - ");
207                if (intent == null) {
208                    pw.println("null");
209                } else {
210                    pw.println(intent.toShortString(false, true, false, true));
211                }
212            }
213        }
214        if (pendingOptions != null) {
215            pw.print(prefix); pw.print("pendingOptions="); pw.println(pendingOptions);
216        }
217        if (uriPermissions != null) {
218            uriPermissions.dump(pw, prefix);
219        }
220        pw.print(prefix); pw.print("launchFailed="); pw.print(launchFailed);
221                pw.print(" launchCount="); pw.print(launchCount);
222                pw.print(" lastLaunchTime=");
223                if (lastLaunchTime == 0) pw.print("0");
224                else TimeUtils.formatDuration(lastLaunchTime, now, pw);
225                pw.println();
226        pw.print(prefix); pw.print("haveState="); pw.print(haveState);
227                pw.print(" icicle="); pw.println(icicle);
228        pw.print(prefix); pw.print("state="); pw.print(state);
229                pw.print(" stopped="); pw.print(stopped);
230                pw.print(" delayedResume="); pw.print(delayedResume);
231                pw.print(" finishing="); pw.println(finishing);
232        pw.print(prefix); pw.print("keysPaused="); pw.print(keysPaused);
233                pw.print(" inHistory="); pw.print(inHistory);
234                pw.print(" visible="); pw.print(visible);
235                pw.print(" sleeping="); pw.print(sleeping);
236                pw.print(" idle="); pw.println(idle);
237        pw.print(prefix); pw.print("fullscreen="); pw.print(fullscreen);
238                pw.print(" noDisplay="); pw.print(noDisplay);
239                pw.print(" immersive="); pw.print(immersive);
240                pw.print(" launchMode="); pw.println(launchMode);
241        pw.print(prefix); pw.print("frozenBeforeDestroy="); pw.print(frozenBeforeDestroy);
242                pw.print(" thumbnailNeeded="); pw.print(thumbnailNeeded);
243                pw.print(" forceNewConfig="); pw.println(forceNewConfig);
244        pw.print(prefix); pw.print("mActivityType=");
245                pw.println(activityTypeToString(mActivityType));
246        pw.print(prefix); pw.print("thumbHolder: ");
247                pw.print(Integer.toHexString(System.identityHashCode(thumbHolder)));
248                if (thumbHolder != null) {
249                    pw.print(" bm="); pw.print(thumbHolder.lastThumbnail);
250                    pw.print(" desc="); pw.print(thumbHolder.lastDescription);
251                }
252                pw.println();
253        if (displayStartTime != 0 || startTime != 0) {
254            pw.print(prefix); pw.print("displayStartTime=");
255                    if (displayStartTime == 0) pw.print("0");
256                    else TimeUtils.formatDuration(displayStartTime, now, pw);
257                    pw.print(" startTime=");
258                    if (startTime == 0) pw.print("0");
259                    else TimeUtils.formatDuration(startTime, now, pw);
260                    pw.println();
261        }
262        if (lastVisibleTime != 0 || waitingVisible || nowVisible) {
263            pw.print(prefix); pw.print("waitingVisible="); pw.print(waitingVisible);
264                    pw.print(" nowVisible="); pw.print(nowVisible);
265                    pw.print(" lastVisibleTime=");
266                    if (lastVisibleTime == 0) pw.print("0");
267                    else TimeUtils.formatDuration(lastVisibleTime, now, pw);
268                    pw.println();
269        }
270        if (configDestroy || configChangeFlags != 0) {
271            pw.print(prefix); pw.print("configDestroy="); pw.print(configDestroy);
272                    pw.print(" configChangeFlags=");
273                    pw.println(Integer.toHexString(configChangeFlags));
274        }
275        if (connections != null) {
276            pw.print(prefix); pw.print("connections="); pw.println(connections);
277        }
278    }
279
280    static class Token extends IApplicationToken.Stub {
281        final WeakReference<ActivityRecord> weakActivity;
282
283        Token(ActivityRecord activity) {
284            weakActivity = new WeakReference<ActivityRecord>(activity);
285        }
286
287        @Override public void windowsDrawn() {
288            ActivityRecord activity = weakActivity.get();
289            if (activity != null) {
290                activity.windowsDrawn();
291            }
292        }
293
294        @Override public void windowsVisible() {
295            ActivityRecord activity = weakActivity.get();
296            if (activity != null) {
297                activity.windowsVisible();
298            }
299        }
300
301        @Override public void windowsGone() {
302            ActivityRecord activity = weakActivity.get();
303            if (activity != null) {
304                activity.windowsGone();
305            }
306        }
307
308        @Override public boolean keyDispatchingTimedOut(String reason) {
309            ActivityRecord activity = weakActivity.get();
310            return activity != null && activity.keyDispatchingTimedOut(reason);
311        }
312
313        @Override public long getKeyDispatchingTimeout() {
314            ActivityRecord activity = weakActivity.get();
315            if (activity != null) {
316                return activity.getKeyDispatchingTimeout();
317            }
318            return 0;
319        }
320
321        @Override
322        public String toString() {
323            StringBuilder sb = new StringBuilder(128);
324            sb.append("Token{");
325            sb.append(Integer.toHexString(System.identityHashCode(this)));
326            sb.append(' ');
327            sb.append(weakActivity.get());
328            sb.append('}');
329            return sb.toString();
330        }
331    }
332
333    static ActivityRecord forToken(IBinder token) {
334        try {
335            return token != null ? ((Token)token).weakActivity.get() : null;
336        } catch (ClassCastException e) {
337            Slog.w(ActivityManagerService.TAG, "Bad activity token: " + token, e);
338            return null;
339        }
340    }
341
342    boolean isNotResolverActivity() {
343        return !ResolverActivity.class.getName().equals(realActivity.getClassName());
344    }
345
346    ActivityRecord(ActivityManagerService _service, ProcessRecord _caller,
347            int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
348            ActivityInfo aInfo, Configuration _configuration,
349            ActivityRecord _resultTo, String _resultWho, int _reqCode,
350            boolean _componentSpecified, ActivityStackSupervisor supervisor,
351            ActivityContainer container) {
352        service = _service;
353        appToken = new Token(this);
354        info = aInfo;
355        launchedFromUid = _launchedFromUid;
356        launchedFromPackage = _launchedFromPackage;
357        userId = UserHandle.getUserId(aInfo.applicationInfo.uid);
358        intent = _intent;
359        shortComponentName = _intent.getComponent().flattenToShortString();
360        resolvedType = _resolvedType;
361        componentSpecified = _componentSpecified;
362        configuration = _configuration;
363        resultTo = _resultTo;
364        resultWho = _resultWho;
365        requestCode = _reqCode;
366        state = ActivityState.INITIALIZING;
367        frontOfTask = false;
368        launchFailed = false;
369        stopped = false;
370        delayedResume = false;
371        finishing = false;
372        configDestroy = false;
373        keysPaused = false;
374        inHistory = false;
375        visible = true;
376        waitingVisible = false;
377        nowVisible = false;
378        thumbnailNeeded = false;
379        idle = false;
380        hasBeenLaunched = false;
381        mStackSupervisor = supervisor;
382        mInitialActivityContainer = container;
383
384        // This starts out true, since the initial state of an activity
385        // is that we have everything, and we shouldn't never consider it
386        // lacking in state to be removed if it dies.
387        haveState = true;
388
389        if (aInfo != null) {
390            if (aInfo.targetActivity == null
391                    || aInfo.launchMode == ActivityInfo.LAUNCH_MULTIPLE
392                    || aInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
393                realActivity = _intent.getComponent();
394            } else {
395                realActivity = new ComponentName(aInfo.packageName,
396                        aInfo.targetActivity);
397            }
398            taskAffinity = aInfo.taskAffinity;
399            stateNotNeeded = (aInfo.flags&
400                    ActivityInfo.FLAG_STATE_NOT_NEEDED) != 0;
401            baseDir = aInfo.applicationInfo.sourceDir;
402            resDir = aInfo.applicationInfo.publicSourceDir;
403            dataDir = aInfo.applicationInfo.dataDir;
404            nonLocalizedLabel = aInfo.nonLocalizedLabel;
405            labelRes = aInfo.labelRes;
406            if (nonLocalizedLabel == null && labelRes == 0) {
407                ApplicationInfo app = aInfo.applicationInfo;
408                nonLocalizedLabel = app.nonLocalizedLabel;
409                labelRes = app.labelRes;
410            }
411            icon = aInfo.getIconResource();
412            logo = aInfo.getLogoResource();
413            theme = aInfo.getThemeResource();
414            realTheme = theme;
415            if (realTheme == 0) {
416                realTheme = aInfo.applicationInfo.targetSdkVersion
417                        < Build.VERSION_CODES.HONEYCOMB
418                        ? android.R.style.Theme
419                        : android.R.style.Theme_Holo;
420            }
421            if ((aInfo.flags&ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
422                windowFlags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
423            }
424            if ((aInfo.flags&ActivityInfo.FLAG_MULTIPROCESS) != 0
425                    && _caller != null
426                    && (aInfo.applicationInfo.uid == Process.SYSTEM_UID
427                            || aInfo.applicationInfo.uid == _caller.info.uid)) {
428                processName = _caller.processName;
429            } else {
430                processName = aInfo.processName;
431            }
432
433            if (intent != null && (aInfo.flags & ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS) != 0) {
434                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
435            }
436
437            packageName = aInfo.applicationInfo.packageName;
438            launchMode = aInfo.launchMode;
439
440            AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
441                    realTheme, com.android.internal.R.styleable.Window, userId);
442            fullscreen = ent != null && !ent.array.getBoolean(
443                    com.android.internal.R.styleable.Window_windowIsFloating, false)
444                    && !ent.array.getBoolean(
445                    com.android.internal.R.styleable.Window_windowIsTranslucent, false);
446            noDisplay = ent != null && ent.array.getBoolean(
447                    com.android.internal.R.styleable.Window_windowNoDisplay, false);
448
449            if ((!_componentSpecified || _launchedFromUid == Process.myUid()
450                    || _launchedFromUid == 0) &&
451                    Intent.ACTION_MAIN.equals(_intent.getAction()) &&
452                    _intent.hasCategory(Intent.CATEGORY_HOME) &&
453                    _intent.getCategories().size() == 1 &&
454                    _intent.getData() == null &&
455                    _intent.getType() == null &&
456                    (intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
457                    isNotResolverActivity()) {
458                // This sure looks like a home activity!
459                mActivityType = HOME_ACTIVITY_TYPE;
460            } else if (realActivity.getClassName().contains(RECENTS_PACKAGE_NAME)) {
461                mActivityType = RECENTS_ACTIVITY_TYPE;
462            } else {
463                mActivityType = APPLICATION_ACTIVITY_TYPE;
464            }
465
466            immersive = (aInfo.flags & ActivityInfo.FLAG_IMMERSIVE) != 0;
467        } else {
468            realActivity = null;
469            taskAffinity = null;
470            stateNotNeeded = false;
471            baseDir = null;
472            resDir = null;
473            dataDir = null;
474            processName = null;
475            packageName = null;
476            fullscreen = true;
477            noDisplay = false;
478            mActivityType = APPLICATION_ACTIVITY_TYPE;
479            immersive = false;
480        }
481    }
482
483    void setTask(TaskRecord newTask, ThumbnailHolder newThumbHolder, boolean isRoot) {
484        if (task != null && task.removeActivity(this)) {
485            if (task != newTask) {
486                task.stack.removeTask(task);
487            } else {
488                Slog.d(TAG, "!!! REMOVE THIS LOG !!! setTask: nearly removed stack=" +
489                        (newTask == null ? null : newTask.stack));
490            }
491        }
492        if (inHistory && !finishing) {
493            if (task != null) {
494                task.numActivities--;
495            }
496            if (newTask != null) {
497                newTask.numActivities++;
498            }
499        }
500        if (newThumbHolder == null) {
501            newThumbHolder = newTask;
502        }
503        task = newTask;
504        if (!isRoot && (intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
505            // This is the start of a new sub-task.
506            if (thumbHolder == null) {
507                thumbHolder = new ThumbnailHolder();
508            }
509        } else {
510            thumbHolder = newThumbHolder;
511        }
512    }
513
514    boolean changeWindowTranslucency(boolean toOpaque) {
515        if (fullscreen == toOpaque) {
516            return false;
517        }
518
519        // Keep track of the number of fullscreen activities in this task.
520        task.numFullscreen += toOpaque ? +1 : -1;
521
522        fullscreen = toOpaque;
523        return true;
524    }
525
526    void putInHistory() {
527        if (!inHistory) {
528            inHistory = true;
529            if (task != null && !finishing) {
530                task.numActivities++;
531            }
532        }
533    }
534
535    void takeFromHistory() {
536        if (inHistory) {
537            inHistory = false;
538            if (task != null && !finishing) {
539                task.numActivities--;
540                task = null;
541            }
542            clearOptionsLocked();
543        }
544    }
545
546    boolean isInHistory() {
547        return inHistory;
548    }
549
550    boolean isHomeActivity() {
551        return mActivityType == HOME_ACTIVITY_TYPE;
552    }
553
554    boolean isRecentsActivity() {
555        return mActivityType == RECENTS_ACTIVITY_TYPE;
556    }
557
558    boolean isApplicationActivity() {
559        return mActivityType == APPLICATION_ACTIVITY_TYPE;
560    }
561
562    void makeFinishing() {
563        if (!finishing) {
564            finishing = true;
565            if (task != null && inHistory) {
566                task.numActivities--;
567            }
568            if (stopped) {
569                clearOptionsLocked();
570            }
571        }
572    }
573
574    boolean isRootActivity() {
575        final ArrayList<ActivityRecord> activities = task.mActivities;
576        return activities.size() == 0 || this == activities.get(0);
577    }
578
579    UriPermissionOwner getUriPermissionsLocked() {
580        if (uriPermissions == null) {
581            uriPermissions = new UriPermissionOwner(service, this);
582        }
583        return uriPermissions;
584    }
585
586    void addResultLocked(ActivityRecord from, String resultWho,
587            int requestCode, int resultCode,
588            Intent resultData) {
589        ActivityResult r = new ActivityResult(from, resultWho,
590                requestCode, resultCode, resultData);
591        if (results == null) {
592            results = new ArrayList<ResultInfo>();
593        }
594        results.add(r);
595    }
596
597    void removeResultsLocked(ActivityRecord from, String resultWho,
598            int requestCode) {
599        if (results != null) {
600            for (int i=results.size()-1; i>=0; i--) {
601                ActivityResult r = (ActivityResult)results.get(i);
602                if (r.mFrom != from) continue;
603                if (r.mResultWho == null) {
604                    if (resultWho != null) continue;
605                } else {
606                    if (!r.mResultWho.equals(resultWho)) continue;
607                }
608                if (r.mRequestCode != requestCode) continue;
609
610                results.remove(i);
611            }
612        }
613    }
614
615    void addNewIntentLocked(Intent intent) {
616        if (newIntents == null) {
617            newIntents = new ArrayList<Intent>();
618        }
619        newIntents.add(intent);
620    }
621
622    /**
623     * Deliver a new Intent to an existing activity, so that its onNewIntent()
624     * method will be called at the proper time.
625     */
626    final void deliverNewIntentLocked(int callingUid, Intent intent) {
627        // The activity now gets access to the data associated with this Intent.
628        service.grantUriPermissionFromIntentLocked(callingUid, packageName,
629                intent, getUriPermissionsLocked());
630        // We want to immediately deliver the intent to the activity if
631        // it is currently the top resumed activity...  however, if the
632        // device is sleeping, then all activities are stopped, so in that
633        // case we will deliver it if this is the current top activity on its
634        // stack.
635        boolean unsent = true;
636        if ((state == ActivityState.RESUMED || (service.mSleeping
637                        && task.stack.topRunningActivityLocked(null) == this))
638                && app != null && app.thread != null) {
639            try {
640                ArrayList<Intent> ar = new ArrayList<Intent>();
641                intent = new Intent(intent);
642                ar.add(intent);
643                app.thread.scheduleNewIntent(ar, appToken);
644                unsent = false;
645            } catch (RemoteException e) {
646                Slog.w(ActivityManagerService.TAG,
647                        "Exception thrown sending new intent to " + this, e);
648            } catch (NullPointerException e) {
649                Slog.w(ActivityManagerService.TAG,
650                        "Exception thrown sending new intent to " + this, e);
651            }
652        }
653        if (unsent) {
654            addNewIntentLocked(new Intent(intent));
655        }
656    }
657
658    void updateOptionsLocked(Bundle options) {
659        if (options != null) {
660            if (pendingOptions != null) {
661                pendingOptions.abort();
662            }
663            pendingOptions = new ActivityOptions(options);
664        }
665    }
666
667    void updateOptionsLocked(ActivityOptions options) {
668        if (options != null) {
669            if (pendingOptions != null) {
670                pendingOptions.abort();
671            }
672            pendingOptions = options;
673        }
674    }
675
676    void applyOptionsLocked() {
677        if (pendingOptions != null
678                && pendingOptions.getAnimationType() != ActivityOptions.ANIM_SCENE_TRANSITION) {
679            final int animationType = pendingOptions.getAnimationType();
680            switch (animationType) {
681                case ActivityOptions.ANIM_CUSTOM:
682                    service.mWindowManager.overridePendingAppTransition(
683                            pendingOptions.getPackageName(),
684                            pendingOptions.getCustomEnterResId(),
685                            pendingOptions.getCustomExitResId(),
686                            pendingOptions.getOnAnimationStartListener());
687                    break;
688                case ActivityOptions.ANIM_SCALE_UP:
689                    service.mWindowManager.overridePendingAppTransitionScaleUp(
690                            pendingOptions.getStartX(), pendingOptions.getStartY(),
691                            pendingOptions.getStartWidth(), pendingOptions.getStartHeight());
692                    if (intent.getSourceBounds() == null) {
693                        intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
694                                pendingOptions.getStartY(),
695                                pendingOptions.getStartX()+pendingOptions.getStartWidth(),
696                                pendingOptions.getStartY()+pendingOptions.getStartHeight()));
697                    }
698                    break;
699                case ActivityOptions.ANIM_THUMBNAIL_SCALE_UP:
700                case ActivityOptions.ANIM_THUMBNAIL_SCALE_DOWN:
701                    boolean scaleUp = (animationType == ActivityOptions.ANIM_THUMBNAIL_SCALE_UP);
702                    service.mWindowManager.overridePendingAppTransitionThumb(
703                            pendingOptions.getThumbnail(),
704                            pendingOptions.getStartX(), pendingOptions.getStartY(),
705                            pendingOptions.getOnAnimationStartListener(),
706                            scaleUp);
707                    if (intent.getSourceBounds() == null) {
708                        intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
709                                pendingOptions.getStartY(),
710                                pendingOptions.getStartX()
711                                        + pendingOptions.getThumbnail().getWidth(),
712                                pendingOptions.getStartY()
713                                        + pendingOptions.getThumbnail().getHeight()));
714                    }
715                    break;
716            }
717            pendingOptions = null;
718        }
719    }
720
721    ActivityOptions getOptionsForTargetActivityLocked() {
722        return pendingOptions != null ? pendingOptions.forTargetActivity() : null;
723    }
724
725    void clearOptionsLocked() {
726        if (pendingOptions != null) {
727            pendingOptions.abort();
728            pendingOptions = null;
729        }
730    }
731
732    ActivityOptions takeOptionsLocked() {
733        ActivityOptions opts = pendingOptions;
734        pendingOptions = null;
735        return opts;
736    }
737
738    void removeUriPermissionsLocked() {
739        if (uriPermissions != null) {
740            uriPermissions.removeUriPermissionsLocked();
741            uriPermissions = null;
742        }
743    }
744
745    void pauseKeyDispatchingLocked() {
746        if (!keysPaused) {
747            keysPaused = true;
748            service.mWindowManager.pauseKeyDispatching(appToken);
749        }
750    }
751
752    void resumeKeyDispatchingLocked() {
753        if (keysPaused) {
754            keysPaused = false;
755            service.mWindowManager.resumeKeyDispatching(appToken);
756        }
757    }
758
759    void updateThumbnail(Bitmap newThumbnail, CharSequence description) {
760        if (thumbHolder != null) {
761            if (newThumbnail != null) {
762                if (ActivityManagerService.DEBUG_THUMBNAILS) Slog.i(ActivityManagerService.TAG,
763                        "Setting thumbnail of " + this + " holder " + thumbHolder
764                        + " to " + newThumbnail);
765                thumbHolder.lastThumbnail = newThumbnail;
766            }
767            thumbHolder.lastDescription = description;
768        }
769    }
770
771    void startLaunchTickingLocked() {
772        if (ActivityManagerService.IS_USER_BUILD) {
773            return;
774        }
775        if (launchTickTime == 0) {
776            launchTickTime = SystemClock.uptimeMillis();
777            continueLaunchTickingLocked();
778        }
779    }
780
781    boolean continueLaunchTickingLocked() {
782        if (launchTickTime != 0) {
783            final ActivityStack stack = task.stack;
784            Message msg = stack.mHandler.obtainMessage(ActivityStack.LAUNCH_TICK_MSG, this);
785            stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
786            stack.mHandler.sendMessageDelayed(msg, ActivityStack.LAUNCH_TICK);
787            return true;
788        }
789        return false;
790    }
791
792    void finishLaunchTickingLocked() {
793        launchTickTime = 0;
794        task.stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
795    }
796
797    // IApplicationToken
798
799    public boolean mayFreezeScreenLocked(ProcessRecord app) {
800        // Only freeze the screen if this activity is currently attached to
801        // an application, and that application is not blocked or unresponding.
802        // In any other case, we can't count on getting the screen unfrozen,
803        // so it is best to leave as-is.
804        return app != null && !app.crashing && !app.notResponding;
805    }
806
807    public void startFreezingScreenLocked(ProcessRecord app, int configChanges) {
808        if (mayFreezeScreenLocked(app)) {
809            service.mWindowManager.startAppFreezingScreen(appToken, configChanges);
810        }
811    }
812
813    public void stopFreezingScreenLocked(boolean force) {
814        if (force || frozenBeforeDestroy) {
815            frozenBeforeDestroy = false;
816            service.mWindowManager.stopAppFreezingScreen(appToken, force);
817        }
818    }
819
820    public void reportFullyDrawnLocked() {
821        final long curTime = SystemClock.uptimeMillis();
822        if (displayStartTime != 0) {
823            reportLaunchTimeLocked(curTime);
824        }
825        if (fullyDrawnStartTime != 0) {
826            final ActivityStack stack = task.stack;
827            final long thisTime = curTime - fullyDrawnStartTime;
828            final long totalTime = stack.mFullyDrawnStartTime != 0
829                    ? (curTime - stack.mFullyDrawnStartTime) : thisTime;
830            if (ActivityManagerService.SHOW_ACTIVITY_START_TIME) {
831                Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
832                EventLog.writeEvent(EventLogTags.AM_ACTIVITY_FULLY_DRAWN_TIME,
833                        userId, System.identityHashCode(this), shortComponentName,
834                        thisTime, totalTime);
835                StringBuilder sb = service.mStringBuilder;
836                sb.setLength(0);
837                sb.append("Fully drawn ");
838                sb.append(shortComponentName);
839                sb.append(": ");
840                TimeUtils.formatDuration(thisTime, sb);
841                if (thisTime != totalTime) {
842                    sb.append(" (total ");
843                    TimeUtils.formatDuration(totalTime, sb);
844                    sb.append(")");
845                }
846                Log.i(ActivityManagerService.TAG, sb.toString());
847            }
848            if (totalTime > 0) {
849                service.mUsageStatsService.noteFullyDrawnTime(realActivity, (int) totalTime);
850            }
851            fullyDrawnStartTime = 0;
852            stack.mFullyDrawnStartTime = 0;
853        }
854    }
855
856    private void reportLaunchTimeLocked(final long curTime) {
857        final ActivityStack stack = task.stack;
858        final long thisTime = curTime - displayStartTime;
859        final long totalTime = stack.mLaunchStartTime != 0
860                ? (curTime - stack.mLaunchStartTime) : thisTime;
861        if (ActivityManagerService.SHOW_ACTIVITY_START_TIME) {
862            Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching", 0);
863            EventLog.writeEvent(EventLogTags.AM_ACTIVITY_LAUNCH_TIME,
864                    userId, System.identityHashCode(this), shortComponentName,
865                    thisTime, totalTime);
866            StringBuilder sb = service.mStringBuilder;
867            sb.setLength(0);
868            sb.append("Displayed ");
869            sb.append(shortComponentName);
870            sb.append(": ");
871            TimeUtils.formatDuration(thisTime, sb);
872            if (thisTime != totalTime) {
873                sb.append(" (total ");
874                TimeUtils.formatDuration(totalTime, sb);
875                sb.append(")");
876            }
877            Log.i(ActivityManagerService.TAG, sb.toString());
878        }
879        mStackSupervisor.reportActivityLaunchedLocked(false, this, thisTime, totalTime);
880        if (totalTime > 0) {
881            service.mUsageStatsService.noteLaunchTime(realActivity, (int)totalTime);
882        }
883        displayStartTime = 0;
884        stack.mLaunchStartTime = 0;
885    }
886
887    public void windowsDrawn() {
888        synchronized(service) {
889            if (displayStartTime != 0) {
890                reportLaunchTimeLocked(SystemClock.uptimeMillis());
891            }
892            startTime = 0;
893            finishLaunchTickingLocked();
894        }
895    }
896
897    public void windowsVisible() {
898        synchronized(service) {
899            mStackSupervisor.reportActivityVisibleLocked(this);
900            if (ActivityManagerService.DEBUG_SWITCH) Log.v(
901                    ActivityManagerService.TAG, "windowsVisible(): " + this);
902            if (!nowVisible) {
903                nowVisible = true;
904                lastVisibleTime = SystemClock.uptimeMillis();
905                if (!idle) {
906                    // Instead of doing the full stop routine here, let's just
907                    // hide any activities we now can, and let them stop when
908                    // the normal idle happens.
909                    mStackSupervisor.processStoppingActivitiesLocked(false);
910                } else {
911                    // If this activity was already idle, then we now need to
912                    // make sure we perform the full stop of any activities
913                    // that are waiting to do so.  This is because we won't
914                    // do that while they are still waiting for this one to
915                    // become visible.
916                    final int N = mStackSupervisor.mWaitingVisibleActivities.size();
917                    if (N > 0) {
918                        for (int i=0; i<N; i++) {
919                            ActivityRecord r = mStackSupervisor.mWaitingVisibleActivities.get(i);
920                            r.waitingVisible = false;
921                            if (ActivityManagerService.DEBUG_SWITCH) Log.v(
922                                    ActivityManagerService.TAG,
923                                    "Was waiting for visible: " + r);
924                        }
925                        mStackSupervisor.mWaitingVisibleActivities.clear();
926                        mStackSupervisor.scheduleIdleLocked();
927                    }
928                }
929                service.scheduleAppGcsLocked();
930            }
931        }
932    }
933
934    public void windowsGone() {
935        if (ActivityManagerService.DEBUG_SWITCH) Log.v(
936                ActivityManagerService.TAG, "windowsGone(): " + this);
937        nowVisible = false;
938    }
939
940    private ActivityRecord getWaitingHistoryRecordLocked() {
941        // First find the real culprit...  if we are waiting
942        // for another app to start, then we have paused dispatching
943        // for this activity.
944        ActivityRecord r = this;
945        if (r.waitingVisible) {
946            final ActivityStack stack = mStackSupervisor.getFocusedStack();
947            // Hmmm, who might we be waiting for?
948            r = stack.mResumedActivity;
949            if (r == null) {
950                r = stack.mPausingActivity;
951            }
952            // Both of those null?  Fall back to 'this' again
953            if (r == null) {
954                r = this;
955            }
956        }
957
958        return r;
959    }
960
961    public boolean keyDispatchingTimedOut(String reason) {
962        ActivityRecord r;
963        ProcessRecord anrApp;
964        synchronized(service) {
965            r = getWaitingHistoryRecordLocked();
966            anrApp = r != null ? r.app : null;
967        }
968        return service.inputDispatchingTimedOut(anrApp, r, this, false, reason);
969    }
970
971    /** Returns the key dispatching timeout for this application token. */
972    public long getKeyDispatchingTimeout() {
973        synchronized(service) {
974            ActivityRecord r = getWaitingHistoryRecordLocked();
975            return ActivityManagerService.getInputDispatchingTimeoutLocked(r);
976        }
977    }
978
979    /**
980     * This method will return true if the activity is either visible, is becoming visible, is
981     * currently pausing, or is resumed.
982     */
983    public boolean isInterestingToUserLocked() {
984        return visible || nowVisible || state == ActivityState.PAUSING ||
985                state == ActivityState.RESUMED;
986    }
987
988    public void setSleeping(boolean _sleeping) {
989        if (sleeping == _sleeping) {
990            return;
991        }
992        if (app != null && app.thread != null) {
993            try {
994                app.thread.scheduleSleeping(appToken, _sleeping);
995                if (_sleeping && !mStackSupervisor.mGoingToSleepActivities.contains(this)) {
996                    mStackSupervisor.mGoingToSleepActivities.add(this);
997                }
998                sleeping = _sleeping;
999            } catch (RemoteException e) {
1000                Slog.w(TAG, "Exception thrown when sleeping: " + intent.getComponent(), e);
1001            }
1002        }
1003    }
1004
1005    static void activityResumedLocked(IBinder token) {
1006        final ActivityRecord r = ActivityRecord.forToken(token);
1007        if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1008        r.icicle = null;
1009        r.haveState = false;
1010    }
1011
1012    static int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
1013        final ActivityRecord r = ActivityRecord.forToken(token);
1014        if (r == null) {
1015            return -1;
1016        }
1017        final TaskRecord task = r.task;
1018        switch (task.mActivities.indexOf(r)) {
1019            case -1: return -1;
1020            case 0: return task.taskId;
1021            default: return onlyRoot ? -1 : task.taskId;
1022        }
1023    }
1024
1025    static ActivityRecord isInStackLocked(IBinder token) {
1026        final ActivityRecord r = ActivityRecord.forToken(token);
1027        if (r != null) {
1028            return r.task.stack.isInStackLocked(token);
1029        }
1030        return null;
1031    }
1032
1033    static ActivityStack getStackLocked(IBinder token) {
1034        final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1035        if (r != null) {
1036            return r.task.stack;
1037        }
1038        return null;
1039    }
1040
1041    private String activityTypeToString(int type) {
1042        switch (type) {
1043            case APPLICATION_ACTIVITY_TYPE: return "APPLICATION_ACTIVITY_TYPE";
1044            case HOME_ACTIVITY_TYPE: return "HOME_ACTIVITY_TYPE";
1045            case RECENTS_ACTIVITY_TYPE: return "RECENTS_ACTIVITY_TYPE";
1046            default: return Integer.toString(type);
1047        }
1048    }
1049
1050    @Override
1051    public String toString() {
1052        if (stringName != null) {
1053            return stringName + " t" + (task == null ? -1 : task.taskId) +
1054                    (finishing ? " f}" : "}");
1055        }
1056        StringBuilder sb = new StringBuilder(128);
1057        sb.append("ActivityRecord{");
1058        sb.append(Integer.toHexString(System.identityHashCode(this)));
1059        sb.append(" u");
1060        sb.append(userId);
1061        sb.append(' ');
1062        sb.append(intent.getComponent().flattenToShortString());
1063        stringName = sb.toString();
1064        return toString();
1065    }
1066}
1067