OSDN Git Service

resolve merge conflicts of 56a2b529373b to nyc-dev am: d7dcc3e227 am: 34377e0357
[android-x86/frameworks-base.git] / services / core / java / com / android / server / am / ActivityRecord.java
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             fullscreen = ent != null && !ent.array.getBoolean(
715                     com.android.internal.R.styleable.Window_windowIsFloating, false)
716                     && !translucent;
717             noDisplay = ent != null && ent.array.getBoolean(
718                     com.android.internal.R.styleable.Window_windowNoDisplay, false);
719
720             setActivityType(_componentSpecified, _launchedFromUid, _intent, sourceRecord);
721
722             immersive = (aInfo.flags & ActivityInfo.FLAG_IMMERSIVE) != 0;
723
724             requestedVrComponent = (aInfo.requestedVrComponent == null) ?
725                     null : ComponentName.unflattenFromString(aInfo.requestedVrComponent);
726         } else {
727             realActivity = null;
728             taskAffinity = null;
729             stateNotNeeded = false;
730             appInfo = null;
731             processName = null;
732             packageName = null;
733             fullscreen = true;
734             noDisplay = false;
735             mActivityType = APPLICATION_ACTIVITY_TYPE;
736             immersive = false;
737             requestedVrComponent  = null;
738         }
739     }
740
741     private boolean isHomeIntent(Intent intent) {
742         return Intent.ACTION_MAIN.equals(intent.getAction())
743                 && intent.hasCategory(Intent.CATEGORY_HOME)
744                 && intent.getCategories().size() == 1
745                 && intent.getData() == null
746                 && intent.getType() == null;
747     }
748
749     static boolean isMainIntent(Intent intent) {
750         return Intent.ACTION_MAIN.equals(intent.getAction())
751                 && intent.hasCategory(Intent.CATEGORY_LAUNCHER)
752                 && intent.getCategories().size() == 1
753                 && intent.getData() == null
754                 && intent.getType() == null;
755     }
756
757     private boolean canLaunchHomeActivity(int uid, ActivityRecord sourceRecord) {
758         if (uid == Process.myUid() || uid == 0) {
759             // System process can launch home activity.
760             return true;
761         }
762         // Resolver activity can launch home activity.
763         return sourceRecord != null && sourceRecord.isResolverActivity();
764     }
765
766     private void setActivityType(boolean componentSpecified,
767             int launchedFromUid, Intent intent, ActivityRecord sourceRecord) {
768         if ((!componentSpecified || canLaunchHomeActivity(launchedFromUid, sourceRecord))
769                 && isHomeIntent(intent) && !isResolverActivity()) {
770             // This sure looks like a home activity!
771             mActivityType = HOME_ACTIVITY_TYPE;
772         } else if (realActivity.getClassName().contains(RECENTS_PACKAGE_NAME)) {
773             mActivityType = RECENTS_ACTIVITY_TYPE;
774         } else {
775             mActivityType = APPLICATION_ACTIVITY_TYPE;
776         }
777     }
778
779     void setTask(TaskRecord newTask, TaskRecord taskToAffiliateWith) {
780         if (task != null && task.removeActivity(this) && task != newTask && task.stack != null) {
781             task.stack.removeTask(task, "setTask");
782         }
783         task = newTask;
784         setTaskToAffiliateWith(taskToAffiliateWith);
785     }
786
787     void setTaskToAffiliateWith(TaskRecord taskToAffiliateWith) {
788         if (taskToAffiliateWith != null &&
789                 launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE &&
790                 launchMode != ActivityInfo.LAUNCH_SINGLE_TASK) {
791             task.setTaskToAffiliateWith(taskToAffiliateWith);
792         }
793     }
794
795     boolean changeWindowTranslucency(boolean toOpaque) {
796         if (fullscreen == toOpaque) {
797             return false;
798         }
799
800         // Keep track of the number of fullscreen activities in this task.
801         task.numFullscreen += toOpaque ? +1 : -1;
802
803         fullscreen = toOpaque;
804         return true;
805     }
806
807     void putInHistory() {
808         if (!inHistory) {
809             inHistory = true;
810         }
811     }
812
813     void takeFromHistory() {
814         if (inHistory) {
815             inHistory = false;
816             if (task != null && !finishing) {
817                 task = null;
818             }
819             clearOptionsLocked();
820         }
821     }
822
823     boolean isInHistory() {
824         return inHistory;
825     }
826
827     boolean isInStackLocked() {
828         return task != null && task.stack != null && task.stack.isInStackLocked(this) != null;
829     }
830
831     boolean isHomeActivity() {
832         return mActivityType == HOME_ACTIVITY_TYPE;
833     }
834
835     boolean isRecentsActivity() {
836         return mActivityType == RECENTS_ACTIVITY_TYPE;
837     }
838
839     boolean isApplicationActivity() {
840         return mActivityType == APPLICATION_ACTIVITY_TYPE;
841     }
842
843     boolean isPersistable() {
844         return (info.persistableMode == ActivityInfo.PERSIST_ROOT_ONLY ||
845                 info.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS) &&
846                 (intent == null ||
847                         (intent.getFlags() & Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS) == 0);
848     }
849
850     boolean isFocusable() {
851         return StackId.canReceiveKeys(task.stack.mStackId) || isAlwaysFocusable();
852     }
853
854     boolean isResizeable() {
855         return !isHomeActivity() && ActivityInfo.isResizeableMode(info.resizeMode);
856     }
857
858     boolean isResizeableOrForced() {
859         return !isHomeActivity() && (isResizeable() || service.mForceResizableActivities);
860     }
861
862     boolean isNonResizableOrForced() {
863         return !isHomeActivity() && info.resizeMode != RESIZE_MODE_RESIZEABLE
864                 && info.resizeMode != RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
865     }
866
867     boolean supportsPictureInPicture() {
868         return !isHomeActivity() && info.resizeMode == RESIZE_MODE_RESIZEABLE_AND_PIPABLE;
869     }
870
871     boolean canGoInDockedStack() {
872         return !isHomeActivity()
873                 && (isResizeableOrForced() || info.resizeMode == RESIZE_MODE_CROP_WINDOWS);
874     }
875
876     boolean isAlwaysFocusable() {
877         return (info.flags & FLAG_ALWAYS_FOCUSABLE) != 0;
878     }
879
880     void makeFinishingLocked() {
881         if (!finishing) {
882             if (task != null && task.stack != null
883                     && this == task.stack.getVisibleBehindActivity()) {
884                 // A finishing activity should not remain as visible in the background
885                 mStackSupervisor.requestVisibleBehindLocked(this, false);
886             }
887             finishing = true;
888             if (stopped) {
889                 clearOptionsLocked();
890             }
891         }
892     }
893
894     UriPermissionOwner getUriPermissionsLocked() {
895         if (uriPermissions == null) {
896             uriPermissions = new UriPermissionOwner(service, this);
897         }
898         return uriPermissions;
899     }
900
901     void addResultLocked(ActivityRecord from, String resultWho,
902             int requestCode, int resultCode,
903             Intent resultData) {
904         ActivityResult r = new ActivityResult(from, resultWho,
905                 requestCode, resultCode, resultData);
906         if (results == null) {
907             results = new ArrayList<ResultInfo>();
908         }
909         results.add(r);
910     }
911
912     void removeResultsLocked(ActivityRecord from, String resultWho,
913             int requestCode) {
914         if (results != null) {
915             for (int i=results.size()-1; i>=0; i--) {
916                 ActivityResult r = (ActivityResult)results.get(i);
917                 if (r.mFrom != from) continue;
918                 if (r.mResultWho == null) {
919                     if (resultWho != null) continue;
920                 } else {
921                     if (!r.mResultWho.equals(resultWho)) continue;
922                 }
923                 if (r.mRequestCode != requestCode) continue;
924
925                 results.remove(i);
926             }
927         }
928     }
929
930     void addNewIntentLocked(ReferrerIntent intent) {
931         if (newIntents == null) {
932             newIntents = new ArrayList<>();
933         }
934         newIntents.add(intent);
935     }
936
937     /**
938      * Deliver a new Intent to an existing activity, so that its onNewIntent()
939      * method will be called at the proper time.
940      */
941     final void deliverNewIntentLocked(int callingUid, Intent intent, String referrer) {
942         // The activity now gets access to the data associated with this Intent.
943         service.grantUriPermissionFromIntentLocked(callingUid, packageName,
944                 intent, getUriPermissionsLocked(), userId);
945         final ReferrerIntent rintent = new ReferrerIntent(intent, referrer);
946         boolean unsent = true;
947         final ActivityStack stack = task.stack;
948         final boolean isTopActivityInStack =
949                 stack != null && stack.topRunningActivityLocked() == this;
950         final boolean isTopActivityWhileSleeping =
951                 service.isSleepingLocked() && isTopActivityInStack;
952
953         // We want to immediately deliver the intent to the activity if:
954         // - It is currently resumed or paused. i.e. it is currently visible to the user and we want
955         //   the user to see the visual effects caused by the intent delivery now.
956         // - The device is sleeping and it is the top activity behind the lock screen (b/6700897).
957         if ((state == ActivityState.RESUMED || state == ActivityState.PAUSED
958                 || isTopActivityWhileSleeping) && app != null && app.thread != null) {
959             try {
960                 ArrayList<ReferrerIntent> ar = new ArrayList<>(1);
961                 ar.add(rintent);
962                 app.thread.scheduleNewIntent(
963                         ar, appToken, state == ActivityState.PAUSED /* andPause */);
964                 unsent = false;
965             } catch (RemoteException e) {
966                 Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
967             } catch (NullPointerException e) {
968                 Slog.w(TAG, "Exception thrown sending new intent to " + this, e);
969             }
970         }
971         if (unsent) {
972             addNewIntentLocked(rintent);
973         }
974     }
975
976     void updateOptionsLocked(ActivityOptions options) {
977         if (options != null) {
978             if (pendingOptions != null) {
979                 pendingOptions.abort();
980             }
981             pendingOptions = options;
982         }
983     }
984
985     void applyOptionsLocked() {
986         if (pendingOptions != null
987                 && pendingOptions.getAnimationType() != ActivityOptions.ANIM_SCENE_TRANSITION) {
988             final int animationType = pendingOptions.getAnimationType();
989             switch (animationType) {
990                 case ActivityOptions.ANIM_CUSTOM:
991                     service.mWindowManager.overridePendingAppTransition(
992                             pendingOptions.getPackageName(),
993                             pendingOptions.getCustomEnterResId(),
994                             pendingOptions.getCustomExitResId(),
995                             pendingOptions.getOnAnimationStartListener());
996                     break;
997                 case ActivityOptions.ANIM_CLIP_REVEAL:
998                     service.mWindowManager.overridePendingAppTransitionClipReveal(
999                             pendingOptions.getStartX(), pendingOptions.getStartY(),
1000                             pendingOptions.getWidth(), pendingOptions.getHeight());
1001                     if (intent.getSourceBounds() == null) {
1002                         intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1003                                 pendingOptions.getStartY(),
1004                                 pendingOptions.getStartX()+pendingOptions.getWidth(),
1005                                 pendingOptions.getStartY()+pendingOptions.getHeight()));
1006                     }
1007                     break;
1008                 case ActivityOptions.ANIM_SCALE_UP:
1009                     service.mWindowManager.overridePendingAppTransitionScaleUp(
1010                             pendingOptions.getStartX(), pendingOptions.getStartY(),
1011                             pendingOptions.getWidth(), pendingOptions.getHeight());
1012                     if (intent.getSourceBounds() == null) {
1013                         intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1014                                 pendingOptions.getStartY(),
1015                                 pendingOptions.getStartX()+pendingOptions.getWidth(),
1016                                 pendingOptions.getStartY()+pendingOptions.getHeight()));
1017                     }
1018                     break;
1019                 case ActivityOptions.ANIM_THUMBNAIL_SCALE_UP:
1020                 case ActivityOptions.ANIM_THUMBNAIL_SCALE_DOWN:
1021                     boolean scaleUp = (animationType == ActivityOptions.ANIM_THUMBNAIL_SCALE_UP);
1022                     service.mWindowManager.overridePendingAppTransitionThumb(
1023                             pendingOptions.getThumbnail(),
1024                             pendingOptions.getStartX(), pendingOptions.getStartY(),
1025                             pendingOptions.getOnAnimationStartListener(),
1026                             scaleUp);
1027                     if (intent.getSourceBounds() == null) {
1028                         intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1029                                 pendingOptions.getStartY(),
1030                                 pendingOptions.getStartX()
1031                                         + pendingOptions.getThumbnail().getWidth(),
1032                                 pendingOptions.getStartY()
1033                                         + pendingOptions.getThumbnail().getHeight()));
1034                     }
1035                     break;
1036                 case ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_UP:
1037                 case ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_DOWN:
1038                     final AppTransitionAnimationSpec[] specs = pendingOptions.getAnimSpecs();
1039                     if (animationType == ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_DOWN
1040                             && specs != null) {
1041                         service.mWindowManager.overridePendingAppTransitionMultiThumb(
1042                                 specs, pendingOptions.getOnAnimationStartListener(),
1043                                 pendingOptions.getAnimationFinishedListener(), false);
1044                     } else {
1045                         service.mWindowManager.overridePendingAppTransitionAspectScaledThumb(
1046                                 pendingOptions.getThumbnail(),
1047                                 pendingOptions.getStartX(), pendingOptions.getStartY(),
1048                                 pendingOptions.getWidth(), pendingOptions.getHeight(),
1049                                 pendingOptions.getOnAnimationStartListener(),
1050                                 (animationType == ActivityOptions.ANIM_THUMBNAIL_ASPECT_SCALE_UP));
1051                         if (intent.getSourceBounds() == null) {
1052                             intent.setSourceBounds(new Rect(pendingOptions.getStartX(),
1053                                     pendingOptions.getStartY(),
1054                                     pendingOptions.getStartX() + pendingOptions.getWidth(),
1055                                     pendingOptions.getStartY() + pendingOptions.getHeight()));
1056                         }
1057                     }
1058                     break;
1059                 default:
1060                     Slog.e(TAG, "applyOptionsLocked: Unknown animationType=" + animationType);
1061                     break;
1062             }
1063             pendingOptions = null;
1064         }
1065     }
1066
1067     ActivityOptions getOptionsForTargetActivityLocked() {
1068         return pendingOptions != null ? pendingOptions.forTargetActivity() : null;
1069     }
1070
1071     void clearOptionsLocked() {
1072         if (pendingOptions != null) {
1073             pendingOptions.abort();
1074             pendingOptions = null;
1075         }
1076     }
1077
1078     ActivityOptions takeOptionsLocked() {
1079         ActivityOptions opts = pendingOptions;
1080         pendingOptions = null;
1081         return opts;
1082     }
1083
1084     void removeUriPermissionsLocked() {
1085         if (uriPermissions != null) {
1086             uriPermissions.removeUriPermissionsLocked();
1087             uriPermissions = null;
1088         }
1089     }
1090
1091     void pauseKeyDispatchingLocked() {
1092         if (!keysPaused) {
1093             keysPaused = true;
1094             service.mWindowManager.pauseKeyDispatching(appToken);
1095         }
1096     }
1097
1098     void resumeKeyDispatchingLocked() {
1099         if (keysPaused) {
1100             keysPaused = false;
1101             service.mWindowManager.resumeKeyDispatching(appToken);
1102         }
1103     }
1104
1105     void updateThumbnailLocked(Bitmap newThumbnail, CharSequence description) {
1106         if (newThumbnail != null) {
1107             if (DEBUG_THUMBNAILS) Slog.i(TAG_THUMBNAILS,
1108                     "Setting thumbnail of " + this + " to " + newThumbnail);
1109             boolean thumbnailUpdated = task.setLastThumbnailLocked(newThumbnail);
1110             if (thumbnailUpdated && isPersistable()) {
1111                 mStackSupervisor.mService.notifyTaskPersisterLocked(task, false);
1112             }
1113         }
1114         task.lastDescription = description;
1115     }
1116
1117     void startLaunchTickingLocked() {
1118         if (ActivityManagerService.IS_USER_BUILD) {
1119             return;
1120         }
1121         if (launchTickTime == 0) {
1122             launchTickTime = SystemClock.uptimeMillis();
1123             continueLaunchTickingLocked();
1124         }
1125     }
1126
1127     boolean continueLaunchTickingLocked() {
1128         if (launchTickTime == 0) {
1129             return false;
1130         }
1131
1132         final ActivityStack stack = task.stack;
1133         if (stack == null) {
1134             return false;
1135         }
1136
1137         Message msg = stack.mHandler.obtainMessage(ActivityStack.LAUNCH_TICK_MSG, this);
1138         stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
1139         stack.mHandler.sendMessageDelayed(msg, ActivityStack.LAUNCH_TICK);
1140         return true;
1141     }
1142
1143     void finishLaunchTickingLocked() {
1144         launchTickTime = 0;
1145         final ActivityStack stack = task.stack;
1146         if (stack != null) {
1147             stack.mHandler.removeMessages(ActivityStack.LAUNCH_TICK_MSG);
1148         }
1149     }
1150
1151     // IApplicationToken
1152
1153     public boolean mayFreezeScreenLocked(ProcessRecord app) {
1154         // Only freeze the screen if this activity is currently attached to
1155         // an application, and that application is not blocked or unresponding.
1156         // In any other case, we can't count on getting the screen unfrozen,
1157         // so it is best to leave as-is.
1158         return app != null && !app.crashing && !app.notResponding;
1159     }
1160
1161     public void startFreezingScreenLocked(ProcessRecord app, int configChanges) {
1162         if (mayFreezeScreenLocked(app)) {
1163             service.mWindowManager.startAppFreezingScreen(appToken, configChanges);
1164         }
1165     }
1166
1167     public void stopFreezingScreenLocked(boolean force) {
1168         if (force || frozenBeforeDestroy) {
1169             frozenBeforeDestroy = false;
1170             service.mWindowManager.stopAppFreezingScreen(appToken, force);
1171         }
1172     }
1173
1174     public void reportFullyDrawnLocked() {
1175         final long curTime = SystemClock.uptimeMillis();
1176         if (displayStartTime != 0) {
1177             reportLaunchTimeLocked(curTime);
1178         }
1179         final ActivityStack stack = task.stack;
1180         if (fullyDrawnStartTime != 0 && stack != null) {
1181             final long thisTime = curTime - fullyDrawnStartTime;
1182             final long totalTime = stack.mFullyDrawnStartTime != 0
1183                     ? (curTime - stack.mFullyDrawnStartTime) : thisTime;
1184             if (SHOW_ACTIVITY_START_TIME) {
1185                 Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "drawing", 0);
1186                 EventLog.writeEvent(EventLogTags.AM_ACTIVITY_FULLY_DRAWN_TIME,
1187                         userId, System.identityHashCode(this), shortComponentName,
1188                         thisTime, totalTime);
1189                 StringBuilder sb = service.mStringBuilder;
1190                 sb.setLength(0);
1191                 sb.append("Fully drawn ");
1192                 sb.append(shortComponentName);
1193                 sb.append(": ");
1194                 TimeUtils.formatDuration(thisTime, sb);
1195                 if (thisTime != totalTime) {
1196                     sb.append(" (total ");
1197                     TimeUtils.formatDuration(totalTime, sb);
1198                     sb.append(")");
1199                 }
1200                 Log.i(TAG, sb.toString());
1201             }
1202             if (totalTime > 0) {
1203                 //service.mUsageStatsService.noteFullyDrawnTime(realActivity, (int) totalTime);
1204             }
1205             stack.mFullyDrawnStartTime = 0;
1206         }
1207         fullyDrawnStartTime = 0;
1208     }
1209
1210     private void reportLaunchTimeLocked(final long curTime) {
1211         final ActivityStack stack = task.stack;
1212         if (stack == null) {
1213             return;
1214         }
1215         final long thisTime = curTime - displayStartTime;
1216         final long totalTime = stack.mLaunchStartTime != 0
1217                 ? (curTime - stack.mLaunchStartTime) : thisTime;
1218         if (SHOW_ACTIVITY_START_TIME) {
1219             Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, "launching: " + packageName, 0);
1220             EventLog.writeEvent(EventLogTags.AM_ACTIVITY_LAUNCH_TIME,
1221                     userId, System.identityHashCode(this), shortComponentName,
1222                     thisTime, totalTime);
1223             StringBuilder sb = service.mStringBuilder;
1224             sb.setLength(0);
1225             sb.append("Displayed ");
1226             sb.append(shortComponentName);
1227             sb.append(": ");
1228             TimeUtils.formatDuration(thisTime, sb);
1229             if (thisTime != totalTime) {
1230                 sb.append(" (total ");
1231                 TimeUtils.formatDuration(totalTime, sb);
1232                 sb.append(")");
1233             }
1234             Log.i(TAG, sb.toString());
1235         }
1236         mStackSupervisor.reportActivityLaunchedLocked(false, this, thisTime, totalTime);
1237         if (totalTime > 0) {
1238             //service.mUsageStatsService.noteLaunchTime(realActivity, (int)totalTime);
1239         }
1240         displayStartTime = 0;
1241         stack.mLaunchStartTime = 0;
1242     }
1243
1244     void windowsDrawnLocked() {
1245         mStackSupervisor.mActivityMetricsLogger.notifyWindowsDrawn();
1246         if (displayStartTime != 0) {
1247             reportLaunchTimeLocked(SystemClock.uptimeMillis());
1248         }
1249         mStackSupervisor.sendWaitingVisibleReportLocked(this);
1250         startTime = 0;
1251         finishLaunchTickingLocked();
1252         if (task != null) {
1253             task.hasBeenVisible = true;
1254         }
1255     }
1256
1257     void windowsVisibleLocked() {
1258         mStackSupervisor.reportActivityVisibleLocked(this);
1259         if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "windowsVisibleLocked(): " + this);
1260         if (!nowVisible) {
1261             nowVisible = true;
1262             lastVisibleTime = SystemClock.uptimeMillis();
1263             if (!idle) {
1264                 // Instead of doing the full stop routine here, let's just hide any activities
1265                 // we now can, and let them stop when the normal idle happens.
1266                 mStackSupervisor.processStoppingActivitiesLocked(false);
1267             } else {
1268                 // If this activity was already idle, then we now need to make sure we perform
1269                 // the full stop of any activities that are waiting to do so. This is because
1270                 // we won't do that while they are still waiting for this one to become visible.
1271                 final int size = mStackSupervisor.mWaitingVisibleActivities.size();
1272                 if (size > 0) {
1273                     for (int i = 0; i < size; i++) {
1274                         ActivityRecord r = mStackSupervisor.mWaitingVisibleActivities.get(i);
1275                         if (DEBUG_SWITCH) Log.v(TAG_SWITCH, "Was waiting for visible: " + r);
1276                     }
1277                     mStackSupervisor.mWaitingVisibleActivities.clear();
1278                     mStackSupervisor.scheduleIdleLocked();
1279                 }
1280             }
1281             service.scheduleAppGcsLocked();
1282         }
1283     }
1284
1285     ActivityRecord getWaitingHistoryRecordLocked() {
1286         // First find the real culprit...  if this activity is waiting for
1287         // another activity to start or has stopped, then the key dispatching
1288         // timeout should not be caused by this.
1289         if (mStackSupervisor.mWaitingVisibleActivities.contains(this) || stopped) {
1290             final ActivityStack stack = mStackSupervisor.getFocusedStack();
1291             // Try to use the one which is closest to top.
1292             ActivityRecord r = stack.mResumedActivity;
1293             if (r == null) {
1294                 r = stack.mPausingActivity;
1295             }
1296             if (r != null) {
1297                 return r;
1298             }
1299         }
1300         return this;
1301     }
1302
1303     /**
1304      * This method will return true if the activity is either visible, is becoming visible, is
1305      * currently pausing, or is resumed.
1306      */
1307     public boolean isInterestingToUserLocked() {
1308         return visible || nowVisible || state == ActivityState.PAUSING ||
1309                 state == ActivityState.RESUMED;
1310     }
1311
1312     void setSleeping(boolean _sleeping) {
1313         setSleeping(_sleeping, false);
1314     }
1315
1316     void setSleeping(boolean _sleeping, boolean force) {
1317         if (!force && sleeping == _sleeping) {
1318             return;
1319         }
1320         if (app != null && app.thread != null) {
1321             try {
1322                 app.thread.scheduleSleeping(appToken, _sleeping);
1323                 if (_sleeping && !mStackSupervisor.mGoingToSleepActivities.contains(this)) {
1324                     mStackSupervisor.mGoingToSleepActivities.add(this);
1325                 }
1326                 sleeping = _sleeping;
1327             } catch (RemoteException e) {
1328                 Slog.w(TAG, "Exception thrown when sleeping: " + intent.getComponent(), e);
1329             }
1330         }
1331     }
1332
1333     static int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
1334         final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1335         if (r == null) {
1336             return INVALID_TASK_ID;
1337         }
1338         final TaskRecord task = r.task;
1339         final int activityNdx = task.mActivities.indexOf(r);
1340         if (activityNdx < 0 || (onlyRoot && activityNdx > task.findEffectiveRootIndex())) {
1341             return INVALID_TASK_ID;
1342         }
1343         return task.taskId;
1344     }
1345
1346     static ActivityRecord isInStackLocked(IBinder token) {
1347         final ActivityRecord r = ActivityRecord.forTokenLocked(token);
1348         return (r != null) ? r.task.stack.isInStackLocked(r) : null;
1349     }
1350
1351     static ActivityStack getStackLocked(IBinder token) {
1352         final ActivityRecord r = ActivityRecord.isInStackLocked(token);
1353         if (r != null) {
1354             return r.task.stack;
1355         }
1356         return null;
1357     }
1358
1359     final boolean isDestroyable() {
1360         if (finishing || app == null || state == ActivityState.DESTROYING
1361                 || state == ActivityState.DESTROYED) {
1362             // This would be redundant.
1363             return false;
1364         }
1365         if (task == null || task.stack == null || this == task.stack.mResumedActivity
1366                 || this == task.stack.mPausingActivity || !haveState || !stopped) {
1367             // We're not ready for this kind of thing.
1368             return false;
1369         }
1370         if (visible) {
1371             // The user would notice this!
1372             return false;
1373         }
1374         return true;
1375     }
1376
1377     private static String createImageFilename(long createTime, int taskId) {
1378         return String.valueOf(taskId) + ACTIVITY_ICON_SUFFIX + createTime +
1379                 TaskPersister.IMAGE_EXTENSION;
1380     }
1381
1382     void setTaskDescription(TaskDescription _taskDescription) {
1383         Bitmap icon;
1384         if (_taskDescription.getIconFilename() == null &&
1385                 (icon = _taskDescription.getIcon()) != null) {
1386             final String iconFilename = createImageFilename(createTime, task.taskId);
1387             final File iconFile = new File(TaskPersister.getUserImagesDir(userId), iconFilename);
1388             final String iconFilePath = iconFile.getAbsolutePath();
1389             service.mRecentTasks.saveImage(icon, iconFilePath);
1390             _taskDescription.setIconFilename(iconFilePath);
1391         }
1392         taskDescription = _taskDescription;
1393     }
1394
1395     void setVoiceSessionLocked(IVoiceInteractionSession session) {
1396         voiceSession = session;
1397         pendingVoiceInteractionStart = false;
1398     }
1399
1400     void clearVoiceSessionLocked() {
1401         voiceSession = null;
1402         pendingVoiceInteractionStart = false;
1403     }
1404
1405     void showStartingWindow(ActivityRecord prev, boolean createIfNeeded) {
1406         final CompatibilityInfo compatInfo =
1407                 service.compatibilityInfoForPackageLocked(info.applicationInfo);
1408         final boolean shown = service.mWindowManager.setAppStartingWindow(
1409                 appToken, packageName, theme, compatInfo, nonLocalizedLabel, labelRes, icon,
1410                 logo, windowFlags, prev != null ? prev.appToken : null, createIfNeeded);
1411         if (shown) {
1412             mStartingWindowState = STARTING_WINDOW_SHOWN;
1413         }
1414     }
1415
1416     void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
1417         out.attribute(null, ATTR_ID, String.valueOf(createTime));
1418         out.attribute(null, ATTR_LAUNCHEDFROMUID, String.valueOf(launchedFromUid));
1419         if (launchedFromPackage != null) {
1420             out.attribute(null, ATTR_LAUNCHEDFROMPACKAGE, launchedFromPackage);
1421         }
1422         if (resolvedType != null) {
1423             out.attribute(null, ATTR_RESOLVEDTYPE, resolvedType);
1424         }
1425         out.attribute(null, ATTR_COMPONENTSPECIFIED, String.valueOf(componentSpecified));
1426         out.attribute(null, ATTR_USERID, String.valueOf(userId));
1427
1428         if (taskDescription != null) {
1429             taskDescription.saveToXml(out);
1430         }
1431
1432         out.startTag(null, TAG_INTENT);
1433         intent.saveToXml(out);
1434         out.endTag(null, TAG_INTENT);
1435
1436         if (isPersistable() && persistentState != null) {
1437             out.startTag(null, TAG_PERSISTABLEBUNDLE);
1438             persistentState.saveToXml(out);
1439             out.endTag(null, TAG_PERSISTABLEBUNDLE);
1440         }
1441     }
1442
1443     static ActivityRecord restoreFromXml(XmlPullParser in,
1444             ActivityStackSupervisor stackSupervisor) throws IOException, XmlPullParserException {
1445         Intent intent = null;
1446         PersistableBundle persistentState = null;
1447         int launchedFromUid = 0;
1448         String launchedFromPackage = null;
1449         String resolvedType = null;
1450         boolean componentSpecified = false;
1451         int userId = 0;
1452         long createTime = -1;
1453         final int outerDepth = in.getDepth();
1454         TaskDescription taskDescription = new TaskDescription();
1455
1456         for (int attrNdx = in.getAttributeCount() - 1; attrNdx >= 0; --attrNdx) {
1457             final String attrName = in.getAttributeName(attrNdx);
1458             final String attrValue = in.getAttributeValue(attrNdx);
1459             if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG,
1460                         "ActivityRecord: attribute name=" + attrName + " value=" + attrValue);
1461             if (ATTR_ID.equals(attrName)) {
1462                 createTime = Long.valueOf(attrValue);
1463             } else if (ATTR_LAUNCHEDFROMUID.equals(attrName)) {
1464                 launchedFromUid = Integer.parseInt(attrValue);
1465             } else if (ATTR_LAUNCHEDFROMPACKAGE.equals(attrName)) {
1466                 launchedFromPackage = attrValue;
1467             } else if (ATTR_RESOLVEDTYPE.equals(attrName)) {
1468                 resolvedType = attrValue;
1469             } else if (ATTR_COMPONENTSPECIFIED.equals(attrName)) {
1470                 componentSpecified = Boolean.valueOf(attrValue);
1471             } else if (ATTR_USERID.equals(attrName)) {
1472                 userId = Integer.parseInt(attrValue);
1473             } else if (attrName.startsWith(TaskDescription.ATTR_TASKDESCRIPTION_PREFIX)) {
1474                 taskDescription.restoreFromXml(attrName, attrValue);
1475             } else {
1476                 Log.d(TAG, "Unknown ActivityRecord attribute=" + attrName);
1477             }
1478         }
1479
1480         int event;
1481         while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
1482                 (event != XmlPullParser.END_TAG || in.getDepth() >= outerDepth)) {
1483             if (event == XmlPullParser.START_TAG) {
1484                 final String name = in.getName();
1485                 if (TaskPersister.DEBUG)
1486                         Slog.d(TaskPersister.TAG, "ActivityRecord: START_TAG name=" + name);
1487                 if (TAG_INTENT.equals(name)) {
1488                     intent = Intent.restoreFromXml(in);
1489                     if (TaskPersister.DEBUG)
1490                             Slog.d(TaskPersister.TAG, "ActivityRecord: intent=" + intent);
1491                 } else if (TAG_PERSISTABLEBUNDLE.equals(name)) {
1492                     persistentState = PersistableBundle.restoreFromXml(in);
1493                     if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG,
1494                             "ActivityRecord: persistentState=" + persistentState);
1495                 } else {
1496                     Slog.w(TAG, "restoreActivity: unexpected name=" + name);
1497                     XmlUtils.skipCurrentTag(in);
1498                 }
1499             }
1500         }
1501
1502         if (intent == null) {
1503             throw new XmlPullParserException("restoreActivity error intent=" + intent);
1504         }
1505
1506         final ActivityManagerService service = stackSupervisor.mService;
1507         final ActivityInfo aInfo = stackSupervisor.resolveActivity(intent, resolvedType, 0, null,
1508                 userId);
1509         if (aInfo == null) {
1510             throw new XmlPullParserException("restoreActivity resolver error. Intent=" + intent +
1511                     " resolvedType=" + resolvedType);
1512         }
1513         final ActivityRecord r = new ActivityRecord(service, /*caller*/null, launchedFromUid,
1514                 launchedFromPackage, intent, resolvedType, aInfo, service.getConfiguration(),
1515                 null, null, 0, componentSpecified, false, stackSupervisor, null, null, null);
1516
1517         r.persistentState = persistentState;
1518         r.taskDescription = taskDescription;
1519         r.createTime = createTime;
1520
1521         return r;
1522     }
1523
1524     private static String activityTypeToString(int type) {
1525         switch (type) {
1526             case APPLICATION_ACTIVITY_TYPE: return "APPLICATION_ACTIVITY_TYPE";
1527             case HOME_ACTIVITY_TYPE: return "HOME_ACTIVITY_TYPE";
1528             case RECENTS_ACTIVITY_TYPE: return "RECENTS_ACTIVITY_TYPE";
1529             default: return Integer.toString(type);
1530         }
1531     }
1532
1533     @Override
1534     public String toString() {
1535         if (stringName != null) {
1536             return stringName + " t" + (task == null ? INVALID_TASK_ID : task.taskId) +
1537                     (finishing ? " f}" : "}");
1538         }
1539         StringBuilder sb = new StringBuilder(128);
1540         sb.append("ActivityRecord{");
1541         sb.append(Integer.toHexString(System.identityHashCode(this)));
1542         sb.append(" u");
1543         sb.append(userId);
1544         sb.append(' ');
1545         sb.append(intent.getComponent().flattenToShortString());
1546         stringName = sb.toString();
1547         return toString();
1548     }
1549 }