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