TaskRecord.java revision 9d4e9bcebbd97ad51daa0ef15cfba5aabb399bbb
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 static com.android.server.am.ActivityManagerService.TAG;
20import static com.android.server.am.ActivityStackSupervisor.DEBUG_ADD_REMOVE;
21
22import android.app.Activity;
23import android.app.ActivityManager;
24import android.app.ActivityOptions;
25import android.app.IThumbnailRetriever;
26import android.content.ComponentName;
27import android.content.Intent;
28import android.content.pm.ActivityInfo;
29import android.graphics.Bitmap;
30import android.os.UserHandle;
31import android.service.voice.IVoiceInteractionSession;
32import android.util.Slog;
33import com.android.internal.app.IVoiceInteractor;
34import com.android.internal.util.XmlUtils;
35import org.xmlpull.v1.XmlPullParser;
36import org.xmlpull.v1.XmlPullParserException;
37import org.xmlpull.v1.XmlSerializer;
38
39import java.io.IOException;
40import java.io.PrintWriter;
41import java.util.ArrayList;
42
43final class TaskRecord extends ThumbnailHolder {
44    private static final String TAG_TASK = "task";
45    private static final String ATTR_TASKID = "task_id";
46    private static final String TAG_INTENT = "intent";
47    private static final String TAG_AFFINITYINTENT = "affinity_intent";
48    private static final String ATTR_REALACTIVITY = "real_activity";
49    private static final String ATTR_ORIGACTIVITY = "orig_activity";
50    private static final String TAG_ACTIVITY = "activity";
51    private static final String ATTR_AFFINITY = "affinity";
52    private static final String ATTR_ROOTHASRESET = "root_has_reset";
53    private static final String ATTR_ASKEDCOMPATMODE = "asked_compat_mode";
54    private static final String ATTR_USERID = "user_id";
55    private static final String ATTR_TASKTYPE = "task_type";
56    private static final String ATTR_ONTOPOFHOME = "on_top_of_home";
57    private static final String ATTR_LASTDESCRIPTION = "last_description";
58    private static final String ATTR_LASTTIMEMOVED = "last_time_moved";
59    private static final String ATTR_NEVERRELINQUISH = "never_relinquish_identity";
60
61    private static final String TASK_THUMBNAIL_SUFFIX = "_task_thumbnail";
62
63    final int taskId;       // Unique identifier for this task.
64    String affinity;        // The affinity name for this task, or null.
65    final IVoiceInteractionSession voiceSession;    // Voice interaction session driving task
66    final IVoiceInteractor voiceInteractor;         // Associated interactor to provide to app
67    Intent intent;          // The original intent that started the task.
68    Intent affinityIntent;  // Intent of affinity-moved activity that started this task.
69    ComponentName origActivity; // The non-alias activity component of the intent.
70    ComponentName realActivity; // The actual activity component that started the task.
71    int numActivities;      // Current number of activities in this task.
72    long lastActiveTime;    // Last time this task was active, including sleep.
73    boolean rootWasReset;   // True if the intent at the root of the task had
74                            // the FLAG_ACTIVITY_RESET_TASK_IF_NEEDED flag.
75    boolean askedCompatMode;// Have asked the user about compat mode for this task.
76    boolean hasBeenVisible; // Set if any activities in the task have been visible to the user.
77
78    String stringName;      // caching of toString() result.
79    int userId;             // user for which this task was created
80    int creatorUid;         // The app uid that originally created the task
81
82    int numFullscreen;      // Number of fullscreen activities.
83
84    // This represents the last resolved activity values for this task
85    // NOTE: This value needs to be persisted with each task
86    ActivityManager.TaskDescription lastTaskDescription =
87            new ActivityManager.TaskDescription();
88
89    /** List of all activities in the task arranged in history order */
90    final ArrayList<ActivityRecord> mActivities;
91
92    /** Current stack */
93    ActivityStack stack;
94
95    /** Takes on same set of values as ActivityRecord.mActivityType */
96    int taskType;
97
98    /** Takes on same value as first root activity */
99    boolean isPersistable = false;
100    int maxRecents;
101
102    /** Only used for persistable tasks, otherwise 0. The last time this task was moved. Used for
103     * determining the order when restoring. Sign indicates whether last task movement was to front
104     * (positive) or back (negative). Absolute value indicates time. */
105    long mLastTimeMoved = System.currentTimeMillis();
106
107    /** True if persistable, has changed, and has not yet been persisted */
108    boolean needsPersisting = false;
109
110    /** Launch the home activity when leaving this task. Will be false for tasks that are not on
111     * Display.DEFAULT_DISPLAY. */
112    boolean mOnTopOfHome = false;
113
114    /** If original intent did not allow relinquishing task identity, save that information */
115    boolean mNeverRelinquishIdentity = true;
116
117    final ActivityManagerService mService;
118
119    TaskRecord(ActivityManagerService service, int _taskId, ActivityInfo info, Intent _intent,
120            IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) {
121        mService = service;
122        taskId = _taskId;
123        voiceSession = _voiceSession;
124        voiceInteractor = _voiceInteractor;
125        setIntent(_intent, info);
126        mActivities = new ArrayList<ActivityRecord>();
127    }
128
129    TaskRecord(ActivityManagerService service, int _taskId, Intent _intent, Intent _affinityIntent,
130            String _affinity, ComponentName _realActivity, ComponentName _origActivity,
131            boolean _rootWasReset, boolean _askedCompatMode, int _taskType, boolean _onTopOfHome,
132            int _userId, String _lastDescription, ArrayList<ActivityRecord> activities,
133            long lastTimeMoved, boolean neverRelinquishIdentity) {
134        mService = service;
135        taskId = _taskId;
136        intent = _intent;
137        affinityIntent = _affinityIntent;
138        affinity = _affinity;
139        voiceSession = null;
140        voiceInteractor = null;
141        realActivity = _realActivity;
142        origActivity = _origActivity;
143        rootWasReset = _rootWasReset;
144        askedCompatMode = _askedCompatMode;
145        taskType = _taskType;
146        mOnTopOfHome = _onTopOfHome;
147        userId = _userId;
148        lastDescription = _lastDescription;
149        mActivities = activities;
150        mLastTimeMoved = lastTimeMoved;
151        mNeverRelinquishIdentity = neverRelinquishIdentity;
152    }
153
154    void touchActiveTime() {
155        lastActiveTime = android.os.SystemClock.elapsedRealtime();
156    }
157
158    long getInactiveDuration() {
159        return android.os.SystemClock.elapsedRealtime() - lastActiveTime;
160    }
161
162    void setIntent(Intent _intent, ActivityInfo info) {
163        if (intent == null) {
164            mNeverRelinquishIdentity =
165                    (info.flags & ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY) == 0;
166        } else if (mNeverRelinquishIdentity) {
167            return;
168        }
169
170        affinity = info.taskAffinity;
171        stringName = null;
172
173        if (info.targetActivity == null) {
174            if (_intent != null) {
175                // If this Intent has a selector, we want to clear it for the
176                // recent task since it is not relevant if the user later wants
177                // to re-launch the app.
178                if (_intent.getSelector() != null || _intent.getSourceBounds() != null) {
179                    _intent = new Intent(_intent);
180                    _intent.setSelector(null);
181                    _intent.setSourceBounds(null);
182                }
183            }
184            if (ActivityManagerService.DEBUG_TASKS) Slog.v(ActivityManagerService.TAG,
185                    "Setting Intent of " + this + " to " + _intent);
186            intent = _intent;
187            realActivity = _intent != null ? _intent.getComponent() : null;
188            origActivity = null;
189        } else {
190            ComponentName targetComponent = new ComponentName(
191                    info.packageName, info.targetActivity);
192            if (_intent != null) {
193                Intent targetIntent = new Intent(_intent);
194                targetIntent.setComponent(targetComponent);
195                targetIntent.setSelector(null);
196                targetIntent.setSourceBounds(null);
197                if (ActivityManagerService.DEBUG_TASKS) Slog.v(ActivityManagerService.TAG,
198                        "Setting Intent of " + this + " to target " + targetIntent);
199                intent = targetIntent;
200                realActivity = targetComponent;
201                origActivity = _intent.getComponent();
202            } else {
203                intent = null;
204                realActivity = targetComponent;
205                origActivity = new ComponentName(info.packageName, info.name);
206            }
207        }
208
209        if (intent != null &&
210                (intent.getFlags()&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
211            // Once we are set to an Intent with this flag, we count this
212            // task as having a true root activity.
213            rootWasReset = true;
214        }
215
216        userId = UserHandle.getUserId(info.applicationInfo.uid);
217        creatorUid = info.applicationInfo.uid;
218        if ((info.flags & ActivityInfo.FLAG_AUTO_REMOVE_FROM_RECENTS) != 0) {
219            intent.addFlags(Intent.FLAG_ACTIVITY_AUTO_REMOVE_FROM_RECENTS);
220        }
221    }
222
223    void disposeThumbnail() {
224        super.disposeThumbnail();
225        for (int i=mActivities.size()-1; i>=0; i--) {
226            ThumbnailHolder thumb = mActivities.get(i).thumbHolder;
227            if (thumb != this) {
228                thumb.disposeThumbnail();
229            }
230        }
231    }
232
233    /** Returns the intent for the root activity for this task */
234    Intent getBaseIntent() {
235        return intent != null ? intent : affinityIntent;
236    }
237
238    /** Returns the first non-finishing activity from the root. */
239    ActivityRecord getRootActivity() {
240        for (int i = 0; i < mActivities.size(); i++) {
241            final ActivityRecord r = mActivities.get(i);
242            if (r.finishing) {
243                continue;
244            }
245            return r;
246        }
247        return null;
248    }
249
250    ActivityRecord getTopActivity() {
251        for (int i = mActivities.size() - 1; i >= 0; --i) {
252            final ActivityRecord r = mActivities.get(i);
253            if (r.finishing) {
254                continue;
255            }
256            return r;
257        }
258        return null;
259    }
260
261    ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
262        for (int activityNdx = mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
263            ActivityRecord r = mActivities.get(activityNdx);
264            if (!r.finishing && r != notTop && stack.okToShowLocked(r)) {
265                return r;
266            }
267        }
268        return null;
269    }
270
271    /** Call after activity movement or finish to make sure that frontOfTask is set correctly */
272    final void setFrontOfTask() {
273        boolean foundFront = false;
274        final int numActivities = mActivities.size();
275        for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
276            final ActivityRecord r = mActivities.get(activityNdx);
277            if (foundFront || r.finishing) {
278                r.frontOfTask = false;
279            } else {
280                r.frontOfTask = true;
281                // Set frontOfTask false for every following activity.
282                foundFront = true;
283            }
284        }
285    }
286
287    /**
288     * Reorder the history stack so that the passed activity is brought to the front.
289     */
290    final void moveActivityToFrontLocked(ActivityRecord newTop) {
291        if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + newTop
292            + " to stack at top", new RuntimeException("here").fillInStackTrace());
293
294        mActivities.remove(newTop);
295        mActivities.add(newTop);
296        updateEffectiveIntent();
297
298        setFrontOfTask();
299    }
300
301    void addActivityAtBottom(ActivityRecord r) {
302        addActivityAtIndex(0, r);
303    }
304
305    void addActivityToTop(ActivityRecord r) {
306        addActivityAtIndex(mActivities.size(), r);
307    }
308
309    void addActivityAtIndex(int index, ActivityRecord r) {
310        // Remove r first, and if it wasn't already in the list and it's fullscreen, count it.
311        if (!mActivities.remove(r) && r.fullscreen) {
312            // Was not previously in list.
313            numFullscreen++;
314        }
315        // Only set this based on the first activity
316        if (mActivities.isEmpty()) {
317            taskType = r.mActivityType;
318            isPersistable = r.isPersistable();
319            // Clamp to [1, 100].
320            maxRecents = Math.min(Math.max(r.info.maxRecents, 1), 100);
321        } else {
322            // Otherwise make all added activities match this one.
323            r.mActivityType = taskType;
324        }
325        mActivities.add(index, r);
326        updateEffectiveIntent();
327        if (r.isPersistable()) {
328            mService.notifyTaskPersisterLocked(this, false);
329        }
330    }
331
332    /** @return true if this was the last activity in the task */
333    boolean removeActivity(ActivityRecord r) {
334        if (mActivities.remove(r) && r.fullscreen) {
335            // Was previously in list.
336            numFullscreen--;
337        }
338        updateEffectiveIntent();
339        if (r.isPersistable()) {
340            mService.notifyTaskPersisterLocked(this, false);
341        }
342        return mActivities.size() == 0;
343    }
344
345    boolean autoRemoveFromRecents() {
346        // We will automatically remove the task either if it has explicitly asked for
347        // this, or it is empty and has never contained an activity that got shown to
348        // the user.
349        return (intent != null &&
350                (intent.getFlags() & Intent.FLAG_ACTIVITY_AUTO_REMOVE_FROM_RECENTS) != 0) ||
351                (mActivities.isEmpty() && !hasBeenVisible);
352    }
353
354    /**
355     * Completely remove all activities associated with an existing
356     * task starting at a specified index.
357     */
358    final void performClearTaskAtIndexLocked(int activityNdx) {
359        int numActivities = mActivities.size();
360        for ( ; activityNdx < numActivities; ++activityNdx) {
361            final ActivityRecord r = mActivities.get(activityNdx);
362            if (r.finishing) {
363                continue;
364            }
365            if (stack == null) {
366                // Task was restored from persistent storage.
367                r.takeFromHistory();
368                mActivities.remove(activityNdx);
369                --activityNdx;
370                --numActivities;
371            } else if (stack.finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear",
372                    false)) {
373                --activityNdx;
374                --numActivities;
375            }
376        }
377    }
378
379    /**
380     * Completely remove all activities associated with an existing task.
381     */
382    final void performClearTaskLocked() {
383        performClearTaskAtIndexLocked(0);
384    }
385
386    /**
387     * Perform clear operation as requested by
388     * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
389     * stack to the given task, then look for
390     * an instance of that activity in the stack and, if found, finish all
391     * activities on top of it and return the instance.
392     *
393     * @param newR Description of the new activity being started.
394     * @return Returns the old activity that should be continued to be used,
395     * or null if none was found.
396     */
397    final ActivityRecord performClearTaskLocked(ActivityRecord newR, int launchFlags) {
398        int numActivities = mActivities.size();
399        for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) {
400            ActivityRecord r = mActivities.get(activityNdx);
401            if (r.finishing) {
402                continue;
403            }
404            if (r.realActivity.equals(newR.realActivity)) {
405                // Here it is!  Now finish everything in front...
406                final ActivityRecord ret = r;
407
408                for (++activityNdx; activityNdx < numActivities; ++activityNdx) {
409                    r = mActivities.get(activityNdx);
410                    if (r.finishing) {
411                        continue;
412                    }
413                    ActivityOptions opts = r.takeOptionsLocked();
414                    if (opts != null) {
415                        ret.updateOptionsLocked(opts);
416                    }
417                    if (stack.finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear",
418                            false)) {
419                        --activityNdx;
420                        --numActivities;
421                    }
422                }
423
424                // Finally, if this is a normal launch mode (that is, not
425                // expecting onNewIntent()), then we will finish the current
426                // instance of the activity so a new fresh one can be started.
427                if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
428                        && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
429                    if (!ret.finishing) {
430                        stack.finishActivityLocked(ret, Activity.RESULT_CANCELED, null,
431                                "clear", false);
432                        return null;
433                    }
434                }
435
436                return ret;
437            }
438        }
439
440        return null;
441    }
442
443    public ActivityManager.TaskThumbnails getTaskThumbnailsLocked() {
444        TaskAccessInfo info = getTaskAccessInfoLocked();
445        final ActivityRecord resumedActivity = stack.mResumedActivity;
446        if (resumedActivity != null && resumedActivity.thumbHolder == this) {
447            info.mainThumbnail = stack.screenshotActivities(resumedActivity);
448        }
449        if (info.mainThumbnail == null) {
450            info.mainThumbnail = lastThumbnail;
451        }
452        return info;
453    }
454
455    public Bitmap getTaskTopThumbnailLocked() {
456        if (stack != null) {
457            final ActivityRecord resumedActivity = stack.mResumedActivity;
458            if (resumedActivity != null && resumedActivity.task == this) {
459                // This task is the current resumed task, we just need to take
460                // a screenshot of it and return that.
461                return stack.screenshotActivities(resumedActivity);
462            }
463        }
464        // Return the information about the task, to figure out the top
465        // thumbnail to return.
466        TaskAccessInfo info = getTaskAccessInfoLocked();
467        if (info.numSubThumbbails <= 0) {
468            return info.mainThumbnail != null ? info.mainThumbnail : lastThumbnail;
469        }
470        return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
471    }
472
473    public ActivityRecord removeTaskActivitiesLocked(int subTaskIndex,
474            boolean taskRequired) {
475        TaskAccessInfo info = getTaskAccessInfoLocked();
476        if (info.root == null) {
477            if (taskRequired) {
478                Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
479            }
480            return null;
481        }
482
483        if (subTaskIndex < 0) {
484            // Just remove the entire task.
485            performClearTaskAtIndexLocked(info.rootIndex);
486            return info.root;
487        }
488
489        if (subTaskIndex >= info.subtasks.size()) {
490            if (taskRequired) {
491                Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
492            }
493            return null;
494        }
495
496        // Remove all of this task's activities starting at the sub task.
497        TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
498        performClearTaskAtIndexLocked(subtask.index);
499        return subtask.activity;
500    }
501
502    boolean isHomeTask() {
503        return taskType == ActivityRecord.HOME_ACTIVITY_TYPE;
504    }
505
506    boolean isApplicationTask() {
507        return taskType == ActivityRecord.APPLICATION_ACTIVITY_TYPE;
508    }
509
510    public TaskAccessInfo getTaskAccessInfoLocked() {
511        final TaskAccessInfo thumbs = new TaskAccessInfo();
512        // How many different sub-thumbnails?
513        final int NA = mActivities.size();
514        int j = 0;
515        ThumbnailHolder holder = null;
516        while (j < NA) {
517            ActivityRecord ar = mActivities.get(j);
518            if (!ar.finishing) {
519                thumbs.root = ar;
520                thumbs.rootIndex = j;
521                holder = ar.thumbHolder;
522                if (holder != null) {
523                    thumbs.mainThumbnail = holder.lastThumbnail;
524                }
525                j++;
526                break;
527            }
528            j++;
529        }
530
531        if (j >= NA) {
532            return thumbs;
533        }
534
535        ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
536        thumbs.subtasks = subtasks;
537        while (j < NA) {
538            ActivityRecord ar = mActivities.get(j);
539            j++;
540            if (ar.finishing) {
541                continue;
542            }
543            if (ar.thumbHolder != holder && holder != null) {
544                thumbs.numSubThumbbails++;
545                holder = ar.thumbHolder;
546                TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
547                sub.holder = holder;
548                sub.activity = ar;
549                sub.index = j-1;
550                subtasks.add(sub);
551            }
552        }
553        if (thumbs.numSubThumbbails > 0) {
554            thumbs.retriever = new IThumbnailRetriever.Stub() {
555                @Override
556                public Bitmap getThumbnail(int index) {
557                    if (index < 0 || index >= thumbs.subtasks.size()) {
558                        return null;
559                    }
560                    TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
561                    ActivityRecord resumedActivity = stack.mResumedActivity;
562                    if (resumedActivity != null && resumedActivity.thumbHolder == sub.holder) {
563                        return stack.screenshotActivities(resumedActivity);
564                    }
565                    return sub.holder.lastThumbnail;
566                }
567            };
568        }
569        return thumbs;
570    }
571
572    /**
573     * Find the activity in the history stack within the given task.  Returns
574     * the index within the history at which it's found, or < 0 if not found.
575     */
576    final ActivityRecord findActivityInHistoryLocked(ActivityRecord r) {
577        final ComponentName realActivity = r.realActivity;
578        for (int activityNdx = mActivities.size() - 1; activityNdx >= 0; --activityNdx) {
579            ActivityRecord candidate = mActivities.get(activityNdx);
580            if (candidate.finishing) {
581                continue;
582            }
583            if (candidate.realActivity.equals(realActivity)) {
584                return candidate;
585            }
586        }
587        return null;
588    }
589
590    /** Updates the last task description values. */
591    void updateTaskDescription() {
592        // Traverse upwards looking for any break between main task activities and
593        // utility activities.
594        int activityNdx;
595        final int numActivities = mActivities.size();
596        final boolean relinquish = numActivities == 0 ? false :
597                (mActivities.get(0).info.flags & ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY) != 0;
598        for (activityNdx = Math.min(numActivities, 1); activityNdx < numActivities;
599                ++activityNdx) {
600            final ActivityRecord r = mActivities.get(activityNdx);
601            if (relinquish && (r.info.flags & ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY) == 0) {
602                // This will be the top activity for determining taskDescription. Pre-inc to
603                // overcome initial decrement below.
604                ++activityNdx;
605                break;
606            }
607            if (r.intent != null &&
608                    (r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
609                break;
610            }
611        }
612        if (activityNdx > 0) {
613            // Traverse downwards starting below break looking for set label, icon.
614            // Note that if there are activities in the task but none of them set the
615            // recent activity values, then we do not fall back to the last set
616            // values in the TaskRecord.
617            String label = null;
618            Bitmap icon = null;
619            int colorPrimary = 0;
620            for (--activityNdx; activityNdx >= 0; --activityNdx) {
621                final ActivityRecord r = mActivities.get(activityNdx);
622                if (r.taskDescription != null) {
623                    if (label == null) {
624                        label = r.taskDescription.getLabel();
625                    }
626                    if (icon == null) {
627                        icon = r.taskDescription.getIcon();
628                    }
629                    if (colorPrimary == 0) {
630                        colorPrimary = r.taskDescription.getPrimaryColor();
631
632                    }
633                }
634            }
635            lastTaskDescription = new ActivityManager.TaskDescription(label, icon, colorPrimary);
636        }
637    }
638
639    int findEffectiveRootIndex() {
640        int activityNdx;
641        final int topActivityNdx = mActivities.size() - 1;
642        for (activityNdx = 0; activityNdx < topActivityNdx; ++activityNdx) {
643            final ActivityRecord r = mActivities.get(activityNdx);
644            if (r.finishing) {
645                continue;
646            }
647            if ((r.info.flags & ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY) == 0) {
648                break;
649            }
650        }
651        return activityNdx;
652    }
653
654    void updateEffectiveIntent() {
655        final int effectiveRootIndex = findEffectiveRootIndex();
656        final ActivityRecord r = mActivities.get(effectiveRootIndex);
657        setIntent(r.intent, r.info);
658    }
659
660    void saveToXml(XmlSerializer out) throws IOException, XmlPullParserException {
661        Slog.i(TAG, "Saving task=" + this);
662
663        out.attribute(null, ATTR_TASKID, String.valueOf(taskId));
664        if (realActivity != null) {
665            out.attribute(null, ATTR_REALACTIVITY, realActivity.flattenToShortString());
666        }
667        if (origActivity != null) {
668            out.attribute(null, ATTR_ORIGACTIVITY, origActivity.flattenToShortString());
669        }
670        if (affinity != null) {
671            out.attribute(null, ATTR_AFFINITY, affinity);
672        }
673        out.attribute(null, ATTR_ROOTHASRESET, String.valueOf(rootWasReset));
674        out.attribute(null, ATTR_ASKEDCOMPATMODE, String.valueOf(askedCompatMode));
675        out.attribute(null, ATTR_USERID, String.valueOf(userId));
676        out.attribute(null, ATTR_TASKTYPE, String.valueOf(taskType));
677        out.attribute(null, ATTR_ONTOPOFHOME, String.valueOf(mOnTopOfHome));
678        out.attribute(null, ATTR_LASTTIMEMOVED, String.valueOf(mLastTimeMoved));
679        out.attribute(null, ATTR_NEVERRELINQUISH, String.valueOf(mNeverRelinquishIdentity));
680        if (lastDescription != null) {
681            out.attribute(null, ATTR_LASTDESCRIPTION, lastDescription.toString());
682        }
683
684        if (affinityIntent != null) {
685            out.startTag(null, TAG_AFFINITYINTENT);
686            affinityIntent.saveToXml(out);
687            out.endTag(null, TAG_AFFINITYINTENT);
688        }
689
690        out.startTag(null, TAG_INTENT);
691        intent.saveToXml(out);
692        out.endTag(null, TAG_INTENT);
693
694        final ArrayList<ActivityRecord> activities = mActivities;
695        final int numActivities = activities.size();
696        for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
697            final ActivityRecord r = activities.get(activityNdx);
698            if (r.info.persistableMode == ActivityInfo.PERSIST_ROOT_ONLY || !r.isPersistable() ||
699                    ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) &&
700                            activityNdx > 0) {
701                // Stop at first non-persistable or first break in task (CLEAR_WHEN_TASK_RESET).
702                break;
703            }
704            out.startTag(null, TAG_ACTIVITY);
705            r.saveToXml(out);
706            out.endTag(null, TAG_ACTIVITY);
707        }
708
709        final Bitmap thumbnail = getTaskTopThumbnailLocked();
710        if (thumbnail != null) {
711            TaskPersister.saveImage(thumbnail, String.valueOf(taskId) + TASK_THUMBNAIL_SUFFIX);
712        }
713    }
714
715    static TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor)
716            throws IOException, XmlPullParserException {
717        Intent intent = null;
718        Intent affinityIntent = null;
719        ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
720        ComponentName realActivity = null;
721        ComponentName origActivity = null;
722        String affinity = null;
723        boolean rootHasReset = false;
724        boolean askedCompatMode = false;
725        int taskType = ActivityRecord.APPLICATION_ACTIVITY_TYPE;
726        boolean onTopOfHome = true;
727        int userId = 0;
728        String lastDescription = null;
729        long lastTimeOnTop = 0;
730        boolean neverRelinquishIdentity = true;
731        int taskId = -1;
732        final int outerDepth = in.getDepth();
733
734        for (int attrNdx = in.getAttributeCount() - 1; attrNdx >= 0; --attrNdx) {
735            final String attrName = in.getAttributeName(attrNdx);
736            final String attrValue = in.getAttributeValue(attrNdx);
737            if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "TaskRecord: attribute name=" +
738                    attrName + " value=" + attrValue);
739            if (ATTR_TASKID.equals(attrName)) {
740                taskId = Integer.valueOf(attrValue);
741            } else if (ATTR_REALACTIVITY.equals(attrName)) {
742                realActivity = ComponentName.unflattenFromString(attrValue);
743            } else if (ATTR_ORIGACTIVITY.equals(attrName)) {
744                origActivity = ComponentName.unflattenFromString(attrValue);
745            } else if (ATTR_AFFINITY.equals(attrName)) {
746                affinity = attrValue;
747            } else if (ATTR_ROOTHASRESET.equals(attrName)) {
748                rootHasReset = Boolean.valueOf(attrValue);
749            } else if (ATTR_ASKEDCOMPATMODE.equals(attrName)) {
750                askedCompatMode = Boolean.valueOf(attrValue);
751            } else if (ATTR_USERID.equals(attrName)) {
752                userId = Integer.valueOf(attrValue);
753            } else if (ATTR_TASKTYPE.equals(attrName)) {
754                taskType = Integer.valueOf(attrValue);
755            } else if (ATTR_ONTOPOFHOME.equals(attrName)) {
756                onTopOfHome = Boolean.valueOf(attrValue);
757            } else if (ATTR_LASTDESCRIPTION.equals(attrName)) {
758                lastDescription = attrValue;
759            } else if (ATTR_LASTTIMEMOVED.equals(attrName)) {
760                lastTimeOnTop = Long.valueOf(attrValue);
761            } else if (ATTR_NEVERRELINQUISH.equals(attrName)) {
762                neverRelinquishIdentity = Boolean.valueOf(attrValue);
763            } else {
764                Slog.w(TAG, "TaskRecord: Unknown attribute=" + attrName);
765            }
766        }
767
768        int event;
769        while (((event = in.next()) != XmlPullParser.END_DOCUMENT) &&
770                (event != XmlPullParser.END_TAG || in.getDepth() < outerDepth)) {
771            if (event == XmlPullParser.START_TAG) {
772                final String name = in.getName();
773                if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "TaskRecord: START_TAG name=" +
774                        name);
775                if (TAG_AFFINITYINTENT.equals(name)) {
776                    affinityIntent = Intent.restoreFromXml(in);
777                } else if (TAG_INTENT.equals(name)) {
778                    intent = Intent.restoreFromXml(in);
779                } else if (TAG_ACTIVITY.equals(name)) {
780                    ActivityRecord activity =
781                            ActivityRecord.restoreFromXml(in, taskId, stackSupervisor);
782                    if (TaskPersister.DEBUG) Slog.d(TaskPersister.TAG, "TaskRecord: activity=" +
783                            activity);
784                    if (activity != null) {
785                        activities.add(activity);
786                    }
787                } else {
788                    Slog.e(TAG, "restoreTask: Unexpected name=" + name);
789                    XmlUtils.skipCurrentTag(in);
790                }
791            }
792        }
793
794        final TaskRecord task = new TaskRecord(stackSupervisor.mService, taskId, intent,
795                affinityIntent, affinity, realActivity, origActivity, rootHasReset,
796                askedCompatMode, taskType, onTopOfHome, userId, lastDescription, activities,
797                lastTimeOnTop, neverRelinquishIdentity);
798
799        for (int activityNdx = activities.size() - 1; activityNdx >=0; --activityNdx) {
800            final ActivityRecord r = activities.get(activityNdx);
801            r.thumbHolder = r.task = task;
802        }
803
804        task.lastThumbnail = TaskPersister.restoreImage(taskId + TASK_THUMBNAIL_SUFFIX);
805
806        Slog.i(TAG, "Restored task=" + task);
807        return task;
808    }
809
810    void dump(PrintWriter pw, String prefix) {
811        if (rootWasReset || userId != 0 || numFullscreen != 0) {
812            pw.print(prefix); pw.print(" rootWasReset="); pw.print(rootWasReset);
813                    pw.print(" userId="); pw.print(userId);
814                    pw.print(" taskType="); pw.print(taskType);
815                    pw.print(" numFullscreen="); pw.print(numFullscreen);
816                    pw.print(" mOnTopOfHome="); pw.println(mOnTopOfHome);
817        }
818        if (affinity != null) {
819            pw.print(prefix); pw.print("affinity="); pw.println(affinity);
820        }
821        if (voiceSession != null || voiceInteractor != null) {
822            pw.print(prefix); pw.print("VOICE: session=0x");
823            pw.print(Integer.toHexString(System.identityHashCode(voiceSession)));
824            pw.print(" interactor=0x");
825            pw.println(Integer.toHexString(System.identityHashCode(voiceInteractor)));
826        }
827        if (intent != null) {
828            StringBuilder sb = new StringBuilder(128);
829            sb.append(prefix); sb.append("intent={");
830            intent.toShortString(sb, false, true, false, true);
831            sb.append('}');
832            pw.println(sb.toString());
833        }
834        if (affinityIntent != null) {
835            StringBuilder sb = new StringBuilder(128);
836            sb.append(prefix); sb.append("affinityIntent={");
837            affinityIntent.toShortString(sb, false, true, false, true);
838            sb.append('}');
839            pw.println(sb.toString());
840        }
841        if (origActivity != null) {
842            pw.print(prefix); pw.print("origActivity=");
843            pw.println(origActivity.flattenToShortString());
844        }
845        if (realActivity != null) {
846            pw.print(prefix); pw.print("realActivity=");
847            pw.println(realActivity.flattenToShortString());
848        }
849        pw.print(prefix); pw.print("Activities="); pw.println(mActivities);
850        if (!askedCompatMode) {
851            pw.print(prefix); pw.print("askedCompatMode="); pw.println(askedCompatMode);
852        }
853        pw.print(prefix); pw.print("lastThumbnail="); pw.print(lastThumbnail);
854                pw.print(" lastDescription="); pw.println(lastDescription);
855        pw.print(prefix); pw.print("hasBeenVisible="); pw.print(hasBeenVisible);
856                pw.print(" lastActiveTime="); pw.print(lastActiveTime);
857                pw.print(" (inactive for ");
858                pw.print((getInactiveDuration()/1000)); pw.println("s)");
859    }
860
861    @Override
862    public String toString() {
863        StringBuilder sb = new StringBuilder(128);
864        if (stringName != null) {
865            sb.append(stringName);
866            sb.append(" U=");
867            sb.append(userId);
868            sb.append(" sz=");
869            sb.append(mActivities.size());
870            sb.append('}');
871            return sb.toString();
872        }
873        sb.append("TaskRecord{");
874        sb.append(Integer.toHexString(System.identityHashCode(this)));
875        sb.append(" #");
876        sb.append(taskId);
877        if (affinity != null) {
878            sb.append(" A=");
879            sb.append(affinity);
880        } else if (intent != null) {
881            sb.append(" I=");
882            sb.append(intent.getComponent().flattenToShortString());
883        } else if (affinityIntent != null) {
884            sb.append(" aI=");
885            sb.append(affinityIntent.getComponent().flattenToShortString());
886        } else {
887            sb.append(" ??");
888        }
889        stringName = sb.toString();
890        return toString();
891    }
892}
893