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