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