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