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