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 com.android.server.AttributeCache;
     20 import com.android.server.am.ActivityStack.ActivityState;
     21 
     22 import android.app.Activity;
     23 import android.content.ComponentName;
     24 import android.content.Intent;
     25 import android.content.pm.ActivityInfo;
     26 import android.content.pm.ApplicationInfo;
     27 import android.content.res.CompatibilityInfo;
     28 import android.content.res.Configuration;
     29 import android.graphics.Bitmap;
     30 import android.os.Build;
     31 import android.os.Bundle;
     32 import android.os.IBinder;
     33 import android.os.Message;
     34 import android.os.Process;
     35 import android.os.RemoteException;
     36 import android.os.SystemClock;
     37 import android.util.EventLog;
     38 import android.util.Log;
     39 import android.util.Slog;
     40 import android.util.TimeUtils;
     41 import android.view.IApplicationToken;
     42 import android.view.WindowManager;
     43 
     44 import java.io.PrintWriter;
     45 import java.lang.ref.WeakReference;
     46 import java.util.ArrayList;
     47 import java.util.HashSet;
     48 
     49 /**
     50  * An entry in the history stack, representing an activity.
     51  */
     52 final class ActivityRecord {
     53     final ActivityManagerService service; // owner
     54     final ActivityStack stack; // owner
     55     final IApplicationToken.Stub appToken; // window manager token
     56     final ActivityInfo info; // all about me
     57     final int launchedFromUid; // always the uid who started the activity.
     58     final Intent intent;    // the original intent that generated us
     59     final ComponentName realActivity;  // the intent component, or target of an alias.
     60     final String shortComponentName; // the short component name of the intent
     61     final String resolvedType; // as per original caller;
     62     final String packageName; // the package implementing intent's component
     63     final String processName; // process where this component wants to run
     64     final String taskAffinity; // as per ActivityInfo.taskAffinity
     65     final boolean stateNotNeeded; // As per ActivityInfo.flags
     66     final boolean fullscreen; // covers the full screen?
     67     final boolean noDisplay;  // activity is not displayed?
     68     final boolean componentSpecified;  // did caller specifiy an explicit component?
     69     final boolean isHomeActivity; // do we consider this to be a home activity?
     70     final String baseDir;   // where activity source (resources etc) located
     71     final String resDir;   // where public activity source (public resources etc) located
     72     final String dataDir;   // where activity data should go
     73     CharSequence nonLocalizedLabel;  // the label information from the package mgr.
     74     int labelRes;           // the label information from the package mgr.
     75     int icon;               // resource identifier of activity's icon.
     76     int theme;              // resource identifier of activity's theme.
     77     int realTheme;          // actual theme resource we will use, never 0.
     78     int windowFlags;        // custom window flags for preview window.
     79     TaskRecord task;        // the task this is in.
     80     ThumbnailHolder thumbHolder; // where our thumbnails should go.
     81     long launchTime;        // when we starting launching this activity
     82     long startTime;         // last time this activity was started
     83     long lastVisibleTime;   // last time this activity became visible
     84     long cpuTimeAtResume;   // the cpu time of host process at the time of resuming activity
     85     Configuration configuration; // configuration activity was last running in
     86     CompatibilityInfo compat;// last used compatibility mode
     87     ActivityRecord resultTo; // who started this entry, so will get our reply
     88     final String resultWho; // additional identifier for use by resultTo.
     89     final int requestCode;  // code given by requester (resultTo)
     90     ArrayList results;      // pending ActivityResult objs we have received
     91     HashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this act
     92     ArrayList newIntents;   // any pending new intents for single-top mode
     93     HashSet<ConnectionRecord> connections; // All ConnectionRecord we hold
     94     UriPermissionOwner uriPermissions; // current special URI access perms.
     95     ProcessRecord app;      // if non-null, hosting application
     96     ActivityState state;    // current state we are in
     97     Bundle  icicle;         // last saved activity state
     98     boolean frontOfTask;    // is this the root activity of its task?
     99     boolean launchFailed;   // set if a launched failed, to abort on 2nd try
    100     boolean haveState;      // have we gotten the last activity state?
    101     boolean stopped;        // is activity pause finished?
    102     boolean delayedResume;  // not yet resumed because of stopped app switches?
    103     boolean finishing;      // activity in pending finish list?
    104     boolean configDestroy;  // need to destroy due to config change?
    105     int configChangeFlags;  // which config values have changed
    106     boolean keysPaused;     // has key dispatching been paused for it?
    107     int launchMode;         // the launch mode activity attribute.
    108     boolean visible;        // does this activity's window need to be shown?
    109     boolean sleeping;       // have we told the activity to sleep?
    110     boolean waitingVisible; // true if waiting for a new act to become vis
    111     boolean nowVisible;     // is this activity's window visible?
    112     boolean thumbnailNeeded;// has someone requested a thumbnail?
    113     boolean idle;           // has the activity gone idle?
    114     boolean hasBeenLaunched;// has this activity ever been launched?
    115     boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.
    116     boolean immersive;      // immersive mode (don't interrupt if possible)
    117     boolean forceNewConfig; // force re-create with new config next time
    118 
    119     String stringName;      // for caching of toString().
    120 
    121     private boolean inHistory;  // are we in the history stack?
    122 
    123     void dump(PrintWriter pw, String prefix) {
    124         pw.print(prefix); pw.print("packageName="); pw.print(packageName);
    125                 pw.print(" processName="); pw.println(processName);
    126         pw.print(prefix); pw.print("launchedFromUid="); pw.print(launchedFromUid);
    127                 pw.print(" app="); pw.println(app);
    128         pw.print(prefix); pw.println(intent.toInsecureString());
    129         pw.print(prefix); pw.print("frontOfTask="); pw.print(frontOfTask);
    130                 pw.print(" task="); pw.println(task);
    131         pw.print(prefix); pw.print("taskAffinity="); pw.println(taskAffinity);
    132         pw.print(prefix); pw.print("realActivity=");
    133                 pw.println(realActivity.flattenToShortString());
    134         pw.print(prefix); pw.print("base="); pw.print(baseDir);
    135                 if (!resDir.equals(baseDir)) pw.print(" res="); pw.print(resDir);
    136                 pw.print(" data="); pw.println(dataDir);
    137         pw.print(prefix); pw.print("labelRes=0x");
    138                 pw.print(Integer.toHexString(labelRes));
    139                 pw.print(" icon=0x"); pw.print(Integer.toHexString(icon));
    140                 pw.print(" theme=0x"); pw.println(Integer.toHexString(theme));
    141         pw.print(prefix); pw.print("stateNotNeeded="); pw.print(stateNotNeeded);
    142                 pw.print(" componentSpecified="); pw.print(componentSpecified);
    143                 pw.print(" isHomeActivity="); pw.println(isHomeActivity);
    144         pw.print(prefix); pw.print("config="); pw.println(configuration);
    145         pw.print(prefix); pw.print("compat="); pw.println(compat);
    146         if (resultTo != null || resultWho != null) {
    147             pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
    148                     pw.print(" resultWho="); pw.print(resultWho);
    149                     pw.print(" resultCode="); pw.println(requestCode);
    150         }
    151         if (results != null) {
    152             pw.print(prefix); pw.print("results="); pw.println(results);
    153         }
    154         if (pendingResults != null) {
    155             pw.print(prefix); pw.print("pendingResults="); pw.println(pendingResults);
    156         }
    157         if (uriPermissions != null) {
    158             if (uriPermissions.readUriPermissions != null) {
    159                 pw.print(prefix); pw.print("readUriPermissions=");
    160                         pw.println(uriPermissions.readUriPermissions);
    161             }
    162             if (uriPermissions.writeUriPermissions != null) {
    163                 pw.print(prefix); pw.print("writeUriPermissions=");
    164                         pw.println(uriPermissions.writeUriPermissions);
    165             }
    166         }
    167         pw.print(prefix); pw.print("launchFailed="); pw.print(launchFailed);
    168                 pw.print(" haveState="); pw.print(haveState);
    169                 pw.print(" icicle="); pw.println(icicle);
    170         pw.print(prefix); pw.print("state="); pw.print(state);
    171                 pw.print(" stopped="); pw.print(stopped);
    172                 pw.print(" delayedResume="); pw.print(delayedResume);
    173                 pw.print(" finishing="); pw.println(finishing);
    174         pw.print(prefix); pw.print("keysPaused="); pw.print(keysPaused);
    175                 pw.print(" inHistory="); pw.print(inHistory);
    176                 pw.print(" visible="); pw.print(visible);
    177                 pw.print(" sleeping="); pw.print(sleeping);
    178                 pw.print(" idle="); pw.println(idle);
    179         pw.print(prefix); pw.print("fullscreen="); pw.print(fullscreen);
    180                 pw.print(" noDisplay="); pw.print(noDisplay);
    181                 pw.print(" immersive="); pw.print(immersive);
    182                 pw.print(" launchMode="); pw.println(launchMode);
    183         pw.print(prefix); pw.print("frozenBeforeDestroy="); pw.print(frozenBeforeDestroy);
    184                 pw.print(" thumbnailNeeded="); pw.print(thumbnailNeeded);
    185                 pw.print(" forceNewConfig="); pw.println(forceNewConfig);
    186         pw.print(prefix); pw.print("thumbHolder="); pw.println(thumbHolder);
    187         if (launchTime != 0 || startTime != 0) {
    188             pw.print(prefix); pw.print("launchTime=");
    189                     TimeUtils.formatDuration(launchTime, pw); pw.print(" startTime=");
    190                     TimeUtils.formatDuration(startTime, pw); pw.println("");
    191         }
    192         if (lastVisibleTime != 0) {
    193             pw.print(prefix); pw.print("lastVisibleTime=");
    194                     TimeUtils.formatDuration(lastVisibleTime, pw); pw.println("");
    195         }
    196         if (waitingVisible || nowVisible) {
    197             pw.print(prefix); pw.print("waitingVisible="); pw.print(waitingVisible);
    198                     pw.print(" nowVisible="); pw.println(nowVisible);
    199         }
    200         if (configDestroy || configChangeFlags != 0) {
    201             pw.print(prefix); pw.print("configDestroy="); pw.print(configDestroy);
    202                     pw.print(" configChangeFlags=");
    203                     pw.println(Integer.toHexString(configChangeFlags));
    204         }
    205         if (connections != null) {
    206             pw.print(prefix); pw.print("connections="); pw.println(connections);
    207         }
    208     }
    209 
    210     static class Token extends IApplicationToken.Stub {
    211         final WeakReference<ActivityRecord> weakActivity;
    212 
    213         Token(ActivityRecord activity) {
    214             weakActivity = new WeakReference<ActivityRecord>(activity);
    215         }
    216 
    217         @Override public void windowsDrawn() throws RemoteException {
    218             ActivityRecord activity = weakActivity.get();
    219             if (activity != null) {
    220                 activity.windowsDrawn();
    221             }
    222         }
    223 
    224         @Override public void windowsVisible() throws RemoteException {
    225             ActivityRecord activity = weakActivity.get();
    226             if (activity != null) {
    227                 activity.windowsVisible();
    228             }
    229         }
    230 
    231         @Override public void windowsGone() throws RemoteException {
    232             ActivityRecord activity = weakActivity.get();
    233             if (activity != null) {
    234                 activity.windowsGone();
    235             }
    236         }
    237 
    238         @Override public boolean keyDispatchingTimedOut() throws RemoteException {
    239             ActivityRecord activity = weakActivity.get();
    240             if (activity != null) {
    241                 return activity.keyDispatchingTimedOut();
    242             }
    243             return false;
    244         }
    245 
    246         @Override public long getKeyDispatchingTimeout() throws RemoteException {
    247             ActivityRecord activity = weakActivity.get();
    248             if (activity != null) {
    249                 return activity.getKeyDispatchingTimeout();
    250             }
    251             return 0;
    252         }
    253 
    254         public String toString() {
    255             StringBuilder sb = new StringBuilder(128);
    256             sb.append("Token{");
    257             sb.append(Integer.toHexString(System.identityHashCode(this)));
    258             sb.append(' ');
    259             sb.append(weakActivity.get());
    260             sb.append('}');
    261             return sb.toString();
    262         }
    263     }
    264 
    265     static ActivityRecord forToken(IBinder token) {
    266         try {
    267             return token != null ? ((Token)token).weakActivity.get() : null;
    268         } catch (ClassCastException e) {
    269             Slog.w(ActivityManagerService.TAG, "Bad activity token: " + token, e);
    270             return null;
    271         }
    272     }
    273 
    274     ActivityRecord(ActivityManagerService _service, ActivityStack _stack, ProcessRecord _caller,
    275             int _launchedFromUid, Intent _intent, String _resolvedType,
    276             ActivityInfo aInfo, Configuration _configuration,
    277             ActivityRecord _resultTo, String _resultWho, int _reqCode,
    278             boolean _componentSpecified) {
    279         service = _service;
    280         stack = _stack;
    281         appToken = new Token(this);
    282         info = aInfo;
    283         launchedFromUid = _launchedFromUid;
    284         intent = _intent;
    285         shortComponentName = _intent.getComponent().flattenToShortString();
    286         resolvedType = _resolvedType;
    287         componentSpecified = _componentSpecified;
    288         configuration = _configuration;
    289         resultTo = _resultTo;
    290         resultWho = _resultWho;
    291         requestCode = _reqCode;
    292         state = ActivityState.INITIALIZING;
    293         frontOfTask = false;
    294         launchFailed = false;
    295         haveState = false;
    296         stopped = false;
    297         delayedResume = false;
    298         finishing = false;
    299         configDestroy = false;
    300         keysPaused = false;
    301         inHistory = false;
    302         visible = true;
    303         waitingVisible = false;
    304         nowVisible = false;
    305         thumbnailNeeded = false;
    306         idle = false;
    307         hasBeenLaunched = false;
    308 
    309         if (aInfo != null) {
    310             if (aInfo.targetActivity == null
    311                     || aInfo.launchMode == ActivityInfo.LAUNCH_MULTIPLE
    312                     || aInfo.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
    313                 realActivity = _intent.getComponent();
    314             } else {
    315                 realActivity = new ComponentName(aInfo.packageName,
    316                         aInfo.targetActivity);
    317             }
    318             taskAffinity = aInfo.taskAffinity;
    319             stateNotNeeded = (aInfo.flags&
    320                     ActivityInfo.FLAG_STATE_NOT_NEEDED) != 0;
    321             baseDir = aInfo.applicationInfo.sourceDir;
    322             resDir = aInfo.applicationInfo.publicSourceDir;
    323             dataDir = aInfo.applicationInfo.dataDir;
    324             nonLocalizedLabel = aInfo.nonLocalizedLabel;
    325             labelRes = aInfo.labelRes;
    326             if (nonLocalizedLabel == null && labelRes == 0) {
    327                 ApplicationInfo app = aInfo.applicationInfo;
    328                 nonLocalizedLabel = app.nonLocalizedLabel;
    329                 labelRes = app.labelRes;
    330             }
    331             icon = aInfo.getIconResource();
    332             theme = aInfo.getThemeResource();
    333             realTheme = theme;
    334             if (realTheme == 0) {
    335                 realTheme = aInfo.applicationInfo.targetSdkVersion
    336                         < Build.VERSION_CODES.HONEYCOMB
    337                         ? android.R.style.Theme
    338                         : android.R.style.Theme_Holo;
    339             }
    340             if ((aInfo.flags&ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
    341                 windowFlags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
    342             }
    343             if ((aInfo.flags&ActivityInfo.FLAG_MULTIPROCESS) != 0
    344                     && _caller != null
    345                     && (aInfo.applicationInfo.uid == Process.SYSTEM_UID
    346                             || aInfo.applicationInfo.uid == _caller.info.uid)) {
    347                 processName = _caller.processName;
    348             } else {
    349                 processName = aInfo.processName;
    350             }
    351 
    352             if (intent != null && (aInfo.flags & ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS) != 0) {
    353                 intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    354             }
    355 
    356             packageName = aInfo.applicationInfo.packageName;
    357             launchMode = aInfo.launchMode;
    358 
    359             AttributeCache.Entry ent = AttributeCache.instance().get(packageName,
    360                     realTheme, com.android.internal.R.styleable.Window);
    361             fullscreen = ent != null && !ent.array.getBoolean(
    362                     com.android.internal.R.styleable.Window_windowIsFloating, false)
    363                     && !ent.array.getBoolean(
    364                     com.android.internal.R.styleable.Window_windowIsTranslucent, false);
    365             noDisplay = ent != null && ent.array.getBoolean(
    366                     com.android.internal.R.styleable.Window_windowNoDisplay, false);
    367 
    368             if (!_componentSpecified || _launchedFromUid == Process.myUid()
    369                     || _launchedFromUid == 0) {
    370                 // If we know the system has determined the component, then
    371                 // we can consider this to be a home activity...
    372                 if (Intent.ACTION_MAIN.equals(_intent.getAction()) &&
    373                         _intent.hasCategory(Intent.CATEGORY_HOME) &&
    374                         _intent.getCategories().size() == 1 &&
    375                         _intent.getData() == null &&
    376                         _intent.getType() == null &&
    377                         (intent.getFlags()&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
    378                         !"android".equals(realActivity.getClassName())) {
    379                     // This sure looks like a home activity!
    380                     // Note the last check is so we don't count the resolver
    381                     // activity as being home...  really, we don't care about
    382                     // doing anything special with something that comes from
    383                     // the core framework package.
    384                     isHomeActivity = true;
    385                 } else {
    386                     isHomeActivity = false;
    387                 }
    388             } else {
    389                 isHomeActivity = false;
    390             }
    391 
    392             immersive = (aInfo.flags & ActivityInfo.FLAG_IMMERSIVE) != 0;
    393         } else {
    394             realActivity = null;
    395             taskAffinity = null;
    396             stateNotNeeded = false;
    397             baseDir = null;
    398             resDir = null;
    399             dataDir = null;
    400             processName = null;
    401             packageName = null;
    402             fullscreen = true;
    403             noDisplay = false;
    404             isHomeActivity = false;
    405             immersive = false;
    406         }
    407     }
    408 
    409     void setTask(TaskRecord newTask, ThumbnailHolder newThumbHolder, boolean isRoot) {
    410         if (inHistory && !finishing) {
    411             if (task != null) {
    412                 task.numActivities--;
    413             }
    414             if (newTask != null) {
    415                 newTask.numActivities++;
    416             }
    417         }
    418         if (newThumbHolder == null) {
    419             newThumbHolder = newTask;
    420         }
    421         task = newTask;
    422         if (!isRoot && (intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
    423             // This is the start of a new sub-task.
    424             if (thumbHolder == null) {
    425                 thumbHolder = new ThumbnailHolder();
    426             }
    427         } else {
    428             thumbHolder = newThumbHolder;
    429         }
    430     }
    431 
    432     void putInHistory() {
    433         if (!inHistory) {
    434             inHistory = true;
    435             if (task != null && !finishing) {
    436                 task.numActivities++;
    437             }
    438         }
    439     }
    440 
    441     void takeFromHistory() {
    442         if (inHistory) {
    443             inHistory = false;
    444             if (task != null && !finishing) {
    445                 task.numActivities--;
    446             }
    447         }
    448     }
    449 
    450     boolean isInHistory() {
    451         return inHistory;
    452     }
    453 
    454     void makeFinishing() {
    455         if (!finishing) {
    456             finishing = true;
    457             if (task != null && inHistory) {
    458                 task.numActivities--;
    459             }
    460         }
    461     }
    462 
    463     UriPermissionOwner getUriPermissionsLocked() {
    464         if (uriPermissions == null) {
    465             uriPermissions = new UriPermissionOwner(service, this);
    466         }
    467         return uriPermissions;
    468     }
    469 
    470     void addResultLocked(ActivityRecord from, String resultWho,
    471             int requestCode, int resultCode,
    472             Intent resultData) {
    473         ActivityResult r = new ActivityResult(from, resultWho,
    474         		requestCode, resultCode, resultData);
    475         if (results == null) {
    476             results = new ArrayList();
    477         }
    478         results.add(r);
    479     }
    480 
    481     void removeResultsLocked(ActivityRecord from, String resultWho,
    482             int requestCode) {
    483         if (results != null) {
    484             for (int i=results.size()-1; i>=0; i--) {
    485                 ActivityResult r = (ActivityResult)results.get(i);
    486                 if (r.mFrom != from) continue;
    487                 if (r.mResultWho == null) {
    488                     if (resultWho != null) continue;
    489                 } else {
    490                     if (!r.mResultWho.equals(resultWho)) continue;
    491                 }
    492                 if (r.mRequestCode != requestCode) continue;
    493 
    494                 results.remove(i);
    495             }
    496         }
    497     }
    498 
    499     void addNewIntentLocked(Intent intent) {
    500         if (newIntents == null) {
    501             newIntents = new ArrayList();
    502         }
    503         newIntents.add(intent);
    504     }
    505 
    506     /**
    507      * Deliver a new Intent to an existing activity, so that its onNewIntent()
    508      * method will be called at the proper time.
    509      */
    510     final void deliverNewIntentLocked(int callingUid, Intent intent) {
    511         boolean sent = false;
    512         if (state == ActivityState.RESUMED
    513                 && app != null && app.thread != null) {
    514             try {
    515                 ArrayList<Intent> ar = new ArrayList<Intent>();
    516                 intent = new Intent(intent);
    517                 ar.add(intent);
    518                 service.grantUriPermissionFromIntentLocked(callingUid, packageName,
    519                         intent, getUriPermissionsLocked());
    520                 app.thread.scheduleNewIntent(ar, appToken);
    521                 sent = true;
    522             } catch (RemoteException e) {
    523                 Slog.w(ActivityManagerService.TAG,
    524                         "Exception thrown sending new intent to " + this, e);
    525             } catch (NullPointerException e) {
    526                 Slog.w(ActivityManagerService.TAG,
    527                         "Exception thrown sending new intent to " + this, e);
    528             }
    529         }
    530         if (!sent) {
    531             addNewIntentLocked(new Intent(intent));
    532         }
    533     }
    534 
    535     void removeUriPermissionsLocked() {
    536         if (uriPermissions != null) {
    537             uriPermissions.removeUriPermissionsLocked();
    538             uriPermissions = null;
    539         }
    540     }
    541 
    542     void pauseKeyDispatchingLocked() {
    543         if (!keysPaused) {
    544             keysPaused = true;
    545             service.mWindowManager.pauseKeyDispatching(appToken);
    546         }
    547     }
    548 
    549     void resumeKeyDispatchingLocked() {
    550         if (keysPaused) {
    551             keysPaused = false;
    552             service.mWindowManager.resumeKeyDispatching(appToken);
    553         }
    554     }
    555 
    556     void updateThumbnail(Bitmap newThumbnail, CharSequence description) {
    557         if ((intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
    558             // This is a logical break in the task; it repre
    559         }
    560         if (thumbHolder != null) {
    561             if (newThumbnail != null) {
    562                 thumbHolder.lastThumbnail = newThumbnail;
    563             }
    564             thumbHolder.lastDescription = description;
    565         }
    566     }
    567 
    568     void clearThumbnail() {
    569         if (thumbHolder != null) {
    570             thumbHolder.lastThumbnail = null;
    571             thumbHolder.lastDescription = null;
    572         }
    573     }
    574 
    575     // IApplicationToken
    576 
    577     public boolean mayFreezeScreenLocked(ProcessRecord app) {
    578         // Only freeze the screen if this activity is currently attached to
    579         // an application, and that application is not blocked or unresponding.
    580         // In any other case, we can't count on getting the screen unfrozen,
    581         // so it is best to leave as-is.
    582         return app != null && !app.crashing && !app.notResponding;
    583     }
    584 
    585     public void startFreezingScreenLocked(ProcessRecord app, int configChanges) {
    586         if (mayFreezeScreenLocked(app)) {
    587             service.mWindowManager.startAppFreezingScreen(appToken, configChanges);
    588         }
    589     }
    590 
    591     public void stopFreezingScreenLocked(boolean force) {
    592         if (force || frozenBeforeDestroy) {
    593             frozenBeforeDestroy = false;
    594             service.mWindowManager.stopAppFreezingScreen(appToken, force);
    595         }
    596     }
    597 
    598     public void windowsDrawn() {
    599         synchronized(service) {
    600             if (launchTime != 0) {
    601                 final long curTime = SystemClock.uptimeMillis();
    602                 final long thisTime = curTime - launchTime;
    603                 final long totalTime = stack.mInitialStartTime != 0
    604                         ? (curTime - stack.mInitialStartTime) : thisTime;
    605                 if (ActivityManagerService.SHOW_ACTIVITY_START_TIME) {
    606                     EventLog.writeEvent(EventLogTags.ACTIVITY_LAUNCH_TIME,
    607                             System.identityHashCode(this), shortComponentName,
    608                             thisTime, totalTime);
    609                     StringBuilder sb = service.mStringBuilder;
    610                     sb.setLength(0);
    611                     sb.append("Displayed ");
    612                     sb.append(shortComponentName);
    613                     sb.append(": ");
    614                     TimeUtils.formatDuration(thisTime, sb);
    615                     if (thisTime != totalTime) {
    616                         sb.append(" (total ");
    617                         TimeUtils.formatDuration(totalTime, sb);
    618                         sb.append(")");
    619                     }
    620                     Log.i(ActivityManagerService.TAG, sb.toString());
    621                 }
    622                 stack.reportActivityLaunchedLocked(false, this, thisTime, totalTime);
    623                 if (totalTime > 0) {
    624                     service.mUsageStatsService.noteLaunchTime(realActivity, (int)totalTime);
    625                 }
    626                 launchTime = 0;
    627                 stack.mInitialStartTime = 0;
    628             }
    629             startTime = 0;
    630         }
    631     }
    632 
    633     public void windowsVisible() {
    634         synchronized(service) {
    635             stack.reportActivityVisibleLocked(this);
    636             if (ActivityManagerService.DEBUG_SWITCH) Log.v(
    637                     ActivityManagerService.TAG, "windowsVisible(): " + this);
    638             if (!nowVisible) {
    639                 nowVisible = true;
    640                 lastVisibleTime = SystemClock.uptimeMillis();
    641                 if (!idle) {
    642                     // Instead of doing the full stop routine here, let's just
    643                     // hide any activities we now can, and let them stop when
    644                     // the normal idle happens.
    645                     stack.processStoppingActivitiesLocked(false);
    646                 } else {
    647                     // If this activity was already idle, then we now need to
    648                     // make sure we perform the full stop of any activities
    649                     // that are waiting to do so.  This is because we won't
    650                     // do that while they are still waiting for this one to
    651                     // become visible.
    652                     final int N = stack.mWaitingVisibleActivities.size();
    653                     if (N > 0) {
    654                         for (int i=0; i<N; i++) {
    655                             ActivityRecord r = (ActivityRecord)
    656                                 stack.mWaitingVisibleActivities.get(i);
    657                             r.waitingVisible = false;
    658                             if (ActivityManagerService.DEBUG_SWITCH) Log.v(
    659                                     ActivityManagerService.TAG,
    660                                     "Was waiting for visible: " + r);
    661                         }
    662                         stack.mWaitingVisibleActivities.clear();
    663                         Message msg = Message.obtain();
    664                         msg.what = ActivityStack.IDLE_NOW_MSG;
    665                         stack.mHandler.sendMessage(msg);
    666                     }
    667                 }
    668                 service.scheduleAppGcsLocked();
    669             }
    670         }
    671     }
    672 
    673     public void windowsGone() {
    674         if (ActivityManagerService.DEBUG_SWITCH) Log.v(
    675                 ActivityManagerService.TAG, "windowsGone(): " + this);
    676         nowVisible = false;
    677     }
    678 
    679     private ActivityRecord getWaitingHistoryRecordLocked() {
    680         // First find the real culprit...  if we are waiting
    681         // for another app to start, then we have paused dispatching
    682         // for this activity.
    683         ActivityRecord r = this;
    684         if (r.waitingVisible) {
    685             // Hmmm, who might we be waiting for?
    686             r = stack.mResumedActivity;
    687             if (r == null) {
    688                 r = stack.mPausingActivity;
    689             }
    690             // Both of those null?  Fall back to 'this' again
    691             if (r == null) {
    692                 r = this;
    693             }
    694         }
    695 
    696         return r;
    697     }
    698 
    699     public boolean keyDispatchingTimedOut() {
    700         ActivityRecord r;
    701         ProcessRecord anrApp = null;
    702         synchronized(service) {
    703             r = getWaitingHistoryRecordLocked();
    704             if (r != null && r.app != null) {
    705                 if (r.app.debugging) {
    706                     return false;
    707                 }
    708 
    709                 if (service.mDidDexOpt) {
    710                     // Give more time since we were dexopting.
    711                     service.mDidDexOpt = false;
    712                     return false;
    713                 }
    714 
    715                 if (r.app.instrumentationClass == null) {
    716                     anrApp = r.app;
    717                 } else {
    718                     Bundle info = new Bundle();
    719                     info.putString("shortMsg", "keyDispatchingTimedOut");
    720                     info.putString("longMsg", "Timed out while dispatching key event");
    721                     service.finishInstrumentationLocked(
    722                             r.app, Activity.RESULT_CANCELED, info);
    723                 }
    724             }
    725         }
    726 
    727         if (anrApp != null) {
    728             service.appNotResponding(anrApp, r, this,
    729                     "keyDispatchingTimedOut");
    730         }
    731 
    732         return true;
    733     }
    734 
    735     /** Returns the key dispatching timeout for this application token. */
    736     public long getKeyDispatchingTimeout() {
    737         synchronized(service) {
    738             ActivityRecord r = getWaitingHistoryRecordLocked();
    739             if (r != null && r.app != null
    740                     && (r.app.instrumentationClass != null || r.app.usingWrapper)) {
    741                 return ActivityManagerService.INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT;
    742             }
    743 
    744             return ActivityManagerService.KEY_DISPATCHING_TIMEOUT;
    745         }
    746     }
    747 
    748     /**
    749      * This method will return true if the activity is either visible, is becoming visible, is
    750      * currently pausing, or is resumed.
    751      */
    752     public boolean isInterestingToUserLocked() {
    753         return visible || nowVisible || state == ActivityState.PAUSING ||
    754                 state == ActivityState.RESUMED;
    755     }
    756 
    757     public void setSleeping(boolean _sleeping) {
    758         if (sleeping == _sleeping) {
    759             return;
    760         }
    761         if (app != null && app.thread != null) {
    762             try {
    763                 app.thread.scheduleSleeping(appToken, _sleeping);
    764                 if (sleeping && !stack.mGoingToSleepActivities.contains(this)) {
    765                     stack.mGoingToSleepActivities.add(this);
    766                 }
    767                 sleeping = _sleeping;
    768             } catch (RemoteException e) {
    769                 Slog.w(ActivityStack.TAG, "Exception thrown when sleeping: "
    770                         + intent.getComponent(), e);
    771             }
    772         }
    773     }
    774 
    775     public String toString() {
    776         if (stringName != null) {
    777             return stringName;
    778         }
    779         StringBuilder sb = new StringBuilder(128);
    780         sb.append("ActivityRecord{");
    781         sb.append(Integer.toHexString(System.identityHashCode(this)));
    782         sb.append(' ');
    783         sb.append(intent.getComponent().flattenToShortString());
    784         sb.append('}');
    785         return stringName = sb.toString();
    786     }
    787 }
    788