ActivityRecord.java revision 1affbbc5932231d5a1fa4563ef0623b4eaaa9cdd
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 static android.app.ActivityManager.StackId;
20import static android.app.ActivityManager.StackId.FREEFORM_WORKSPACE_STACK_ID;
21import static android.app.ActivityManager.StackId.PINNED_STACK_ID;
22import static android.content.pm.ActivityInfo.RESIZE_MODE_CROP_WINDOWS;
23import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
24import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
25import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
26import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_CONFIGURATION;
27import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_SWITCH;
28import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_THUMBNAILS;
29import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_STATES;
30import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_SWITCH;
31import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_THUMBNAILS;
32import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
33import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
34import static com.android.server.am.TaskRecord.INVALID_TASK_ID;
35
36import android.app.ActivityManager.TaskDescription;
37import android.app.ActivityOptions;
38import android.app.PendingIntent;
39import android.app.ResultInfo;
40import android.content.ComponentName;
41import android.content.Intent;
42import android.content.pm.ActivityInfo;
43import android.content.pm.ApplicationInfo;
44import android.content.res.CompatibilityInfo;
45import android.content.res.Configuration;
46import android.graphics.Bitmap;
47import android.graphics.Rect;
48import android.os.Build;
49import android.os.Bundle;
50import android.os.IBinder;
51import android.os.Message;
52import android.os.PersistableBundle;
53import android.os.Process;
54import android.os.RemoteException;
55import android.os.SystemClock;
56import android.os.Trace;
57import android.os.UserHandle;
58import android.service.voice.IVoiceInteractionSession;
59import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
62import android.util.TimeUtils;
63import android.view.AppTransitionAnimationSpec;
64import android.view.IApplicationToken;
65import android.view.WindowManager;
66
67import com.android.internal.app.ResolverActivity;
68import com.android.internal.content.ReferrerIntent;
69import com.android.internal.util.XmlUtils;
70import com.android.server.AttributeCache;
71import com.android.server.am.ActivityStack.ActivityState;
72import com.android.server.am.ActivityStackSupervisor.ActivityContainer;
73
74import java.io.File;
75import java.io.IOException;
76import java.io.PrintWriter;
77import java.lang.ref.WeakReference;
78import java.util.ArrayList;
79import java.util.Arrays;
80import java.util.HashSet;
81import java.util.Objects;
82
83import org.xmlpull.v1.XmlPullParser;
84import org.xmlpull.v1.XmlPullParserException;
85import org.xmlpull.v1.XmlSerializer;
86
87/**
88 * An entry in the history stack, representing an activity.
89 */
90final class ActivityRecord {
91    private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityRecord" : TAG_AM;
92    private static final String TAG_STATES = TAG + POSTFIX_STATES;
93    private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
94    private static final String TAG_THUMBNAILS = TAG + POSTFIX_THUMBNAILS;
95
96    private static final boolean SHOW_ACTIVITY_START_TIME = true;
97    final public static String RECENTS_PACKAGE_NAME = "com.android.systemui.recents";
98
99    private static final String ATTR_ID = "id";
100    private static final String TAG_INTENT = "intent";
101    private static final String ATTR_USERID = "user_id";
102    private static final String TAG_PERSISTABLEBUNDLE = "persistable_bundle";
103    private static final String ATTR_LAUNCHEDFROMUID = "launched_from_uid";
104    private static final String ATTR_LAUNCHEDFROMPACKAGE = "launched_from_package";
105    private static final String ATTR_RESOLVEDTYPE = "resolved_type";
106    private static final String ATTR_COMPONENTSPECIFIED = "component_specified";
107    static final String ACTIVITY_ICON_SUFFIX = "_activity_icon_";
108
109    final ActivityManagerService service; // owner
110    final IApplicationToken.Stub appToken; // window manager token
111    final ActivityInfo info; // all about me
112    final ApplicationInfo appInfo; // information about activity's app
113    final int launchedFromUid; // always the uid who started the activity.
114    final String launchedFromPackage; // always the package who started the activity.
115    final int userId;          // Which user is this running for?
116    final Intent intent;    // the original intent that generated us
117    final ComponentName realActivity;  // the intent component, or target of an alias.
118    final String shortComponentName; // the short component name of the intent
119    final String resolvedType; // as per original caller;
120    final String packageName; // the package implementing intent's component
121    final String processName; // process where this component wants to run
122    final String taskAffinity; // as per ActivityInfo.taskAffinity
123    final boolean stateNotNeeded; // As per ActivityInfo.flags
124    boolean fullscreen; // covers the full screen?
125    final boolean noDisplay;  // activity is not displayed?
126    final boolean componentSpecified;  // did caller specify an explicit component?
127    final boolean rootVoiceInteraction;  // was this the root activity of a voice interaction?
128
129    static final int APPLICATION_ACTIVITY_TYPE = 0;
130    static final int HOME_ACTIVITY_TYPE = 1;
131    static final int RECENTS_ACTIVITY_TYPE = 2;
132    int mActivityType;
133
134    CharSequence nonLocalizedLabel;  // the label information from the package mgr.
135    int labelRes;           // the label information from the package mgr.
136    int icon;               // resource identifier of activity's icon.
137    int logo;               // resource identifier of activity's logo.
138    int theme;              // resource identifier of activity's theme.
139    int realTheme;          // actual theme resource we will use, never 0.
140    int windowFlags;        // custom window flags for preview window.
141    TaskRecord task;        // the task this is in.
142    long createTime = System.currentTimeMillis();
143    long displayStartTime;  // when we started launching this activity
144    long fullyDrawnStartTime; // when we started launching this activity
145    long startTime;         // last time this activity was started
146    long lastVisibleTime;   // last time this activity became visible
147    long cpuTimeAtResume;   // the cpu time of host process at the time of resuming activity
148    long pauseTime;         // last time we started pausing the activity
149    long launchTickTime;    // base time for launch tick messages
150    Configuration configuration; // configuration activity was last running in
151    // Overridden configuration by the activity task
152    // WARNING: Reference points to {@link TaskRecord#mOverrideConfig}, so its internal state
153    // should never be altered directly.
154    Configuration taskConfigOverride;
155    CompatibilityInfo compat;// last used compatibility mode
156    ActivityRecord resultTo; // who started this entry, so will get our reply
157    final String resultWho; // additional identifier for use by resultTo.
158    final int requestCode;  // code given by requester (resultTo)
159    ArrayList<ResultInfo> results; // pending ActivityResult objs we have received
160    HashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this act
161    ArrayList<ReferrerIntent> newIntents; // any pending new intents for single-top mode
162    ActivityOptions pendingOptions; // most recently given options
163    ActivityOptions returningOptions; // options that are coming back via convertToTranslucent
164    AppTimeTracker appTimeTracker; // set if we are tracking the time in this app/task/activity
165    HashSet<ConnectionRecord> connections; // All ConnectionRecord we hold
166    UriPermissionOwner uriPermissions; // current special URI access perms.
167    ProcessRecord app;      // if non-null, hosting application
168    ActivityState state;    // current state we are in
169    Bundle  icicle;         // last saved activity state
170    PersistableBundle persistentState; // last persistently saved activity state
171    boolean frontOfTask;    // is this the root activity of its task?
172    boolean launchFailed;   // set if a launched failed, to abort on 2nd try
173    boolean haveState;      // have we gotten the last activity state?
174    boolean stopped;        // is activity pause finished?
175    boolean delayedResume;  // not yet resumed because of stopped app switches?
176    boolean finishing;      // activity in pending finish list?
177    boolean deferRelaunchUntilPaused;   // relaunch of activity is being deferred until pause is
178                                        // completed
179    boolean preserveWindowOnDeferredRelaunch; // activity windows are preserved on deferred relaunch
180    int configChangeFlags;  // which config values have changed
181    boolean keysPaused;     // has key dispatching been paused for it?
182    int launchMode;         // the launch mode activity attribute.
183    boolean visible;        // does this activity's window need to be shown?
184    boolean sleeping;       // have we told the activity to sleep?
185    boolean nowVisible;     // is this activity's window visible?
186    boolean idle;           // has the activity gone idle?
187    boolean hasBeenLaunched;// has this activity ever been launched?
188    boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.
189    boolean immersive;      // immersive mode (don't interrupt if possible)
190    boolean forceNewConfig; // force re-create with new config next time
191    int launchCount;        // count of launches since last state
192    long lastLaunchTime;    // time of last launch of this activity
193    ComponentName requestedVrComponent; // the requested component for handling VR mode.
194    ArrayList<ActivityContainer> mChildContainers = new ArrayList<>();
195
196    String stringName;      // for caching of toString().
197
198    private boolean inHistory;  // are we in the history stack?
199    final ActivityStackSupervisor mStackSupervisor;
200
201    static final int STARTING_WINDOW_NOT_SHOWN = 0;
202    static final int STARTING_WINDOW_SHOWN = 1;
203    static final int STARTING_WINDOW_REMOVED = 2;
204    int mStartingWindowState = STARTING_WINDOW_NOT_SHOWN;
205
206    boolean mUpdateTaskThumbnailWhenHidden;
207    ActivityContainer mInitialActivityContainer;
208
209    TaskDescription taskDescription; // the recents information for this activity
210    boolean mLaunchTaskBehind; // this activity is actively being launched with
211        // ActivityOptions.setLaunchTaskBehind, will be cleared once launch is completed.
212
213    // These configurations are collected from application's resources based on size-sensitive
214    // qualifiers. For example, layout-w800dp will be added to mHorizontalSizeConfigurations as 800
215    // and drawable-sw400dp will be added to both as 400.
216    private int[] mVerticalSizeConfigurations;
217    private int[] mHorizontalSizeConfigurations;
218    private int[] mSmallestSizeConfigurations;
219
220    boolean pendingVoiceInteractionStart;   // Waiting for activity-invoked voice session
221    IVoiceInteractionSession voiceSession;  // Voice interaction session for this activity
222
223    private static String startingWindowStateToString(int state) {
224        switch (state) {
225            case STARTING_WINDOW_NOT_SHOWN:
226                return "STARTING_WINDOW_NOT_SHOWN";
227            case STARTING_WINDOW_SHOWN:
228                return "STARTING_WINDOW_SHOWN";
229            case STARTING_WINDOW_REMOVED:
230                return "STARTING_WINDOW_REMOVED";
231            default:
232                return "unknown state=" + state;
233        }
234    }
235
236    void dump(PrintWriter pw, String prefix) {
237        final long now = SystemClock.uptimeMillis();
238        pw.print(prefix); pw.print("packageName="); pw.print(packageName);
239                pw.print(" processName="); pw.println(processName);
240        pw.print(prefix); pw.print("launchedFromUid="); pw.print(launchedFromUid);
241                pw.print(" launchedFromPackage="); pw.print(launchedFromPackage);
242                pw.print(" userId="); pw.println(userId);
243        pw.print(prefix); pw.print("app="); pw.println(app);
244        pw.print(prefix); pw.println(intent.toInsecureStringWithClip());
245        pw.print(prefix); pw.print("frontOfTask="); pw.print(frontOfTask);
246                pw.print(" task="); pw.println(task);
247        pw.print(prefix); pw.print("taskAffinity="); pw.println(taskAffinity);
248        pw.print(prefix); pw.print("realActivity=");
249                pw.println(realActivity.flattenToShortString());
250        if (appInfo != null) {
251            pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir);
252            if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
253                pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir);
254            }
255            pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir);
256            if (appInfo.splitSourceDirs != null) {
257                pw.print(prefix); pw.print("splitDir=");
258                        pw.println(Arrays.toString(appInfo.splitSourceDirs));
259            }
260        }
261        pw.print(prefix); pw.print("stateNotNeeded="); pw.print(stateNotNeeded);
262                pw.print(" componentSpecified="); pw.print(componentSpecified);
263                pw.print(" mActivityType="); pw.println(mActivityType);
264        if (rootVoiceInteraction) {
265            pw.print(prefix); pw.print("rootVoiceInteraction="); pw.println(rootVoiceInteraction);
266        }
267        pw.print(prefix); pw.print("compat="); pw.print(compat);
268                pw.print(" labelRes=0x"); pw.print(Integer.toHexString(labelRes));
269                pw.print(" icon=0x"); pw.print(Integer.toHexString(icon));
270                pw.print(" theme=0x"); pw.println(Integer.toHexString(theme));
271        pw.print(prefix); pw.print("config="); pw.println(configuration);
272        pw.print(prefix); pw.print("taskConfigOverride="); pw.println(taskConfigOverride);
273        if (resultTo != null || resultWho != null) {
274            pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
275                    pw.print(" resultWho="); pw.print(resultWho);
276                    pw.print(" resultCode="); pw.println(requestCode);
277        }
278        if (taskDescription != null) {
279            final String iconFilename = taskDescription.getIconFilename();
280            if (iconFilename != null || taskDescription.getLabel() != null ||
281                    taskDescription.getPrimaryColor() != 0) {
282                pw.print(prefix); pw.print("taskDescription:");
283                        pw.print(" iconFilename="); pw.print(taskDescription.getIconFilename());
284                        pw.print(" label=\""); pw.print(taskDescription.getLabel());
285                                pw.print("\"");
286                        pw.print(" color=");
287                        pw.println(Integer.toHexString(taskDescription.getPrimaryColor()));
288            }
289            if (iconFilename == null && taskDescription.getIcon() != null) {
290                pw.print(prefix); pw.println("taskDescription contains Bitmap");
291            }
292        }
293        if (results != null) {
294            pw.print(prefix); pw.print("results="); pw.println(results);
295        }
296        if (pendingResults != null && pendingResults.size() > 0) {
297            pw.print(prefix); pw.println("Pending Results:");
298            for (WeakReference<PendingIntentRecord> wpir : pendingResults) {
299                PendingIntentRecord pir = wpir != null ? wpir.get() : null;
300                pw.print(prefix); pw.print("  - ");
301                if (pir == null) {
302                    pw.println("null");
303                } else {
304                    pw.println(pir);
305                    pir.dump(pw, prefix + "    ");
306                }
307            }
308        }
309        if (newIntents != null && newIntents.size() > 0) {
310            pw.print(prefix); pw.println("Pending New Intents:");
311            for (int i=0; i<newIntents.size(); i++) {
312                Intent intent = newIntents.get(i);
313                pw.print(prefix); pw.print("  - ");
314                if (intent == null) {
315                    pw.println("null");
316                } else {
317                    pw.println(intent.toShortString(false, true, false, true));
318                }
319            }
320        }
321        if (pendingOptions != null) {
322            pw.print(prefix); pw.print("pendingOptions="); pw.println(pendingOptions);
323        }
324        if (appTimeTracker != null) {
325            appTimeTracker.dumpWithHeader(pw, prefix, false);
326        }
327        if (uriPermissions != null) {
328            uriPermissions.dump(pw, prefix);
329        }
330        pw.print(prefix); pw.print("launchFailed="); pw.print(launchFailed);
331                pw.print(" launchCount="); pw.print(launchCount);
332                pw.print(" lastLaunchTime=");
333                if (lastLaunchTime == 0) pw.print("0");
334                else TimeUtils.formatDuration(lastLaunchTime, now, pw);
335                pw.println();
336        pw.print(prefix); pw.print("haveState="); pw.print(haveState);
337                pw.print(" icicle="); pw.println(icicle);
338        pw.print(prefix); pw.print("state="); pw.print(state);
339                pw.print(" stopped="); pw.print(stopped);
340                pw.print(" delayedResume="); pw.print(delayedResume);
341                pw.print(" finishing="); pw.println(finishing);
342        pw.print(prefix); pw.print("keysPaused="); pw.print(keysPaused);
343                pw.print(" inHistory="); pw.print(inHistory);
344                pw.print(" visible="); pw.print(visible);
345                pw.print(" sleeping="); pw.print(sleeping);
346                pw.print(" idle="); pw.print(idle);
347                pw.print(" mStartingWindowState=");
348                pw.println(startingWindowStateToString(mStartingWindowState));
349        pw.print(prefix); pw.print("fullscreen="); pw.print(fullscreen);
350                pw.print(" noDisplay="); pw.print(noDisplay);
351                pw.print(" immersive="); pw.print(immersive);
352                pw.print(" launchMode="); pw.println(launchMode);
353        pw.print(prefix); pw.print("frozenBeforeDestroy="); pw.print(frozenBeforeDestroy);
354                pw.print(" forceNewConfig="); pw.println(forceNewConfig);
355        pw.print(prefix); pw.print("mActivityType=");
356                pw.println(activityTypeToString(mActivityType));
357        if (requestedVrComponent != null) {
358            pw.print(prefix);
359            pw.print("requestedVrComponent=");
360            pw.println(requestedVrComponent);
361        }
362        if (displayStartTime != 0 || startTime != 0) {
363            pw.print(prefix); pw.print("displayStartTime=");
364                    if (displayStartTime == 0) pw.print("0");
365                    else TimeUtils.formatDuration(displayStartTime, now, pw);
366                    pw.print(" startTime=");
367                    if (startTime == 0) pw.print("0");
368                    else TimeUtils.formatDuration(startTime, now, pw);
369                    pw.println();
370        }
371        final boolean waitingVisible = mStackSupervisor.mWaitingVisibleActivities.contains(this);
372        if (lastVisibleTime != 0 || waitingVisible || nowVisible) {
373            pw.print(prefix); pw.print("waitingVisible="); pw.print(waitingVisible);
374                    pw.print(" nowVisible="); pw.print(nowVisible);
375                    pw.print(" lastVisibleTime=");
376                    if (lastVisibleTime == 0) pw.print("0");
377                    else TimeUtils.formatDuration(lastVisibleTime, now, pw);
378                    pw.println();
379        }
380        if (deferRelaunchUntilPaused || configChangeFlags != 0) {
381            pw.print(prefix); pw.print("deferRelaunchUntilPaused="); pw.print(deferRelaunchUntilPaused);
382                    pw.print(" configChangeFlags=");
383                    pw.println(Integer.toHexString(configChangeFlags));
384        }
385        if (connections != null) {
386            pw.print(prefix); pw.print("connections="); pw.println(connections);
387        }
388        if (info != null) {
389            pw.println(prefix + "resizeMode=" + ActivityInfo.resizeModeToString(info.resizeMode));
390        }
391    }
392
393    public boolean crossesHorizontalSizeThreshold(int firstDp, int secondDp) {
394        return crossesSizeThreshold(mHorizontalSizeConfigurations, firstDp, secondDp);
395    }
396
397    public boolean crossesVerticalSizeThreshold(int firstDp, int secondDp) {
398        return crossesSizeThreshold(mVerticalSizeConfigurations, firstDp, secondDp);
399    }
400
401    public boolean crossesSmallestSizeThreshold(int firstDp, int secondDp) {
402        return crossesSizeThreshold(mSmallestSizeConfigurations, firstDp, secondDp);
403    }
404
405    /**
406     * The purpose of this method is to decide whether the activity needs to be relaunched upon
407     * changing its size. In most cases the activities don't need to be relaunched, if the resize
408     * is small, all the activity content has to do is relayout itself within new bounds. There are
409     * cases however, where the activity's content would be completely changed in the new size and
410     * the full relaunch is required.
411     *
412     * The activity will report to us vertical and horizontal thresholds after which a relaunch is
413     * required. These thresholds are collected from the application resource qualifiers. For
414     * example, if application has layout-w600dp resource directory, then it needs a relaunch when
415     * we resize from width of 650dp to 550dp, as it crosses the 600dp threshold. However, if
416     * it resizes width from 620dp to 700dp, it won't be relaunched as it stays on the same side
417     * of the threshold.
418     */
419    private static boolean crossesSizeThreshold(int[] thresholds, int firstDp,
420            int secondDp) {
421        if (thresholds == null) {
422            return false;
423        }
424        for (int i = thresholds.length - 1; i >= 0; i--) {
425            final int threshold = thresholds[i];
426            if ((firstDp < threshold && secondDp >= threshold)
427                    || (firstDp >= threshold && secondDp < threshold)) {
428                return true;
429            }
430        }
431        return false;
432    }
433
434    public void setSizeConfigurations(int[] horizontalSizeConfiguration,
435            int[] verticalSizeConfigurations, int[] smallestSizeConfigurations) {
436        mHorizontalSizeConfigurations = horizontalSizeConfiguration;
437        mVerticalSizeConfigurations = verticalSizeConfigurations;
438        mSmallestSizeConfigurations = smallestSizeConfigurations;
439    }
440
441    void scheduleConfigurationChanged(Configuration config, boolean reportToActivity) {
442        if (app == null || app.thread == null) {
443            return;
444        }
445        try {
446            if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + this + " " +
447                    "reportToActivity=" + reportToActivity + " and config: " + config);
448            app.thread.scheduleActivityConfigurationChanged(
449                    appToken, new Configuration(config), reportToActivity);
450        } catch (RemoteException e) {
451            // If process died, whatever.
452        }
453    }
454
455    void scheduleMultiWindowModeChanged() {
456        if (task == null || task.stack == null || app == null || app.thread == null) {
457            return;
458        }
459        try {
460            // An activity is considered to be in multi-window mode if its task isn't fullscreen.
461            app.thread.scheduleMultiWindowModeChanged(appToken, !task.mFullscreen);
462        } catch (Exception e) {
463            // If process died, I don't care.
464        }
465    }
466
467    void schedulePictureInPictureModeChanged() {
468        if (task == null || task.stack == null || app == null || app.thread == null) {
469            return;
470        }
471        try {
472            app.thread.schedulePictureInPictureModeChanged(
473                    appToken, task.stack.mStackId == PINNED_STACK_ID);
474        } catch (Exception e) {
475            // If process died, no one cares.
476        }
477    }
478
479    boolean isFreeform() {
480        return task != null && task.stack != null
481                && task.stack.mStackId == FREEFORM_WORKSPACE_STACK_ID;
482    }
483
484    static class Token extends IApplicationToken.Stub {
485        private final WeakReference<ActivityRecord> weakActivity;
486        private final ActivityManagerService mService;
487
488        Token(ActivityRecord activity, ActivityManagerService service) {
489            weakActivity = new WeakReference<>(activity);
490            mService = service;
491        }
492
493        @Override
494        public void windowsDrawn() {
495            synchronized (mService) {
496                ActivityRecord r = tokenToActivityRecordLocked(this);
497                if (r != null) {
498                    r.windowsDrawnLocked();
499                }
500            }
501        }
502
503        @Override
504        public void windowsVisible() {
505            synchronized (mService) {
506                ActivityRecord r = tokenToActivityRecordLocked(this);
507                if (r != null) {
508                    r.windowsVisibleLocked();
509                }
510            }
511        }
512
513        @Override
514        public void windowsGone() {
515            synchronized (mService) {
516                ActivityRecord r = tokenToActivityRecordLocked(this);
517                if (r != null) {
518                    if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsGone(): " + r);
519                    r.nowVisible = false;
520                    return;
521                }
522            }
523        }
524
525        @Override
526        public boolean keyDispatchingTimedOut(String reason) {
527            ActivityRecord r;
528            ActivityRecord anrActivity;
529            ProcessRecord anrApp;
530            synchronized (mService) {
531                r = tokenToActivityRecordLocked(this);
532                if (r == null) {
533                    return false;
534                }
535                anrActivity = r.getWaitingHistoryRecordLocked();
536                anrApp = r != null ? r.app : null;
537            }
538            return mService.inputDispatchingTimedOut(anrApp, anrActivity, r, false, reason);
539        }
540
541        @Override
542        public long getKeyDispatchingTimeout() {
543            synchronized (mService) {
544                ActivityRecord r = tokenToActivityRecordLocked(this);
545                if (r == null) {
546                    return 0;
547                }
548                r = r.getWaitingHistoryRecordLocked();
549                return ActivityManagerService.getInputDispatchingTimeoutLocked(r);
550            }
551        }
552
553        private static final ActivityRecord tokenToActivityRecordLocked(Token token) {
554            if (token == null) {
555                return null;
556            }
557            ActivityRecord r = token.weakActivity.get();
558            if (r == null || r.task == null || r.task.stack == null) {
559                return null;
560            }
561            return r;
562        }
563
564        @Override
565        public String toString() {
566            StringBuilder sb = new StringBuilder(128);
567            sb.append("Token{");
568            sb.append(Integer.toHexString(System.identityHashCode(this)));
569            sb.append(' ');
570            sb.append(weakActivity.get());
571            sb.append('}');
572            return sb.toString();
573        }
574    }
575
576    static ActivityRecord forTokenLocked(IBinder token) {
577        try {
578            return Token.tokenToActivityRecordLocked((Token)token);
579        } catch (ClassCastException e) {
580            Slog.w(TAG, "Bad activity token: " + token, e);
581            return null;
582        }
583    }
584
585    boolean isResolverActivity() {
586        return ResolverActivity.class.getName().equals(realActivity.getClassName());
587    }
588
589    ActivityRecord(ActivityManagerService _service, ProcessRecord _caller,
590            int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
591            ActivityInfo aInfo, Configuration _configuration,
592            ActivityRecord _resultTo, String _resultWho, int _reqCode,
593            boolean _componentSpecified, boolean _rootVoiceInteraction,
594            ActivityStackSupervisor supervisor,
595            ActivityContainer container, ActivityOptions options, ActivityRecord sourceRecord) {
596        service = _service;
597        appToken = new Token(this, service);
598        info = aInfo;
599        launchedFromUid = _launchedFromUid;
600        launchedFromPackage = _launchedFromPackage;
601        userId = UserHandle.getUserId(aInfo.applicationInfo.uid);
602        intent = _intent;
603        shortComponentName = _intent.getComponent().flattenToShortString();
604        resolvedType = _resolvedType;
605        componentSpecified = _componentSpecified;
606        rootVoiceInteraction = _rootVoiceInteraction;
607        configuration = _configuration;
608        taskConfigOverride = Configuration.EMPTY;
609        resultTo = _resultTo;
610        resultWho = _resultWho;
611        requestCode = _reqCode;
612        state = ActivityState.INITIALIZING;
613        frontOfTask = false;
614        launchFailed = false;
615        stopped = false;
616        delayedResume = false;
617        finishing = false;
618        deferRelaunchUntilPaused = false;
619        keysPaused = false;
620        inHistory = false;
621        visible = false;
622        nowVisible = false;
623        idle = false;
624        hasBeenLaunched = false;
625        mStackSupervisor = supervisor;
626        mInitialActivityContainer = container;
627        if (options != null) {
628            pendingOptions = options;
629            mLaunchTaskBehind = pendingOptions.getLaunchTaskBehind();
630            PendingIntent usageReport = pendingOptions.getUsageTimeReport();
631            if (usageReport != null) {
632                appTimeTracker = new AppTimeTracker(usageReport);
633            }
634        }
635
636        // This starts out true, since the initial state of an activity
637        // is that we have everything, and we shouldn't never consider it
638        // lacking in state to be removed if it dies.
639        haveState = true;
640
641        if (aInfo != null) {
642            // If the class name in the intent doesn't match that of the target, this is
643            // probably an alias. We have to create a new ComponentName object to keep track
644            // of the real activity name, so that FLAG_ACTIVITY_CLEAR_TOP is handled properly.
645            if (aInfo.targetActivity == null
646                    || (aInfo.targetActivity.equals(_intent.getComponent().getClassName())
647                    && (aInfo.launchMode == ActivityInfo.LAUNCH_MULTIPLE
648                    || aInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP))) {
649                realActivity = _intent.getComponent();
650            } else {
651                realActivity = new ComponentName(aInfo.packageName, aInfo.targetActivity);
652            }
653            taskAffinity = aInfo.taskAffinity;
654            stateNotNeeded = (aInfo.flags&
655                    ActivityInfo.FLAG_STATE_NOT_NEEDED) != 0;
656            appInfo = aInfo.applicationInfo;
657            nonLocalizedLabel = aInfo.nonLocalizedLabel;
658            labelRes = aInfo.labelRes;
659            if (nonLocalizedLabel == null && labelRes == 0) {
660                ApplicationInfo app = aInfo.applicationInfo;
661                nonLocalizedLabel = app.nonLocalizedLabel;
662                labelRes = app.labelRes;
663            }
664            icon = aInfo.getIconResource();
665            logo = aInfo.getLogoResource();
666            theme = aInfo.getThemeResource();
667            realTheme = theme;
668            if (realTheme == 0) {
669                realTheme = aInfo.applicationInfo.targetSdkVersion
670                        < Build.VERSION_CODES.HONEYCOMB
671                        ? android.R.style.Theme
672                        : android.R.style.Theme_Holo;
673            }
674            if ((aInfo.flags&ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
675                windowFlags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
676            }
677            if ((aInfo.flags&ActivityInfo.FLAG_MULTIPROCESS) != 0
678                    && _caller != null
679                    && (aInfo.applicationInfo.uid == Process.SYSTEM_UID
680                            || aInfo.applicationInfo.uid == _caller.info.uid)) {
681                processName = _caller.processName;
682            } else {
683                processName = aInfo.processName;
684            }
685
686            if (intent != null && (aInfo.flags & ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS) != 0) {
687                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
688            }
689
690            packageName = aInfo.applicationInfo.packageName;
691            launchMode = aInfo.launchMode;
692
693            AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
694                    realTheme, com.android.internal.R.styleable.Window, userId);
695            final boolean translucent = ent != null && (ent.array.getBoolean(
696                    com.android.internal.R.styleable.Window_windowIsTranslucent, false)
697                    || (!ent.array.hasValue(
698                            com.android.internal.R.styleable.Window_windowIsTranslucent)
699                            && ent.array.getBoolean(
700                                    com.android.internal.R.styleable.Window_windowSwipeToDismiss,
701                                            false)));
702            fullscreen = ent != null && !ent.array.getBoolean(
703                    com.android.internal.R.styleable.Window_windowIsFloating, false)
704                    && !translucent;
705            noDisplay = ent != null && ent.array.getBoolean(
706                    com.android.internal.R.styleable.Window_windowNoDisplay, false);
707
708            setActivityType(_componentSpecified, _launchedFromUid, _intent, sourceRecord);
709
710            immersive = (aInfo.flags & ActivityInfo.FLAG_IMMERSIVE) != 0;
711
712            requestedVrComponent = (aInfo.requestedVrComponent == null) ?
713                    null : ComponentName.unflattenFromString(aInfo.requestedVrComponent);
714        } else {
715            realActivity = null;
716            taskAffinity = null;
717            stateNotNeeded = false;
718            appInfo = null;
719            processName = null;
720            packageName = null;
721            fullscreen = true;
722            noDisplay = false;
723            mActivityType = APPLICATION_ACTIVITY_TYPE;
724            immersive = false;
725            requestedVrComponent  = null;
726        }
727    }
728
729    private boolean isHomeIntent(Intent intent) {
730        return Intent.ACTION_MAIN.equals(intent.getAction())
731                && intent.hasCategory(Intent.CATEGORY_HOME)
732                && intent.getCategories().size() == 1
733                && intent.getData() == null
734                && intent.getType() == null;
735    }
736
737    private boolean canLaunchHomeActivity(int uid, ActivityRecord sourceRecord) {
738        if (uid == Process.myUid() || uid == 0) {
739            // System process can launch home activity.
740            return true;
741        }
742        // Resolver activity can launch home activity.
743        return sourceRecord != null && sourceRecord.isResolverActivity();
744    }
745
746    private void setActivityType(boolean componentSpecified,
747            int launchedFromUid, Intent intent, ActivityRecord sourceRecord) {
748        if ((!componentSpecified || canLaunchHomeActivity(launchedFromUid, sourceRecord))
749                && isHomeIntent(intent) && !isResolverActivity()) {
750            // This sure looks like a home activity!
751            mActivityType = HOME_ACTIVITY_TYPE;
752        } else if (realActivity.getClassName().contains(RECENTS_PACKAGE_NAME)) {
753            mActivityType = RECENTS_ACTIVITY_TYPE;
754        } else {
755            mActivityType = APPLICATION_ACTIVITY_TYPE;
756        }
757    }
758
759    void setTask(TaskRecord newTask, TaskRecord taskToAffiliateWith) {
760        if (task != null && task.removeActivity(this) && task != newTask && task.stack != null) {
761            task.stack.removeTask(task, "setTask");
762        }
763        task = newTask;
764        setTaskToAffiliateWith(taskToAffiliateWith);
765    }
766
767    void setTaskToAffiliateWith(TaskRecord taskToAffiliateWith) {
768        if (taskToAffiliateWith != null &&
769                launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE &&
770                launchMode != ActivityInfo.LAUNCH_SINGLE_TASK) {
771            task.setTaskToAffiliateWith(taskToAffiliateWith);
772        }
773    }
774
775    boolean changeWindowTranslucency(boolean toOpaque) {
776        if (fullscreen == toOpaque) {
777            return false;
778        }
779
780        // Keep track of the number of fullscreen activities in this task.
781        task.numFullscreen += toOpaque ? +1 : -1;
782
783        fullscreen = toOpaque;
784        return true;
785    }
786
787    void putInHistory() {
788        if (!inHistory) {
789            inHistory = true;
790        }
791    }
792
793    void takeFromHistory() {
794        if (inHistory) {
795            inHistory = false;
796            if (task != null && !finishing) {
797                task = null;
798            }
799            clearOptionsLocked();
800        }
801    }
802
803    boolean isInHistory() {
804        return inHistory;
805    }
806
807    boolean isInStackLocked() {
808        return task != null && task.stack != null && task.stack.isInStackLocked(this) != null;
809    }
810
811    boolean isHomeActivity() {
812        return mActivityType == HOME_ACTIVITY_TYPE;
813    }
814
815    boolean isRecentsActivity() {
816        return mActivityType == RECENTS_ACTIVITY_TYPE;
817    }
818
819    boolean isApplicationActivity() {
820        return mActivityType == APPLICATION_ACTIVITY_TYPE;
821    }
822
823    boolean isPersistable() {
824        return (info.persistableMode == ActivityInfo.PERSIST_ROOT_ONLY ||
825                info.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS) &&
826                (intent == null ||
827                        (intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0);
828    }
829
830    boolean isFocusable() {
831        return StackId.canReceiveKeys(task.stack.mStackId) || isAlwaysFocusable();
832    }
833
834    boolean isResizeable() {
835        return !isHomeActivity() && ActivityInfo.isResizeableMode(info.resizeMode);
836    }
837
838    boolean isResizeableOrForced() {
839        return !isHomeActivity() && (isResizeable() || service.mForceResizableActivities);
840    }
841
842    boolean isNonResizableOrForced() {
843        return !isHomeActivity() && info.resizeMode != RESIZE_MODE_RESIZEABLE
844                && info.resizeMode != RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
845    }
846
847    boolean supportsPictureInPicture() {
848        return !isHomeActivity() && info.resizeMode == RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
849    }
850
851    boolean canGoInDockedStack() {
852        return !isHomeActivity()
853                && (isResizeableOrForced() || info.resizeMode == RESIZE_MODE_CROP_WINDOWS);
854    }
855
856    boolean isAlwaysFocusable() {
857        return (info.flags & FLAG_ALWAYS_FOCUSABLE) != 0;
858    }
859
860    void makeFinishingLocked() {
861        if (!finishing) {
862            if (task != null && task.stack != null
863                    && this == task.stack.getVisibleBehindActivity()) {
864                // A finishing activity should not remain as visible in the background
865                mStackSupervisor.requestVisibleBehindLocked(this, false);
866            }
867            finishing = true;
868            if (stopped) {
869                clearOptionsLocked();
870            }
871        }
872    }
873
874    UriPermissionOwner getUriPermissionsLocked() {
875        if (uriPermissions == null) {
876            uriPermissions = new UriPermissionOwner(service, this);
877        }
878        return uriPermissions;
879    }
880
881    void addResultLocked(ActivityRecord from, String resultWho,
882            int requestCode, int resultCode,
883            Intent resultData) {
884        ActivityResult r = new ActivityResult(from, resultWho,
885                requestCode, resultCode, resultData);
886        if (results == null) {
887            results = new ArrayList<ResultInfo>();
888        }
889        results.add(r);
890    }
891
892    void removeResultsLocked(ActivityRecord from, String resultWho,
893            int requestCode) {
894        if (results != null) {
895            for (int i=results.size()-1; i>=0; i--) {
896                ActivityResult r = (ActivityResult)results.get(i);
897                if (r.mFrom != from) continue;
898                if (r.mResultWho == null) {
899                    if (resultWho != null) continue;
900                } else {
901                    if (!r.mResultWho.equals(resultWho)) continue;
902                }
903                if (r.mRequestCode != requestCode) continue;
904
905                results.remove(i);
906            }
907        }
908    }
909
910    void addNewIntentLocked(ReferrerIntent intent) {
911        if (newIntents == null) {
912            newIntents = new ArrayList<>();
913        }
914        newIntents.add(intent);
915    }
916
917    /**
918     * Deliver a new Intent to an existing activity, so that its onNewIntent()
919     * method will be called at the proper time.
920     */
921    final void deliverNewIntentLocked(int callingUid, Intent intent, String referrer) {
922        // The activity now gets access to the data associated with this Intent.
923        service.grantUriPermissionFromIntentLocked(callingUid, packageName,
924                intent, getUriPermissionsLocked(), userId);
925        // We want to immediately deliver the intent to the activity if
926        // it is currently the top resumed activity...  however, if the
927        // device is sleeping, then all activities are stopped, so in that
928        // case we will deliver it if this is the current top activity on its
929        // stack.
930        final ReferrerIntent rintent = new ReferrerIntent(intent, referrer);
931        boolean unsent = true;
932        if ((state == ActivityState.RESUMED
933                || (service.isSleeping() && task.stack != null
934                    && task.stack.topRunningActivityLocked() == this))
935                && app != null && app.thread != null) {
936            try {
937                ArrayList<ReferrerIntent> ar = new ArrayList<>(1);
938                ar.add(rintent);
939                app.thread.scheduleNewIntent(ar, appToken);
940                unsent = false;
941            } catch (RemoteException e) {
942                Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
943            } catch (NullPointerException e) {
944                Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
945            }
946        }
947        if (unsent) {
948            addNewIntentLocked(rintent);
949        }
950    }
951
952    void updateOptionsLocked(ActivityOptions options) {
953        if (options != null) {
954            if (pendingOptions != null) {
955                pendingOptions.abort();
956            }
957            pendingOptions = options;
958        }
959    }
960
961    void applyOptionsLocked() {
962        if (pendingOptions != null
963                && pendingOptions.getAnimationType() != ActivityOptions.ANIM_SCENE_TRANSITION) {
964            final int animationType = pendingOptions.getAnimationType();
965            switch (animationType) {
966                case ActivityOptions.ANIM_CUSTOM:
967                    service.mWindowManager.overridePendingAppTransition(
968                            pendingOptions.getPackageName(),
969                            pendingOptions.getCustomEnterResId(),
970                            pendingOptions.getCustomExitResId(),
971                            pendingOptions.getOnAnimationStartListener());
972                    break;
973                case ActivityOptions.ANIM_CLIP_REVEAL:
974                    service.mWindowManager.overridePendingAppTransitionClipReveal(
975                            pendingOptions.getStartX(), pendingOptions.getStartY(),
976                            pendingOptions.getWidth(), pendingOptions.getHeight());
977                    if (intent.getSourceBounds() == null) {
978                        intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
979                                pendingOptions.getStartY(),
980                                pendingOptions.getStartX()+pendingOptions.getWidth(),
981                                pendingOptions.getStartY()+pendingOptions.getHeight()));
982                    }
983                    break;
984                case ActivityOptions.ANIM_SCALE_UP:
985                    service.mWindowManager.overridePendingAppTransitionScaleUp(
986                            pendingOptions.getStartX(), pendingOptions.getStartY(),
987                            pendingOptions.getWidth(), pendingOptions.getHeight());
988                    if (intent.getSourceBounds() == null) {
989                        intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
990                                pendingOptions.getStartY(),
991                                pendingOptions.getStartX()+pendingOptions.getWidth(),
992                                pendingOptions.getStartY()+pendingOptions.getHeight()));
993                    }
994                    break;
995                case ActivityOptions.ANIM_THUMBNAIL_SCALE_UP:
996                case ActivityOptions.ANIM_THUMBNAIL_SCALE_DOWN:
997                    boolean scaleUp = (animationType == ActivityOptions.ANIM_THUMBNAIL_SCALE_UP);
998                    service.mWindowManager.overridePendingAppTransitionThumb(
999                            pendingOptions.getThumbnail(),
1000                            pendingOptions.getStartX(), pendingOptions.getStartY(),
1001                            pendingOptions.getOnAnimationStartListener(),
1002                            scaleUp);
1003                    if (intent.getSourceBounds() == null) {
1004                        intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1005                                pendingOptions.getStartY(),
1006                                pendingOptions.getStartX()
1007                                        + pendingOptions.getThumbnail().getWidth(),
1008                                pendingOptions.getStartY()
1009                                        + pendingOptions.getThumbnail().getHeight()));
1010                    }
1011                    break;
1012                case ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_UP:
1013                case ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_DOWN:
1014                    final AppTransitionAnimationSpec[] specs = pendingOptions.getAnimSpecs();
1015                    if (animationType == ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_DOWN
1016                            && specs != null) {
1017                        service.mWindowManager.overridePendingAppTransitionMultiThumb(
1018                                specs, pendingOptions.getOnAnimationStartListener(),
1019                                pendingOptions.getAnimationFinishedListener(), false);
1020                    } else {
1021                        service.mWindowManager.overridePendingAppTransitionAspectScaledThumb(
1022                                pendingOptions.getThumbnail(),
1023                                pendingOptions.getStartX(), pendingOptions.getStartY(),
1024                                pendingOptions.getWidth(), pendingOptions.getHeight(),
1025                                pendingOptions.getOnAnimationStartListener(),
1026                                (animationType == ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_UP));
1027                        if (intent.getSourceBounds() == null) {
1028                            intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1029                                    pendingOptions.getStartY(),
1030                                    pendingOptions.getStartX() + pendingOptions.getWidth(),
1031                                    pendingOptions.getStartY() + pendingOptions.getHeight()));
1032                        }
1033                    }
1034                    break;
1035                default:
1036                    Slog.e(TAG, "applyOptionsLocked: Unknown animationType=" + animationType);
1037                    break;
1038            }
1039            pendingOptions = null;
1040        }
1041    }
1042
1043    ActivityOptions getOptionsForTargetActivityLocked() {
1044        return pendingOptions != null ? pendingOptions.forTargetActivity() : null;
1045    }
1046
1047    void clearOptionsLocked() {
1048        if (pendingOptions != null) {
1049            pendingOptions.abort();
1050            pendingOptions = null;
1051        }
1052    }
1053
1054    ActivityOptions takeOptionsLocked() {
1055        ActivityOptions opts = pendingOptions;
1056        pendingOptions = null;
1057        return opts;
1058    }
1059
1060    void removeUriPermissionsLocked() {
1061        if (uriPermissions != null) {
1062            uriPermissions.removeUriPermissionsLocked();
1063            uriPermissions = null;
1064        }
1065    }
1066
1067    void pauseKeyDispatchingLocked() {
1068        if (!keysPaused) {
1069            keysPaused = true;
1070            service.mWindowManager.pauseKeyDispatching(appToken);
1071        }
1072    }
1073
1074    void resumeKeyDispatchingLocked() {
1075        if (keysPaused) {
1076            keysPaused = false;
1077            service.mWindowManager.resumeKeyDispatching(appToken);
1078        }
1079    }
1080
1081    void updateThumbnailLocked(Bitmap newThumbnail, CharSequence description) {
1082        if (newThumbnail != null) {
1083            if (DEBUG_THUMBNAILS) Slog.i(TAG_THUMBNAILS,
1084                    "Setting thumbnail of " + this + " to " + newThumbnail);
1085            boolean thumbnailUpdated = task.setLastThumbnailLocked(newThumbnail);
1086            if (thumbnailUpdated && isPersistable()) {
1087                mStackSupervisor.mService.notifyTaskPersisterLocked(task, false);
1088            }
1089        }
1090        task.lastDescription = description;
1091    }
1092
1093    void startLaunchTickingLocked() {
1094        if (ActivityManagerService.IS_USER_BUILD) {
1095            return;
1096        }
1097        if (launchTickTime == 0) {
1098            launchTickTime = SystemClock.uptimeMillis();
1099            continueLaunchTickingLocked();
1100        }
1101    }
1102
1103    boolean continueLaunchTickingLocked() {
1104        if (launchTickTime == 0) {
1105            return false;
1106        }
1107
1108        final ActivityStack stack = task.stack;
1109        if (stack == null) {
1110            return false;
1111        }
1112
1113        Message msg = stack.mHandler.obtainMessage(ActivityStack.LAUNCH_TICK_MSG, this);
1114        stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
1115        stack.mHandler.sendMessageDelayed(msg, ActivityStack.LAUNCH_TICK);
1116        return true;
1117    }
1118
1119    void finishLaunchTickingLocked() {
1120        launchTickTime = 0;
1121        final ActivityStack stack = task.stack;
1122        if (stack != null) {
1123            stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
1124        }
1125    }
1126
1127    // IApplicationToken
1128
1129    public boolean mayFreezeScreenLocked(ProcessRecord app) {
1130        // Only freeze the screen if this activity is currently attached to
1131        // an application, and that application is not blocked or unresponding.
1132        // In any other case, we can't count on getting the screen unfrozen,
1133        // so it is best to leave as-is.
1134        return app != null && !app.crashing && !app.notResponding;
1135    }
1136
1137    public void startFreezingScreenLocked(ProcessRecord app, int configChanges) {
1138        if (mayFreezeScreenLocked(app)) {
1139            service.mWindowManager.startAppFreezingScreen(appToken, configChanges);
1140        }
1141    }
1142
1143    public void stopFreezingScreenLocked(boolean force) {
1144        if (force || frozenBeforeDestroy) {
1145            frozenBeforeDestroy = false;
1146            service.mWindowManager.stopAppFreezingScreen(appToken, force);
1147        }
1148    }
1149
1150    public void reportFullyDrawnLocked() {
1151        final long curTime = SystemClock.uptimeMillis();
1152        // Normally launch time counts from the point when the activity is resumed, to when the
1153        // first window is drawn. However the activity could become visible before it is resumed,
1154        // due to some other activity in the same task being launched. In this case we still need
1155        // to report launch time to unblock ActivityStarter.startActivityMayWait().
1156        if (displayStartTime == 0 && task != null && task.isLaunching) {
1157            displayStartTime = curTime;
1158        }
1159        if (displayStartTime != 0) {
1160            reportLaunchTimeLocked(curTime);
1161        }
1162        final ActivityStack stack = task.stack;
1163        if (fullyDrawnStartTime != 0 && stack != null) {
1164            final long thisTime = curTime - fullyDrawnStartTime;
1165            final long totalTime = stack.mFullyDrawnStartTime != 0
1166                    ? (curTime - stack.mFullyDrawnStartTime) : thisTime;
1167            if (SHOW_ACTIVITY_START_TIME) {
1168                Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
1169                EventLog.writeEvent(EventLogTags.AM_ACTIVITY_FULLY_DRAWN_TIME,
1170                        userId, System.identityHashCode(this), shortComponentName,
1171                        thisTime, totalTime);
1172                StringBuilder sb = service.mStringBuilder;
1173                sb.setLength(0);
1174                sb.append("Fully drawn ");
1175                sb.append(shortComponentName);
1176                sb.append(": ");
1177                TimeUtils.formatDuration(thisTime, sb);
1178                if (thisTime != totalTime) {
1179                    sb.append(" (total ");
1180                    TimeUtils.formatDuration(totalTime, sb);
1181                    sb.append(")");
1182                }
1183                Log.i(TAG, sb.toString());
1184            }
1185            if (totalTime > 0) {
1186                //service.mUsageStatsService.noteFullyDrawnTime(realActivity, (int) totalTime);
1187            }
1188            stack.mFullyDrawnStartTime = 0;
1189        }
1190        fullyDrawnStartTime = 0;
1191    }
1192
1193    private void reportLaunchTimeLocked(final long curTime) {
1194        final ActivityStack stack = task.stack;
1195        if (stack == null) {
1196            return;
1197        }
1198        final long thisTime = curTime - displayStartTime;
1199        final long totalTime = stack.mLaunchStartTime != 0
1200                ? (curTime - stack.mLaunchStartTime) : thisTime;
1201        if (SHOW_ACTIVITY_START_TIME) {
1202            Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching: " + packageName, 0);
1203            EventLog.writeEvent(EventLogTags.AM_ACTIVITY_LAUNCH_TIME,
1204                    userId, System.identityHashCode(this), shortComponentName,
1205                    thisTime, totalTime);
1206            StringBuilder sb = service.mStringBuilder;
1207            sb.setLength(0);
1208            sb.append("Displayed ");
1209            sb.append(shortComponentName);
1210            sb.append(": ");
1211            TimeUtils.formatDuration(thisTime, sb);
1212            if (thisTime != totalTime) {
1213                sb.append(" (total ");
1214                TimeUtils.formatDuration(totalTime, sb);
1215                sb.append(")");
1216            }
1217            Log.i(TAG, sb.toString());
1218        }
1219        mStackSupervisor.reportActivityLaunchedLocked(false, this, thisTime, totalTime);
1220        if (totalTime > 0) {
1221            //service.mUsageStatsService.noteLaunchTime(realActivity, (int)totalTime);
1222        }
1223        displayStartTime = 0;
1224        task.isLaunching = false;
1225        stack.mLaunchStartTime = 0;
1226    }
1227
1228    void windowsDrawnLocked() {
1229        mStackSupervisor.mActivityMetricsLogger.notifyWindowsDrawn();
1230        final long curTime = SystemClock.uptimeMillis();
1231        // Normally launch time counts from the point when the activity is resumed, to when the
1232        // first window is drawn. However the activity could become visible before it is resumed,
1233        // due to some other activity in the same task being launched. In this case we still need
1234        // to report launch time to unblock ActivityStarter.startActivityMayWait().
1235        if (displayStartTime == 0 && task != null && task.isLaunching) {
1236            displayStartTime = curTime;
1237        }
1238        if (displayStartTime != 0) {
1239            reportLaunchTimeLocked(curTime);
1240        }
1241        mStackSupervisor.sendWaitingVisibleReportLocked(this);
1242        startTime = 0;
1243        finishLaunchTickingLocked();
1244        if (task != null) {
1245            task.hasBeenVisible = true;
1246        }
1247    }
1248
1249    void windowsVisibleLocked() {
1250        mStackSupervisor.reportActivityVisibleLocked(this);
1251        if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsVisibleLocked(): " + this);
1252        if (!nowVisible) {
1253            nowVisible = true;
1254            lastVisibleTime = SystemClock.uptimeMillis();
1255            if (!idle) {
1256                // Instead of doing the full stop routine here, let's just hide any activities
1257                // we now can, and let them stop when the normal idle happens.
1258                mStackSupervisor.processStoppingActivitiesLocked(false);
1259            } else {
1260                // If this activity was already idle, then we now need to make sure we perform
1261                // the full stop of any activities that are waiting to do so. This is because
1262                // we won't do that while they are still waiting for this one to become visible.
1263                final int size = mStackSupervisor.mWaitingVisibleActivities.size();
1264                if (size > 0) {
1265                    for (int i = 0; i < size; i++) {
1266                        ActivityRecord r = mStackSupervisor.mWaitingVisibleActivities.get(i);
1267                        if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "Was waiting for visible: " + r);
1268                    }
1269                    mStackSupervisor.mWaitingVisibleActivities.clear();
1270                    mStackSupervisor.scheduleIdleLocked();
1271                }
1272            }
1273            service.scheduleAppGcsLocked();
1274        }
1275    }
1276
1277    ActivityRecord getWaitingHistoryRecordLocked() {
1278        // First find the real culprit...  if this activity is waiting for
1279        // another activity to start or has stopped, then the key dispatching
1280        // timeout should not be caused by this.
1281        if (mStackSupervisor.mWaitingVisibleActivities.contains(this) || stopped) {
1282            final ActivityStack stack = mStackSupervisor.getFocusedStack();
1283            // Try to use the one which is closest to top.
1284            ActivityRecord r = stack.mResumedActivity;
1285            if (r == null) {
1286                r = stack.mPausingActivity;
1287            }
1288            if (r != null) {
1289                return r;
1290            }
1291        }
1292        return this;
1293    }
1294
1295    /**
1296     * This method will return true if the activity is either visible, is becoming visible, is
1297     * currently pausing, or is resumed.
1298     */
1299    public boolean isInterestingToUserLocked() {
1300        return visible || nowVisible || state == ActivityState.PAUSING ||
1301                state == ActivityState.RESUMED;
1302    }
1303
1304    public void setSleeping(boolean _sleeping) {
1305        if (sleeping == _sleeping) {
1306            return;
1307        }
1308        if (app != null && app.thread != null) {
1309            try {
1310                app.thread.scheduleSleeping(appToken, _sleeping);
1311                if (_sleeping && !mStackSupervisor.mGoingToSleepActivities.contains(this)) {
1312                    mStackSupervisor.mGoingToSleepActivities.add(this);
1313                }
1314                sleeping = _sleeping;
1315            } catch (RemoteException e) {
1316                Slog.w(TAG, "Exception thrown when sleeping: " + intent.getComponent(), e);
1317            }
1318        }
1319    }
1320
1321    static int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
1322        final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1323        if (r == null) {
1324            return INVALID_TASK_ID;
1325        }
1326        final TaskRecord task = r.task;
1327        final int activityNdx = task.mActivities.indexOf(r);
1328        if (activityNdx < 0 || (onlyRoot && activityNdx > task.findEffectiveRootIndex())) {
1329            return INVALID_TASK_ID;
1330        }
1331        return task.taskId;
1332    }
1333
1334    static ActivityRecord isInStackLocked(IBinder token) {
1335        final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1336        return (r != null) ? r.task.stack.isInStackLocked(r) : null;
1337    }
1338
1339    static ActivityStack getStackLocked(IBinder token) {
1340        final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1341        if (r != null) {
1342            return r.task.stack;
1343        }
1344        return null;
1345    }
1346
1347    final boolean isDestroyable() {
1348        if (finishing || app == null || state == ActivityState.DESTROYING
1349                || state == ActivityState.DESTROYED) {
1350            // This would be redundant.
1351            return false;
1352        }
1353        if (task == null || task.stack == null || this == task.stack.mResumedActivity
1354                || this == task.stack.mPausingActivity || !haveState || !stopped) {
1355            // We're not ready for this kind of thing.
1356            return false;
1357        }
1358        if (visible) {
1359            // The user would notice this!
1360            return false;
1361        }
1362        return true;
1363    }
1364
1365    private static String createImageFilename(long createTime, int taskId) {
1366        return String.valueOf(taskId) + ACTIVITY_ICON_SUFFIX + createTime +
1367                TaskPersister.IMAGE_EXTENSION;
1368    }
1369
1370    void setTaskDescription(TaskDescription _taskDescription) {
1371        Bitmap icon;
1372        if (_taskDescription.getIconFilename() == null &&
1373                (icon = _taskDescription.getIcon()) != null) {
1374            final String iconFilename = createImageFilename(createTime, task.taskId);
1375            final File iconFile = new File(TaskPersister.getUserImagesDir(userId), iconFilename);
1376            final String iconFilePath = iconFile.getAbsolutePath();
1377            service.mRecentTasks.saveImage(icon, iconFilePath);
1378            _taskDescription.setIconFilename(iconFilePath);
1379        }
1380        taskDescription = _taskDescription;
1381    }
1382
1383    void setVoiceSessionLocked(IVoiceInteractionSession session) {
1384        voiceSession = session;
1385        pendingVoiceInteractionStart = false;
1386    }
1387
1388    void clearVoiceSessionLocked() {
1389        voiceSession = null;
1390        pendingVoiceInteractionStart = false;
1391    }
1392
1393    void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
1394        out.attribute(null, ATTR_ID, String.valueOf(createTime));
1395        out.attribute(null, ATTR_LAUNCHEDFROMUID, String.valueOf(launchedFromUid));
1396        if (launchedFromPackage != null) {
1397            out.attribute(null, ATTR_LAUNCHEDFROMPACKAGE, launchedFromPackage);
1398        }
1399        if (resolvedType != null) {
1400            out.attribute(null, ATTR_RESOLVEDTYPE, resolvedType);
1401        }
1402        out.attribute(null, ATTR_COMPONENTSPECIFIED, String.valueOf(componentSpecified));
1403        out.attribute(null, ATTR_USERID, String.valueOf(userId));
1404
1405        if (taskDescription != null) {
1406            taskDescription.saveToXml(out);
1407        }
1408
1409        out.startTag(null, TAG_INTENT);
1410        intent.saveToXml(out);
1411        out.endTag(null, TAG_INTENT);
1412
1413        if (isPersistable() && persistentState != null) {
1414            out.startTag(null, TAG_PERSISTABLEBUNDLE);
1415            persistentState.saveToXml(out);
1416            out.endTag(null, TAG_PERSISTABLEBUNDLE);
1417        }
1418    }
1419
1420    static ActivityRecord restoreFromXml(XmlPullParser in,
1421            ActivityStackSupervisor stackSupervisor) throws IOException, XmlPullParserException {
1422        Intent intent = null;
1423        PersistableBundle persistentState = null;
1424        int launchedFromUid = 0;
1425        String launchedFromPackage = null;
1426        String resolvedType = null;
1427        boolean componentSpecified = false;
1428        int userId = 0;
1429        long createTime = -1;
1430        final int outerDepth = in.getDepth();
1431        TaskDescription taskDescription = new TaskDescription();
1432
1433        for (int attrNdx = in.getAttributeCount() - 1; attrNdx >= 0; --attrNdx) {
1434            final String attrName = in.getAttributeName(attrNdx);
1435            final String attrValue = in.getAttributeValue(attrNdx);
1436            if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG,
1437                        "ActivityRecord: attribute name=" + attrName + " value=" + attrValue);
1438            if (ATTR_ID.equals(attrName)) {
1439                createTime = Long.valueOf(attrValue);
1440            } else if (ATTR_LAUNCHEDFROMUID.equals(attrName)) {
1441                launchedFromUid = Integer.parseInt(attrValue);
1442            } else if (ATTR_LAUNCHEDFROMPACKAGE.equals(attrName)) {
1443                launchedFromPackage = attrValue;
1444            } else if (ATTR_RESOLVEDTYPE.equals(attrName)) {
1445                resolvedType = attrValue;
1446            } else if (ATTR_COMPONENTSPECIFIED.equals(attrName)) {
1447                componentSpecified = Boolean.valueOf(attrValue);
1448            } else if (ATTR_USERID.equals(attrName)) {
1449                userId = Integer.parseInt(attrValue);
1450            } else if (attrName.startsWith(TaskDescription.ATTR_TASKDESCRIPTION_PREFIX)) {
1451                taskDescription.restoreFromXml(attrName, attrValue);
1452            } else {
1453                Log.d(TAG, "Unknown ActivityRecord attribute=" + attrName);
1454            }
1455        }
1456
1457        int event;
1458        while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
1459                (event != XmlPullParser.END_TAG || in.getDepth() >= outerDepth)) {
1460            if (event == XmlPullParser.START_TAG) {
1461                final String name = in.getName();
1462                if (TaskPersister.DEBUG)
1463                        Slog.d(TaskPersister.TAG, "ActivityRecord: START_TAG name=" + name);
1464                if (TAG_INTENT.equals(name)) {
1465                    intent = Intent.restoreFromXml(in);
1466                    if (TaskPersister.DEBUG)
1467                            Slog.d(TaskPersister.TAG, "ActivityRecord: intent=" + intent);
1468                } else if (TAG_PERSISTABLEBUNDLE.equals(name)) {
1469                    persistentState = PersistableBundle.restoreFromXml(in);
1470                    if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG,
1471                            "ActivityRecord: persistentState=" + persistentState);
1472                } else {
1473                    Slog.w(TAG, "restoreActivity: unexpected name=" + name);
1474                    XmlUtils.skipCurrentTag(in);
1475                }
1476            }
1477        }
1478
1479        if (intent == null) {
1480            throw new XmlPullParserException("restoreActivity error intent=" + intent);
1481        }
1482
1483        final ActivityManagerService service = stackSupervisor.mService;
1484        final ActivityInfo aInfo = stackSupervisor.resolveActivity(intent, resolvedType, 0, null,
1485                userId);
1486        if (aInfo == null) {
1487            throw new XmlPullParserException("restoreActivity resolver error. Intent=" + intent +
1488                    " resolvedType=" + resolvedType);
1489        }
1490        final ActivityRecord r = new ActivityRecord(service, /*caller*/null, launchedFromUid,
1491                launchedFromPackage, intent, resolvedType, aInfo, service.getConfiguration(),
1492                null, null, 0, componentSpecified, false, stackSupervisor, null, null, null);
1493
1494        r.persistentState = persistentState;
1495        r.taskDescription = taskDescription;
1496        r.createTime = createTime;
1497
1498        return r;
1499    }
1500
1501    private static String activityTypeToString(int type) {
1502        switch (type) {
1503            case APPLICATION_ACTIVITY_TYPE: return "APPLICATION_ACTIVITY_TYPE";
1504            case HOME_ACTIVITY_TYPE: return "HOME_ACTIVITY_TYPE";
1505            case RECENTS_ACTIVITY_TYPE: return "RECENTS_ACTIVITY_TYPE";
1506            default: return Integer.toString(type);
1507        }
1508    }
1509
1510    @Override
1511    public String toString() {
1512        if (stringName != null) {
1513            return stringName + " t" + (task == null ? INVALID_TASK_ID : task.taskId) +
1514                    (finishing ? " f}" : "}");
1515        }
1516        StringBuilder sb = new StringBuilder(128);
1517        sb.append("ActivityRecord{");
1518        sb.append(Integer.toHexString(System.identityHashCode(this)));
1519        sb.append(" u");
1520        sb.append(userId);
1521        sb.append(' ');
1522        sb.append(intent.getComponent().flattenToShortString());
1523        stringName = sb.toString();
1524        return toString();
1525    }
1526}
1527