blob: e77ec206828d21e298c2865abb1047c58f7f57c5 [file] [log] [blame]
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001/*
2 * Copyright (C) 2010 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.HeavyWeightSwitcherActivity;
20import com.android.internal.os.BatteryStatsImpl;
21import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
22
23import android.app.Activity;
24import android.app.AppGlobals;
25import android.app.IActivityManager;
26import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
27import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
28import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
29import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
30import static android.app.IActivityManager.START_PERMISSION_DENIED;
31import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
32import static android.app.IActivityManager.START_SUCCESS;
33import static android.app.IActivityManager.START_SWITCHES_CANCELED;
34import static android.app.IActivityManager.START_TASK_TO_FRONT;
35import android.app.IApplicationThread;
36import android.app.PendingIntent;
37import android.app.ResultInfo;
38import android.app.IActivityManager.WaitResult;
39import android.content.ComponentName;
40import android.content.Context;
41import android.content.IIntentSender;
42import android.content.Intent;
43import android.content.IntentSender;
44import android.content.pm.ActivityInfo;
45import android.content.pm.ApplicationInfo;
46import android.content.pm.PackageManager;
47import android.content.pm.ResolveInfo;
48import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080049import android.content.res.Resources;
50import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070051import android.net.Uri;
52import android.os.Binder;
53import android.os.Bundle;
54import android.os.Handler;
55import android.os.IBinder;
56import android.os.Message;
57import android.os.PowerManager;
58import android.os.RemoteException;
59import android.os.SystemClock;
60import android.util.EventLog;
61import android.util.Log;
62import android.util.Slog;
63import android.view.WindowManagerPolicy;
64
65import java.lang.ref.WeakReference;
66import java.util.ArrayList;
67import java.util.Iterator;
68import java.util.List;
69
70/**
71 * State and management of a single stack of activities.
72 */
73public class ActivityStack {
74 static final String TAG = ActivityManagerService.TAG;
75 static final boolean localLOGV = ActivityManagerService.localLOGV;
76 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
77 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
78 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
79 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
80 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
81 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
82 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
83 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
84
85 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
86
87 // How long we wait until giving up on the last activity telling us it
88 // is idle.
89 static final int IDLE_TIMEOUT = 10*1000;
90
91 // How long we wait until giving up on the last activity to pause. This
92 // is short because it directly impacts the responsiveness of starting the
93 // next activity.
94 static final int PAUSE_TIMEOUT = 500;
95
96 // How long we can hold the launch wake lock before giving up.
97 static final int LAUNCH_TIMEOUT = 10*1000;
98
99 // How long we wait until giving up on an activity telling us it has
100 // finished destroying itself.
101 static final int DESTROY_TIMEOUT = 10*1000;
102
103 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800104 // disabled.
105 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700106
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700107 // How long between activity launches that we consider safe to not warn
108 // the user about an unexpected activity being launched on top.
109 static final long START_WARN_TIME = 5*1000;
110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700111 // Set to false to disable the preview that is shown while a new activity
112 // is being started.
113 static final boolean SHOW_APP_STARTING_PREVIEW = true;
114
115 enum ActivityState {
116 INITIALIZING,
117 RESUMED,
118 PAUSING,
119 PAUSED,
120 STOPPING,
121 STOPPED,
122 FINISHING,
123 DESTROYING,
124 DESTROYED
125 }
126
127 final ActivityManagerService mService;
128 final boolean mMainStack;
129
130 final Context mContext;
131
132 /**
133 * The back history of all previous (and possibly still
134 * running) activities. It contains HistoryRecord objects.
135 */
136 final ArrayList mHistory = new ArrayList();
137
138 /**
139 * List of running activities, sorted by recent usage.
140 * The first entry in the list is the least recently used.
141 * It contains HistoryRecord objects.
142 */
143 final ArrayList mLRUActivities = new ArrayList();
144
145 /**
146 * List of activities that are waiting for a new activity
147 * to become visible before completing whatever operation they are
148 * supposed to do.
149 */
150 final ArrayList<ActivityRecord> mWaitingVisibleActivities
151 = new ArrayList<ActivityRecord>();
152
153 /**
154 * List of activities that are ready to be stopped, but waiting
155 * for the next activity to settle down before doing so. It contains
156 * HistoryRecord objects.
157 */
158 final ArrayList<ActivityRecord> mStoppingActivities
159 = new ArrayList<ActivityRecord>();
160
161 /**
162 * Animations that for the current transition have requested not to
163 * be considered for the transition animation.
164 */
165 final ArrayList<ActivityRecord> mNoAnimActivities
166 = new ArrayList<ActivityRecord>();
167
168 /**
169 * List of activities that are ready to be finished, but waiting
170 * for the previous activity to settle down before doing so. It contains
171 * HistoryRecord objects.
172 */
173 final ArrayList<ActivityRecord> mFinishingActivities
174 = new ArrayList<ActivityRecord>();
175
176 /**
177 * List of people waiting to find out about the next launched activity.
178 */
179 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
180 = new ArrayList<IActivityManager.WaitResult>();
181
182 /**
183 * List of people waiting to find out about the next visible activity.
184 */
185 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
186 = new ArrayList<IActivityManager.WaitResult>();
187
188 /**
189 * Set when the system is going to sleep, until we have
190 * successfully paused the current activity and released our wake lock.
191 * At that point the system is allowed to actually sleep.
192 */
193 final PowerManager.WakeLock mGoingToSleep;
194
195 /**
196 * We don't want to allow the device to go to sleep while in the process
197 * of launching an activity. This is primarily to allow alarm intent
198 * receivers to launch an activity and get that to run before the device
199 * goes back to sleep.
200 */
201 final PowerManager.WakeLock mLaunchingActivity;
202
203 /**
204 * When we are in the process of pausing an activity, before starting the
205 * next one, this variable holds the activity that is currently being paused.
206 */
207 ActivityRecord mPausingActivity = null;
208
209 /**
210 * This is the last activity that we put into the paused state. This is
211 * used to determine if we need to do an activity transition while sleeping,
212 * when we normally hold the top activity paused.
213 */
214 ActivityRecord mLastPausedActivity = null;
215
216 /**
217 * Current activity that is resumed, or null if there is none.
218 */
219 ActivityRecord mResumedActivity = null;
220
221 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700222 * This is the last activity that has been started. It is only used to
223 * identify when multiple activities are started at once so that the user
224 * can be warned they may not be in the activity they think they are.
225 */
226 ActivityRecord mLastStartedActivity = null;
227
228 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700229 * Set when we know we are going to be calling updateConfiguration()
230 * soon, so want to skip intermediate config checks.
231 */
232 boolean mConfigWillChange;
233
234 /**
235 * Set to indicate whether to issue an onUserLeaving callback when a
236 * newly launched activity is being brought in front of us.
237 */
238 boolean mUserLeaving = false;
239
240 long mInitialStartTime = 0;
241
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800242 int mThumbnailWidth = -1;
243 int mThumbnailHeight = -1;
244
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700245 static final int PAUSE_TIMEOUT_MSG = 9;
246 static final int IDLE_TIMEOUT_MSG = 10;
247 static final int IDLE_NOW_MSG = 11;
248 static final int LAUNCH_TIMEOUT_MSG = 16;
249 static final int DESTROY_TIMEOUT_MSG = 17;
250 static final int RESUME_TOP_ACTIVITY_MSG = 19;
251
252 final Handler mHandler = new Handler() {
253 //public Handler() {
254 // if (localLOGV) Slog.v(TAG, "Handler started!");
255 //}
256
257 public void handleMessage(Message msg) {
258 switch (msg.what) {
259 case PAUSE_TIMEOUT_MSG: {
260 IBinder token = (IBinder)msg.obj;
261 // We don't at this point know if the activity is fullscreen,
262 // so we need to be conservative and assume it isn't.
263 Slog.w(TAG, "Activity pause timeout for " + token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800264 activityPaused(token, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700265 } break;
266 case IDLE_TIMEOUT_MSG: {
267 if (mService.mDidDexOpt) {
268 mService.mDidDexOpt = false;
269 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
270 nmsg.obj = msg.obj;
271 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
272 return;
273 }
274 // We don't at this point know if the activity is fullscreen,
275 // so we need to be conservative and assume it isn't.
276 IBinder token = (IBinder)msg.obj;
277 Slog.w(TAG, "Activity idle timeout for " + token);
278 activityIdleInternal(token, true, null);
279 } break;
280 case DESTROY_TIMEOUT_MSG: {
281 IBinder token = (IBinder)msg.obj;
282 // We don't at this point know if the activity is fullscreen,
283 // so we need to be conservative and assume it isn't.
284 Slog.w(TAG, "Activity destroy timeout for " + token);
285 activityDestroyed(token);
286 } break;
287 case IDLE_NOW_MSG: {
288 IBinder token = (IBinder)msg.obj;
289 activityIdleInternal(token, false, null);
290 } break;
291 case LAUNCH_TIMEOUT_MSG: {
292 if (mService.mDidDexOpt) {
293 mService.mDidDexOpt = false;
294 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
295 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
296 return;
297 }
298 synchronized (mService) {
299 if (mLaunchingActivity.isHeld()) {
300 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
301 mLaunchingActivity.release();
302 }
303 }
304 } break;
305 case RESUME_TOP_ACTIVITY_MSG: {
306 synchronized (mService) {
307 resumeTopActivityLocked(null);
308 }
309 } break;
310 }
311 }
312 };
313
314 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
315 mService = service;
316 mContext = context;
317 mMainStack = mainStack;
318 PowerManager pm =
319 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
320 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
321 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
322 mLaunchingActivity.setReferenceCounted(false);
323 }
324
325 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
326 int i = mHistory.size()-1;
327 while (i >= 0) {
328 ActivityRecord r = (ActivityRecord)mHistory.get(i);
329 if (!r.finishing && r != notTop) {
330 return r;
331 }
332 i--;
333 }
334 return null;
335 }
336
337 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
338 int i = mHistory.size()-1;
339 while (i >= 0) {
340 ActivityRecord r = (ActivityRecord)mHistory.get(i);
341 if (!r.finishing && !r.delayedResume && r != notTop) {
342 return r;
343 }
344 i--;
345 }
346 return null;
347 }
348
349 /**
350 * This is a simplified version of topRunningActivityLocked that provides a number of
351 * optional skip-over modes. It is intended for use with the ActivityController hook only.
352 *
353 * @param token If non-null, any history records matching this token will be skipped.
354 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
355 *
356 * @return Returns the HistoryRecord of the next activity on the stack.
357 */
358 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
359 int i = mHistory.size()-1;
360 while (i >= 0) {
361 ActivityRecord r = (ActivityRecord)mHistory.get(i);
362 // Note: the taskId check depends on real taskId fields being non-zero
363 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
364 return r;
365 }
366 i--;
367 }
368 return null;
369 }
370
371 final int indexOfTokenLocked(IBinder token) {
372 int count = mHistory.size();
373
374 // convert the token to an entry in the history.
375 int index = -1;
376 for (int i=count-1; i>=0; i--) {
377 Object o = mHistory.get(i);
378 if (o == token) {
379 index = i;
380 break;
381 }
382 }
383
384 return index;
385 }
386
387 private final boolean updateLRUListLocked(ActivityRecord r) {
388 final boolean hadit = mLRUActivities.remove(r);
389 mLRUActivities.add(r);
390 return hadit;
391 }
392
393 /**
394 * Returns the top activity in any existing task matching the given
395 * Intent. Returns null if no such task is found.
396 */
397 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
398 ComponentName cls = intent.getComponent();
399 if (info.targetActivity != null) {
400 cls = new ComponentName(info.packageName, info.targetActivity);
401 }
402
403 TaskRecord cp = null;
404
405 final int N = mHistory.size();
406 for (int i=(N-1); i>=0; i--) {
407 ActivityRecord r = (ActivityRecord)mHistory.get(i);
408 if (!r.finishing && r.task != cp
409 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
410 cp = r.task;
411 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
412 // + "/aff=" + r.task.affinity + " to new cls="
413 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
414 if (r.task.affinity != null) {
415 if (r.task.affinity.equals(info.taskAffinity)) {
416 //Slog.i(TAG, "Found matching affinity!");
417 return r;
418 }
419 } else if (r.task.intent != null
420 && r.task.intent.getComponent().equals(cls)) {
421 //Slog.i(TAG, "Found matching class!");
422 //dump();
423 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
424 return r;
425 } else if (r.task.affinityIntent != null
426 && r.task.affinityIntent.getComponent().equals(cls)) {
427 //Slog.i(TAG, "Found matching class!");
428 //dump();
429 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
430 return r;
431 }
432 }
433 }
434
435 return null;
436 }
437
438 /**
439 * Returns the first activity (starting from the top of the stack) that
440 * is the same as the given activity. Returns null if no such activity
441 * is found.
442 */
443 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
444 ComponentName cls = intent.getComponent();
445 if (info.targetActivity != null) {
446 cls = new ComponentName(info.packageName, info.targetActivity);
447 }
448
449 final int N = mHistory.size();
450 for (int i=(N-1); i>=0; i--) {
451 ActivityRecord r = (ActivityRecord)mHistory.get(i);
452 if (!r.finishing) {
453 if (r.intent.getComponent().equals(cls)) {
454 //Slog.i(TAG, "Found matching class!");
455 //dump();
456 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
457 return r;
458 }
459 }
460 }
461
462 return null;
463 }
464
465 final boolean realStartActivityLocked(ActivityRecord r,
466 ProcessRecord app, boolean andResume, boolean checkConfig)
467 throws RemoteException {
468
469 r.startFreezingScreenLocked(app, 0);
470 mService.mWindowManager.setAppVisibility(r, true);
471
472 // Have the window manager re-evaluate the orientation of
473 // the screen based on the new activity order. Note that
474 // as a result of this, it can call back into the activity
475 // manager with a new orientation. We don't care about that,
476 // because the activity is not currently running so we are
477 // just restarting it anyway.
478 if (checkConfig) {
479 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
480 mService.mConfiguration,
481 r.mayFreezeScreenLocked(app) ? r : null);
482 mService.updateConfigurationLocked(config, r);
483 }
484
485 r.app = app;
486
487 if (localLOGV) Slog.v(TAG, "Launching: " + r);
488
489 int idx = app.activities.indexOf(r);
490 if (idx < 0) {
491 app.activities.add(r);
492 }
493 mService.updateLruProcessLocked(app, true, true);
494
495 try {
496 if (app.thread == null) {
497 throw new RemoteException();
498 }
499 List<ResultInfo> results = null;
500 List<Intent> newIntents = null;
501 if (andResume) {
502 results = r.results;
503 newIntents = r.newIntents;
504 }
505 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
506 + " icicle=" + r.icicle
507 + " with results=" + results + " newIntents=" + newIntents
508 + " andResume=" + andResume);
509 if (andResume) {
510 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
511 System.identityHashCode(r),
512 r.task.taskId, r.shortComponentName);
513 }
514 if (r.isHomeActivity) {
515 mService.mHomeProcess = app;
516 }
517 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
518 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
519 System.identityHashCode(r),
520 r.info, r.icicle, results, newIntents, !andResume,
521 mService.isNextTransitionForward());
522
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700523 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700524 // This may be a heavy-weight process! Note that the package
525 // manager will ensure that only activity can run in the main
526 // process of the .apk, which is the only thing that will be
527 // considered heavy-weight.
528 if (app.processName.equals(app.info.packageName)) {
529 if (mService.mHeavyWeightProcess != null
530 && mService.mHeavyWeightProcess != app) {
531 Log.w(TAG, "Starting new heavy weight process " + app
532 + " when already running "
533 + mService.mHeavyWeightProcess);
534 }
535 mService.mHeavyWeightProcess = app;
536 Message msg = mService.mHandler.obtainMessage(
537 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
538 msg.obj = r;
539 mService.mHandler.sendMessage(msg);
540 }
541 }
542
543 } catch (RemoteException e) {
544 if (r.launchFailed) {
545 // This is the second time we failed -- finish activity
546 // and give up.
547 Slog.e(TAG, "Second failure launching "
548 + r.intent.getComponent().flattenToShortString()
549 + ", giving up", e);
550 mService.appDiedLocked(app, app.pid, app.thread);
551 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
552 "2nd-crash");
553 return false;
554 }
555
556 // This is the first time we failed -- restart process and
557 // retry.
558 app.activities.remove(r);
559 throw e;
560 }
561
562 r.launchFailed = false;
563 if (updateLRUListLocked(r)) {
564 Slog.w(TAG, "Activity " + r
565 + " being launched, but already in LRU list");
566 }
567
568 if (andResume) {
569 // As part of the process of launching, ActivityThread also performs
570 // a resume.
571 r.state = ActivityState.RESUMED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700572 r.stopped = false;
573 mResumedActivity = r;
574 r.task.touchActiveTime();
575 completeResumeLocked(r);
576 pauseIfSleepingLocked();
577 } else {
578 // This activity is not starting in the resumed state... which
579 // should look like we asked it to pause+stop (but remain visible),
580 // and it has done so and reported back the current icicle and
581 // other state.
582 r.state = ActivityState.STOPPED;
583 r.stopped = true;
584 }
585
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800586 r.icicle = null;
587 r.haveState = false;
588
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700589 // Launch the new version setup screen if needed. We do this -after-
590 // launching the initial activity (that is, home), so that it can have
591 // a chance to initialize itself while in the background, making the
592 // switch back to it faster and look better.
593 if (mMainStack) {
594 mService.startSetupActivityLocked();
595 }
596
597 return true;
598 }
599
600 private final void startSpecificActivityLocked(ActivityRecord r,
601 boolean andResume, boolean checkConfig) {
602 // Is this activity's application already running?
603 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
604 r.info.applicationInfo.uid);
605
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700606 if (r.launchTime == 0) {
607 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700608 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700609 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700610 }
611 } else if (mInitialStartTime == 0) {
612 mInitialStartTime = SystemClock.uptimeMillis();
613 }
614
615 if (app != null && app.thread != null) {
616 try {
617 realStartActivityLocked(r, app, andResume, checkConfig);
618 return;
619 } catch (RemoteException e) {
620 Slog.w(TAG, "Exception when starting activity "
621 + r.intent.getComponent().flattenToShortString(), e);
622 }
623
624 // If a dead object exception was thrown -- fall through to
625 // restart the application.
626 }
627
628 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
629 "activity", r.intent.getComponent(), false);
630 }
631
632 void pauseIfSleepingLocked() {
633 if (mService.mSleeping || mService.mShuttingDown) {
634 if (!mGoingToSleep.isHeld()) {
635 mGoingToSleep.acquire();
636 if (mLaunchingActivity.isHeld()) {
637 mLaunchingActivity.release();
638 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
639 }
640 }
641
642 // If we are not currently pausing an activity, get the current
643 // one to pause. If we are pausing one, we will just let that stuff
644 // run and release the wake lock when all done.
645 if (mPausingActivity == null) {
646 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause...");
647 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
648 startPausingLocked(false, true);
649 }
650 }
651 }
652
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800653 public final Bitmap screenshotActivities() {
654 Resources res = mService.mContext.getResources();
655 int w = mThumbnailWidth;
656 int h = mThumbnailHeight;
657 if (w < 0) {
658 mThumbnailWidth = w =
659 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
660 mThumbnailHeight = h =
661 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
662 }
663
664 if (w > 0) {
665 return mService.mWindowManager.screenshotApplications(w, h);
666 }
667 return null;
668 }
669
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700670 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
671 if (mPausingActivity != null) {
672 RuntimeException e = new RuntimeException();
673 Slog.e(TAG, "Trying to pause when pause is already pending for "
674 + mPausingActivity, e);
675 }
676 ActivityRecord prev = mResumedActivity;
677 if (prev == null) {
678 RuntimeException e = new RuntimeException();
679 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
680 resumeTopActivityLocked(null);
681 return;
682 }
683 if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
684 mResumedActivity = null;
685 mPausingActivity = prev;
686 mLastPausedActivity = prev;
687 prev.state = ActivityState.PAUSING;
688 prev.task.touchActiveTime();
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800689 prev.thumbnail = screenshotActivities();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700690
691 mService.updateCpuStats();
692
693 if (prev.app != null && prev.app.thread != null) {
694 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
695 try {
696 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
697 System.identityHashCode(prev),
698 prev.shortComponentName);
699 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
700 prev.configChangeFlags);
701 if (mMainStack) {
702 mService.updateUsageStats(prev, false);
703 }
704 } catch (Exception e) {
705 // Ignore exception, if process died other code will cleanup.
706 Slog.w(TAG, "Exception thrown during pause", e);
707 mPausingActivity = null;
708 mLastPausedActivity = null;
709 }
710 } else {
711 mPausingActivity = null;
712 mLastPausedActivity = null;
713 }
714
715 // If we are not going to sleep, we want to ensure the device is
716 // awake until the next activity is started.
717 if (!mService.mSleeping && !mService.mShuttingDown) {
718 mLaunchingActivity.acquire();
719 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
720 // To be safe, don't allow the wake lock to be held for too long.
721 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
722 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
723 }
724 }
725
726
727 if (mPausingActivity != null) {
728 // Have the window manager pause its key dispatching until the new
729 // activity has started. If we're pausing the activity just because
730 // the screen is being turned off and the UI is sleeping, don't interrupt
731 // key dispatch; the same activity will pick it up again on wakeup.
732 if (!uiSleeping) {
733 prev.pauseKeyDispatchingLocked();
734 } else {
735 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
736 }
737
738 // Schedule a pause timeout in case the app doesn't respond.
739 // We don't give it much time because this directly impacts the
740 // responsiveness seen by the user.
741 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
742 msg.obj = prev;
743 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
744 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
745 } else {
746 // This activity failed to schedule the
747 // pause, so just treat it as being paused now.
748 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
749 resumeTopActivityLocked(null);
750 }
751 }
752
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800753 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700754 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800755 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700756
757 ActivityRecord r = null;
758
759 synchronized (mService) {
760 int index = indexOfTokenLocked(token);
761 if (index >= 0) {
762 r = (ActivityRecord)mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700763 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
764 if (mPausingActivity == r) {
765 r.state = ActivityState.PAUSED;
766 completePauseLocked();
767 } else {
768 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
769 System.identityHashCode(r), r.shortComponentName,
770 mPausingActivity != null
771 ? mPausingActivity.shortComponentName : "(none)");
772 }
773 }
774 }
775 }
776
777 private final void completePauseLocked() {
778 ActivityRecord prev = mPausingActivity;
779 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
780
781 if (prev != null) {
782 if (prev.finishing) {
783 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
784 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
785 } else if (prev.app != null) {
786 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
787 if (prev.waitingVisible) {
788 prev.waitingVisible = false;
789 mWaitingVisibleActivities.remove(prev);
790 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
791 TAG, "Complete pause, no longer waiting: " + prev);
792 }
793 if (prev.configDestroy) {
794 // The previous is being paused because the configuration
795 // is changing, which means it is actually stopping...
796 // To juggle the fact that we are also starting a new
797 // instance right now, we need to first completely stop
798 // the current instance before starting the new one.
799 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
800 destroyActivityLocked(prev, true);
801 } else {
802 mStoppingActivities.add(prev);
803 if (mStoppingActivities.size() > 3) {
804 // If we already have a few activities waiting to stop,
805 // then give up on things going idle and start clearing
806 // them out.
807 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
808 Message msg = Message.obtain();
809 msg.what = IDLE_NOW_MSG;
810 mHandler.sendMessage(msg);
811 }
812 }
813 } else {
814 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
815 prev = null;
816 }
817 mPausingActivity = null;
818 }
819
820 if (!mService.mSleeping && !mService.mShuttingDown) {
821 resumeTopActivityLocked(prev);
822 } else {
823 if (mGoingToSleep.isHeld()) {
824 mGoingToSleep.release();
825 }
826 if (mService.mShuttingDown) {
827 mService.notifyAll();
828 }
829 }
830
831 if (prev != null) {
832 prev.resumeKeyDispatchingLocked();
833 }
834
835 if (prev.app != null && prev.cpuTimeAtResume > 0
836 && mService.mBatteryStatsService.isOnBattery()) {
837 long diff = 0;
838 synchronized (mService.mProcessStatsThread) {
839 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
840 - prev.cpuTimeAtResume;
841 }
842 if (diff > 0) {
843 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
844 synchronized (bsi) {
845 BatteryStatsImpl.Uid.Proc ps =
846 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
847 prev.info.packageName);
848 if (ps != null) {
849 ps.addForegroundTimeLocked(diff);
850 }
851 }
852 }
853 }
854 prev.cpuTimeAtResume = 0; // reset it
855 }
856
857 /**
858 * Once we know that we have asked an application to put an activity in
859 * the resumed state (either by launching it or explicitly telling it),
860 * this function updates the rest of our state to match that fact.
861 */
862 private final void completeResumeLocked(ActivityRecord next) {
863 next.idle = false;
864 next.results = null;
865 next.newIntents = null;
866
867 // schedule an idle timeout in case the app doesn't do it for us.
868 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
869 msg.obj = next;
870 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
871
872 if (false) {
873 // The activity was never told to pause, so just keep
874 // things going as-is. To maintain our own state,
875 // we need to emulate it coming back and saying it is
876 // idle.
877 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
878 msg.obj = next;
879 mHandler.sendMessage(msg);
880 }
881
882 if (mMainStack) {
883 mService.reportResumedActivityLocked(next);
884 }
885
886 next.thumbnail = null;
887 if (mMainStack) {
888 mService.setFocusedActivityLocked(next);
889 }
890 next.resumeKeyDispatchingLocked();
891 ensureActivitiesVisibleLocked(null, 0);
892 mService.mWindowManager.executeAppTransition();
893 mNoAnimActivities.clear();
894
895 // Mark the point when the activity is resuming
896 // TODO: To be more accurate, the mark should be before the onCreate,
897 // not after the onResume. But for subsequent starts, onResume is fine.
898 if (next.app != null) {
899 synchronized (mService.mProcessStatsThread) {
900 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
901 }
902 } else {
903 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
904 }
905 }
906
907 /**
908 * Make sure that all activities that need to be visible (that is, they
909 * currently can be seen by the user) actually are.
910 */
911 final void ensureActivitiesVisibleLocked(ActivityRecord top,
912 ActivityRecord starting, String onlyThisProcess, int configChanges) {
913 if (DEBUG_VISBILITY) Slog.v(
914 TAG, "ensureActivitiesVisible behind " + top
915 + " configChanges=0x" + Integer.toHexString(configChanges));
916
917 // If the top activity is not fullscreen, then we need to
918 // make sure any activities under it are now visible.
919 final int count = mHistory.size();
920 int i = count-1;
921 while (mHistory.get(i) != top) {
922 i--;
923 }
924 ActivityRecord r;
925 boolean behindFullscreen = false;
926 for (; i>=0; i--) {
927 r = (ActivityRecord)mHistory.get(i);
928 if (DEBUG_VISBILITY) Slog.v(
929 TAG, "Make visible? " + r + " finishing=" + r.finishing
930 + " state=" + r.state);
931 if (r.finishing) {
932 continue;
933 }
934
935 final boolean doThisProcess = onlyThisProcess == null
936 || onlyThisProcess.equals(r.processName);
937
938 // First: if this is not the current activity being started, make
939 // sure it matches the current configuration.
940 if (r != starting && doThisProcess) {
941 ensureActivityConfigurationLocked(r, 0);
942 }
943
944 if (r.app == null || r.app.thread == null) {
945 if (onlyThisProcess == null
946 || onlyThisProcess.equals(r.processName)) {
947 // This activity needs to be visible, but isn't even
948 // running... get it started, but don't resume it
949 // at this point.
950 if (DEBUG_VISBILITY) Slog.v(
951 TAG, "Start and freeze screen for " + r);
952 if (r != starting) {
953 r.startFreezingScreenLocked(r.app, configChanges);
954 }
955 if (!r.visible) {
956 if (DEBUG_VISBILITY) Slog.v(
957 TAG, "Starting and making visible: " + r);
958 mService.mWindowManager.setAppVisibility(r, true);
959 }
960 if (r != starting) {
961 startSpecificActivityLocked(r, false, false);
962 }
963 }
964
965 } else if (r.visible) {
966 // If this activity is already visible, then there is nothing
967 // else to do here.
968 if (DEBUG_VISBILITY) Slog.v(
969 TAG, "Skipping: already visible at " + r);
970 r.stopFreezingScreenLocked(false);
971
972 } else if (onlyThisProcess == null) {
973 // This activity is not currently visible, but is running.
974 // Tell it to become visible.
975 r.visible = true;
976 if (r.state != ActivityState.RESUMED && r != starting) {
977 // If this activity is paused, tell it
978 // to now show its window.
979 if (DEBUG_VISBILITY) Slog.v(
980 TAG, "Making visible and scheduling visibility: " + r);
981 try {
982 mService.mWindowManager.setAppVisibility(r, true);
983 r.app.thread.scheduleWindowVisibility(r, true);
984 r.stopFreezingScreenLocked(false);
985 } catch (Exception e) {
986 // Just skip on any failure; we'll make it
987 // visible when it next restarts.
988 Slog.w(TAG, "Exception thrown making visibile: "
989 + r.intent.getComponent(), e);
990 }
991 }
992 }
993
994 // Aggregate current change flags.
995 configChanges |= r.configChangeFlags;
996
997 if (r.fullscreen) {
998 // At this point, nothing else needs to be shown
999 if (DEBUG_VISBILITY) Slog.v(
1000 TAG, "Stopping: fullscreen at " + r);
1001 behindFullscreen = true;
1002 i--;
1003 break;
1004 }
1005 }
1006
1007 // Now for any activities that aren't visible to the user, make
1008 // sure they no longer are keeping the screen frozen.
1009 while (i >= 0) {
1010 r = (ActivityRecord)mHistory.get(i);
1011 if (DEBUG_VISBILITY) Slog.v(
1012 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1013 + " state=" + r.state
1014 + " behindFullscreen=" + behindFullscreen);
1015 if (!r.finishing) {
1016 if (behindFullscreen) {
1017 if (r.visible) {
1018 if (DEBUG_VISBILITY) Slog.v(
1019 TAG, "Making invisible: " + r);
1020 r.visible = false;
1021 try {
1022 mService.mWindowManager.setAppVisibility(r, false);
1023 if ((r.state == ActivityState.STOPPING
1024 || r.state == ActivityState.STOPPED)
1025 && r.app != null && r.app.thread != null) {
1026 if (DEBUG_VISBILITY) Slog.v(
1027 TAG, "Scheduling invisibility: " + r);
1028 r.app.thread.scheduleWindowVisibility(r, false);
1029 }
1030 } catch (Exception e) {
1031 // Just skip on any failure; we'll make it
1032 // visible when it next restarts.
1033 Slog.w(TAG, "Exception thrown making hidden: "
1034 + r.intent.getComponent(), e);
1035 }
1036 } else {
1037 if (DEBUG_VISBILITY) Slog.v(
1038 TAG, "Already invisible: " + r);
1039 }
1040 } else if (r.fullscreen) {
1041 if (DEBUG_VISBILITY) Slog.v(
1042 TAG, "Now behindFullscreen: " + r);
1043 behindFullscreen = true;
1044 }
1045 }
1046 i--;
1047 }
1048 }
1049
1050 /**
1051 * Version of ensureActivitiesVisible that can easily be called anywhere.
1052 */
1053 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1054 int configChanges) {
1055 ActivityRecord r = topRunningActivityLocked(null);
1056 if (r != null) {
1057 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1058 }
1059 }
1060
1061 /**
1062 * Ensure that the top activity in the stack is resumed.
1063 *
1064 * @param prev The previously resumed activity, for when in the process
1065 * of pausing; can be null to call from elsewhere.
1066 *
1067 * @return Returns true if something is being resumed, or false if
1068 * nothing happened.
1069 */
1070 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1071 // Find the first activity that is not finishing.
1072 ActivityRecord next = topRunningActivityLocked(null);
1073
1074 // Remember how we'll process this pause/resume situation, and ensure
1075 // that the state is reset however we wind up proceeding.
1076 final boolean userLeaving = mUserLeaving;
1077 mUserLeaving = false;
1078
1079 if (next == null) {
1080 // There are no more activities! Let's just start up the
1081 // Launcher...
1082 if (mMainStack) {
1083 return mService.startHomeActivityLocked();
1084 }
1085 }
1086
1087 next.delayedResume = false;
1088
1089 // If the top activity is the resumed one, nothing to do.
1090 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1091 // Make sure we have executed any pending transitions, since there
1092 // should be nothing left to do at this point.
1093 mService.mWindowManager.executeAppTransition();
1094 mNoAnimActivities.clear();
1095 return false;
1096 }
1097
1098 // If we are sleeping, and there is no resumed activity, and the top
1099 // activity is paused, well that is the state we want.
1100 if ((mService.mSleeping || mService.mShuttingDown)
1101 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1102 // Make sure we have executed any pending transitions, since there
1103 // should be nothing left to do at this point.
1104 mService.mWindowManager.executeAppTransition();
1105 mNoAnimActivities.clear();
1106 return false;
1107 }
1108
1109 // The activity may be waiting for stop, but that is no longer
1110 // appropriate for it.
1111 mStoppingActivities.remove(next);
1112 mWaitingVisibleActivities.remove(next);
1113
1114 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1115
1116 // If we are currently pausing an activity, then don't do anything
1117 // until that is done.
1118 if (mPausingActivity != null) {
1119 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1120 return false;
1121 }
1122
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001123 // Okay we are now going to start a switch, to 'next'. We may first
1124 // have to pause the current activity, but this is an important point
1125 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001126 // XXX "App Redirected" dialog is getting too many false positives
1127 // at this point, so turn off for now.
1128 if (false) {
1129 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1130 long now = SystemClock.uptimeMillis();
1131 final boolean inTime = mLastStartedActivity.startTime != 0
1132 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1133 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1134 final int nextUid = next.info.applicationInfo.uid;
1135 if (inTime && lastUid != nextUid
1136 && lastUid != next.launchedFromUid
1137 && mService.checkPermission(
1138 android.Manifest.permission.STOP_APP_SWITCHES,
1139 -1, next.launchedFromUid)
1140 != PackageManager.PERMISSION_GRANTED) {
1141 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1142 } else {
1143 next.startTime = now;
1144 mLastStartedActivity = next;
1145 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001146 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001147 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001148 mLastStartedActivity = next;
1149 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001150 }
1151
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001152 // We need to start pausing the current activity so the top one
1153 // can be resumed...
1154 if (mResumedActivity != null) {
1155 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1156 startPausingLocked(userLeaving, false);
1157 return true;
1158 }
1159
1160 if (prev != null && prev != next) {
1161 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1162 prev.waitingVisible = true;
1163 mWaitingVisibleActivities.add(prev);
1164 if (DEBUG_SWITCH) Slog.v(
1165 TAG, "Resuming top, waiting visible to hide: " + prev);
1166 } else {
1167 // The next activity is already visible, so hide the previous
1168 // activity's windows right now so we can show the new one ASAP.
1169 // We only do this if the previous is finishing, which should mean
1170 // it is on top of the one being resumed so hiding it quickly
1171 // is good. Otherwise, we want to do the normal route of allowing
1172 // the resumed activity to be shown so we can decide if the
1173 // previous should actually be hidden depending on whether the
1174 // new one is found to be full-screen or not.
1175 if (prev.finishing) {
1176 mService.mWindowManager.setAppVisibility(prev, false);
1177 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1178 + prev + ", waitingVisible="
1179 + (prev != null ? prev.waitingVisible : null)
1180 + ", nowVisible=" + next.nowVisible);
1181 } else {
1182 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1183 + prev + ", waitingVisible="
1184 + (prev != null ? prev.waitingVisible : null)
1185 + ", nowVisible=" + next.nowVisible);
1186 }
1187 }
1188 }
1189
1190 // We are starting up the next activity, so tell the window manager
1191 // that the previous one will be hidden soon. This way it can know
1192 // to ignore it when computing the desired screen orientation.
1193 if (prev != null) {
1194 if (prev.finishing) {
1195 if (DEBUG_TRANSITION) Slog.v(TAG,
1196 "Prepare close transition: prev=" + prev);
1197 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001198 mService.mWindowManager.prepareAppTransition(
1199 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001200 } else {
1201 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1202 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001203 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001204 }
1205 mService.mWindowManager.setAppWillBeHidden(prev);
1206 mService.mWindowManager.setAppVisibility(prev, false);
1207 } else {
1208 if (DEBUG_TRANSITION) Slog.v(TAG,
1209 "Prepare open transition: prev=" + prev);
1210 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001211 mService.mWindowManager.prepareAppTransition(
1212 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001213 } else {
1214 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1215 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001216 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001217 }
1218 }
1219 if (false) {
1220 mService.mWindowManager.setAppWillBeHidden(prev);
1221 mService.mWindowManager.setAppVisibility(prev, false);
1222 }
1223 } else if (mHistory.size() > 1) {
1224 if (DEBUG_TRANSITION) Slog.v(TAG,
1225 "Prepare open transition: no previous");
1226 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001227 mService.mWindowManager.prepareAppTransition(
1228 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001229 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001230 mService.mWindowManager.prepareAppTransition(
1231 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001232 }
1233 }
1234
1235 if (next.app != null && next.app.thread != null) {
1236 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1237
1238 // This activity is now becoming visible.
1239 mService.mWindowManager.setAppVisibility(next, true);
1240
1241 ActivityRecord lastResumedActivity = mResumedActivity;
1242 ActivityState lastState = next.state;
1243
1244 mService.updateCpuStats();
1245
1246 next.state = ActivityState.RESUMED;
1247 mResumedActivity = next;
1248 next.task.touchActiveTime();
1249 mService.updateLruProcessLocked(next.app, true, true);
1250 updateLRUListLocked(next);
1251
1252 // Have the window manager re-evaluate the orientation of
1253 // the screen based on the new activity order.
1254 boolean updated = false;
1255 if (mMainStack) {
1256 synchronized (mService) {
1257 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1258 mService.mConfiguration,
1259 next.mayFreezeScreenLocked(next.app) ? next : null);
1260 if (config != null) {
1261 next.frozenBeforeDestroy = true;
1262 }
1263 updated = mService.updateConfigurationLocked(config, next);
1264 }
1265 }
1266 if (!updated) {
1267 // The configuration update wasn't able to keep the existing
1268 // instance of the activity, and instead started a new one.
1269 // We should be all done, but let's just make sure our activity
1270 // is still at the top and schedule another run if something
1271 // weird happened.
1272 ActivityRecord nextNext = topRunningActivityLocked(null);
1273 if (DEBUG_SWITCH) Slog.i(TAG,
1274 "Activity config changed during resume: " + next
1275 + ", new next: " + nextNext);
1276 if (nextNext != next) {
1277 // Do over!
1278 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1279 }
1280 if (mMainStack) {
1281 mService.setFocusedActivityLocked(next);
1282 }
1283 ensureActivitiesVisibleLocked(null, 0);
1284 mService.mWindowManager.executeAppTransition();
1285 mNoAnimActivities.clear();
1286 return true;
1287 }
1288
1289 try {
1290 // Deliver all pending results.
1291 ArrayList a = next.results;
1292 if (a != null) {
1293 final int N = a.size();
1294 if (!next.finishing && N > 0) {
1295 if (DEBUG_RESULTS) Slog.v(
1296 TAG, "Delivering results to " + next
1297 + ": " + a);
1298 next.app.thread.scheduleSendResult(next, a);
1299 }
1300 }
1301
1302 if (next.newIntents != null) {
1303 next.app.thread.scheduleNewIntent(next.newIntents, next);
1304 }
1305
1306 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1307 System.identityHashCode(next),
1308 next.task.taskId, next.shortComponentName);
1309
1310 next.app.thread.scheduleResumeActivity(next,
1311 mService.isNextTransitionForward());
1312
1313 pauseIfSleepingLocked();
1314
1315 } catch (Exception e) {
1316 // Whoops, need to restart this activity!
1317 next.state = lastState;
1318 mResumedActivity = lastResumedActivity;
1319 Slog.i(TAG, "Restarting because process died: " + next);
1320 if (!next.hasBeenLaunched) {
1321 next.hasBeenLaunched = true;
1322 } else {
1323 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1324 mService.mWindowManager.setAppStartingWindow(
1325 next, next.packageName, next.theme,
1326 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001327 next.labelRes, next.icon, next.windowFlags,
1328 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001329 }
1330 }
1331 startSpecificActivityLocked(next, true, false);
1332 return true;
1333 }
1334
1335 // From this point on, if something goes wrong there is no way
1336 // to recover the activity.
1337 try {
1338 next.visible = true;
1339 completeResumeLocked(next);
1340 } catch (Exception e) {
1341 // If any exception gets thrown, toss away this
1342 // activity and try the next one.
1343 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1344 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1345 "resume-exception");
1346 return true;
1347 }
1348
1349 // Didn't need to use the icicle, and it is now out of date.
1350 next.icicle = null;
1351 next.haveState = false;
1352 next.stopped = false;
1353
1354 } else {
1355 // Whoops, need to restart this activity!
1356 if (!next.hasBeenLaunched) {
1357 next.hasBeenLaunched = true;
1358 } else {
1359 if (SHOW_APP_STARTING_PREVIEW) {
1360 mService.mWindowManager.setAppStartingWindow(
1361 next, next.packageName, next.theme,
1362 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001363 next.labelRes, next.icon, next.windowFlags,
1364 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001365 }
1366 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1367 }
1368 startSpecificActivityLocked(next, true, true);
1369 }
1370
1371 return true;
1372 }
1373
1374 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001375 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001376 final int NH = mHistory.size();
1377
1378 int addPos = -1;
1379
1380 if (!newTask) {
1381 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001382 boolean startIt = true;
1383 for (int i = NH-1; i >= 0; i--) {
1384 ActivityRecord p = (ActivityRecord)mHistory.get(i);
1385 if (p.finishing) {
1386 continue;
1387 }
1388 if (p.task == r.task) {
1389 // Here it is! Now, if this is not yet visible to the
1390 // user, then just add it without starting; it will
1391 // get started when the user navigates back to it.
1392 addPos = i+1;
1393 if (!startIt) {
1394 mHistory.add(addPos, r);
1395 r.inHistory = true;
1396 r.task.numActivities++;
1397 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1398 r.info.screenOrientation, r.fullscreen);
1399 if (VALIDATE_TOKENS) {
1400 mService.mWindowManager.validateAppTokens(mHistory);
1401 }
1402 return;
1403 }
1404 break;
1405 }
1406 if (p.fullscreen) {
1407 startIt = false;
1408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001409 }
1410 }
1411
1412 // Place a new activity at top of stack, so it is next to interact
1413 // with the user.
1414 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001415 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001416 }
1417
1418 // If we are not placing the new activity frontmost, we do not want
1419 // to deliver the onUserLeaving callback to the actual frontmost
1420 // activity
1421 if (addPos < NH) {
1422 mUserLeaving = false;
1423 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1424 }
1425
1426 // Slot the activity into the history stack and proceed
1427 mHistory.add(addPos, r);
1428 r.inHistory = true;
1429 r.frontOfTask = newTask;
1430 r.task.numActivities++;
1431 if (NH > 0) {
1432 // We want to show the starting preview window if we are
1433 // switching to a new task, or the next activity's process is
1434 // not currently running.
1435 boolean showStartingIcon = newTask;
1436 ProcessRecord proc = r.app;
1437 if (proc == null) {
1438 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1439 }
1440 if (proc == null || proc.thread == null) {
1441 showStartingIcon = true;
1442 }
1443 if (DEBUG_TRANSITION) Slog.v(TAG,
1444 "Prepare open transition: starting " + r);
1445 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001446 mService.mWindowManager.prepareAppTransition(
1447 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001448 mNoAnimActivities.add(r);
1449 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1450 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001451 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001452 mNoAnimActivities.remove(r);
1453 } else {
1454 mService.mWindowManager.prepareAppTransition(newTask
1455 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001456 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001457 mNoAnimActivities.remove(r);
1458 }
1459 mService.mWindowManager.addAppToken(
1460 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1461 boolean doShow = true;
1462 if (newTask) {
1463 // Even though this activity is starting fresh, we still need
1464 // to reset it to make sure we apply affinities to move any
1465 // existing activities from other tasks in to it.
1466 // If the caller has requested that the target task be
1467 // reset, then do so.
1468 if ((r.intent.getFlags()
1469 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1470 resetTaskIfNeededLocked(r, r);
1471 doShow = topRunningNonDelayedActivityLocked(null) == r;
1472 }
1473 }
1474 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1475 // Figure out if we are transitioning from another activity that is
1476 // "has the same starting icon" as the next one. This allows the
1477 // window manager to keep the previous window it had previously
1478 // created, if it still had one.
1479 ActivityRecord prev = mResumedActivity;
1480 if (prev != null) {
1481 // We don't want to reuse the previous starting preview if:
1482 // (1) The current activity is in a different task.
1483 if (prev.task != r.task) prev = null;
1484 // (2) The current activity is already displayed.
1485 else if (prev.nowVisible) prev = null;
1486 }
1487 mService.mWindowManager.setAppStartingWindow(
1488 r, r.packageName, r.theme, r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001489 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001490 }
1491 } else {
1492 // If this is the first activity, don't do any fancy animations,
1493 // because there is nothing for it to animate on top of.
1494 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1495 r.info.screenOrientation, r.fullscreen);
1496 }
1497 if (VALIDATE_TOKENS) {
1498 mService.mWindowManager.validateAppTokens(mHistory);
1499 }
1500
1501 if (doResume) {
1502 resumeTopActivityLocked(null);
1503 }
1504 }
1505
1506 /**
1507 * Perform a reset of the given task, if needed as part of launching it.
1508 * Returns the new HistoryRecord at the top of the task.
1509 */
1510 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1511 ActivityRecord newActivity) {
1512 boolean forceReset = (newActivity.info.flags
1513 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001514 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1515 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001516 if ((newActivity.info.flags
1517 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1518 forceReset = true;
1519 }
1520 }
1521
1522 final TaskRecord task = taskTop.task;
1523
1524 // We are going to move through the history list so that we can look
1525 // at each activity 'target' with 'below' either the interesting
1526 // activity immediately below it in the stack or null.
1527 ActivityRecord target = null;
1528 int targetI = 0;
1529 int taskTopI = -1;
1530 int replyChainEnd = -1;
1531 int lastReparentPos = -1;
1532 for (int i=mHistory.size()-1; i>=-1; i--) {
1533 ActivityRecord below = i >= 0 ? (ActivityRecord)mHistory.get(i) : null;
1534
1535 if (below != null && below.finishing) {
1536 continue;
1537 }
1538 if (target == null) {
1539 target = below;
1540 targetI = i;
1541 // If we were in the middle of a reply chain before this
1542 // task, it doesn't appear like the root of the chain wants
1543 // anything interesting, so drop it.
1544 replyChainEnd = -1;
1545 continue;
1546 }
1547
1548 final int flags = target.info.flags;
1549
1550 final boolean finishOnTaskLaunch =
1551 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1552 final boolean allowTaskReparenting =
1553 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1554
1555 if (target.task == task) {
1556 // We are inside of the task being reset... we'll either
1557 // finish this activity, push it out for another task,
1558 // or leave it as-is. We only do this
1559 // for activities that are not the root of the task (since
1560 // if we finish the root, we may no longer have the task!).
1561 if (taskTopI < 0) {
1562 taskTopI = targetI;
1563 }
1564 if (below != null && below.task == task) {
1565 final boolean clearWhenTaskReset =
1566 (target.intent.getFlags()
1567 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1568 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1569 // If this activity is sending a reply to a previous
1570 // activity, we can't do anything with it now until
1571 // we reach the start of the reply chain.
1572 // XXX note that we are assuming the result is always
1573 // to the previous activity, which is almost always
1574 // the case but we really shouldn't count on.
1575 if (replyChainEnd < 0) {
1576 replyChainEnd = targetI;
1577 }
1578 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1579 && target.taskAffinity != null
1580 && !target.taskAffinity.equals(task.affinity)) {
1581 // If this activity has an affinity for another
1582 // task, then we need to move it out of here. We will
1583 // move it as far out of the way as possible, to the
1584 // bottom of the activity stack. This also keeps it
1585 // correctly ordered with any activities we previously
1586 // moved.
1587 ActivityRecord p = (ActivityRecord)mHistory.get(0);
1588 if (target.taskAffinity != null
1589 && target.taskAffinity.equals(p.task.affinity)) {
1590 // If the activity currently at the bottom has the
1591 // same task affinity as the one we are moving,
1592 // then merge it into the same task.
1593 target.task = p.task;
1594 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1595 + " out to bottom task " + p.task);
1596 } else {
1597 mService.mCurTask++;
1598 if (mService.mCurTask <= 0) {
1599 mService.mCurTask = 1;
1600 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001601 target.task = new TaskRecord(mService.mCurTask, target.info, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001602 target.task.affinityIntent = target.intent;
1603 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1604 + " out to new task " + target.task);
1605 }
1606 mService.mWindowManager.setAppGroupId(target, task.taskId);
1607 if (replyChainEnd < 0) {
1608 replyChainEnd = targetI;
1609 }
1610 int dstPos = 0;
1611 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1612 p = (ActivityRecord)mHistory.get(srcPos);
1613 if (p.finishing) {
1614 continue;
1615 }
1616 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1617 + " out to target's task " + target.task);
1618 task.numActivities--;
1619 p.task = target.task;
1620 target.task.numActivities++;
1621 mHistory.remove(srcPos);
1622 mHistory.add(dstPos, p);
1623 mService.mWindowManager.moveAppToken(dstPos, p);
1624 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1625 dstPos++;
1626 if (VALIDATE_TOKENS) {
1627 mService.mWindowManager.validateAppTokens(mHistory);
1628 }
1629 i++;
1630 }
1631 if (taskTop == p) {
1632 taskTop = below;
1633 }
1634 if (taskTopI == replyChainEnd) {
1635 taskTopI = -1;
1636 }
1637 replyChainEnd = -1;
1638 if (mMainStack) {
1639 mService.addRecentTaskLocked(target.task);
1640 }
1641 } else if (forceReset || finishOnTaskLaunch
1642 || clearWhenTaskReset) {
1643 // If the activity should just be removed -- either
1644 // because it asks for it, or the task should be
1645 // cleared -- then finish it and anything that is
1646 // part of its reply chain.
1647 if (clearWhenTaskReset) {
1648 // In this case, we want to finish this activity
1649 // and everything above it, so be sneaky and pretend
1650 // like these are all in the reply chain.
1651 replyChainEnd = targetI+1;
1652 while (replyChainEnd < mHistory.size() &&
1653 ((ActivityRecord)mHistory.get(
1654 replyChainEnd)).task == task) {
1655 replyChainEnd++;
1656 }
1657 replyChainEnd--;
1658 } else if (replyChainEnd < 0) {
1659 replyChainEnd = targetI;
1660 }
1661 ActivityRecord p = null;
1662 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1663 p = (ActivityRecord)mHistory.get(srcPos);
1664 if (p.finishing) {
1665 continue;
1666 }
1667 if (finishActivityLocked(p, srcPos,
1668 Activity.RESULT_CANCELED, null, "reset")) {
1669 replyChainEnd--;
1670 srcPos--;
1671 }
1672 }
1673 if (taskTop == p) {
1674 taskTop = below;
1675 }
1676 if (taskTopI == replyChainEnd) {
1677 taskTopI = -1;
1678 }
1679 replyChainEnd = -1;
1680 } else {
1681 // If we were in the middle of a chain, well the
1682 // activity that started it all doesn't want anything
1683 // special, so leave it all as-is.
1684 replyChainEnd = -1;
1685 }
1686 } else {
1687 // Reached the bottom of the task -- any reply chain
1688 // should be left as-is.
1689 replyChainEnd = -1;
1690 }
1691
1692 } else if (target.resultTo != null) {
1693 // If this activity is sending a reply to a previous
1694 // activity, we can't do anything with it now until
1695 // we reach the start of the reply chain.
1696 // XXX note that we are assuming the result is always
1697 // to the previous activity, which is almost always
1698 // the case but we really shouldn't count on.
1699 if (replyChainEnd < 0) {
1700 replyChainEnd = targetI;
1701 }
1702
1703 } else if (taskTopI >= 0 && allowTaskReparenting
1704 && task.affinity != null
1705 && task.affinity.equals(target.taskAffinity)) {
1706 // We are inside of another task... if this activity has
1707 // an affinity for our task, then either remove it if we are
1708 // clearing or move it over to our task. Note that
1709 // we currently punt on the case where we are resetting a
1710 // task that is not at the top but who has activities above
1711 // with an affinity to it... this is really not a normal
1712 // case, and we will need to later pull that task to the front
1713 // and usually at that point we will do the reset and pick
1714 // up those remaining activities. (This only happens if
1715 // someone starts an activity in a new task from an activity
1716 // in a task that is not currently on top.)
1717 if (forceReset || finishOnTaskLaunch) {
1718 if (replyChainEnd < 0) {
1719 replyChainEnd = targetI;
1720 }
1721 ActivityRecord p = null;
1722 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1723 p = (ActivityRecord)mHistory.get(srcPos);
1724 if (p.finishing) {
1725 continue;
1726 }
1727 if (finishActivityLocked(p, srcPos,
1728 Activity.RESULT_CANCELED, null, "reset")) {
1729 taskTopI--;
1730 lastReparentPos--;
1731 replyChainEnd--;
1732 srcPos--;
1733 }
1734 }
1735 replyChainEnd = -1;
1736 } else {
1737 if (replyChainEnd < 0) {
1738 replyChainEnd = targetI;
1739 }
1740 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
1741 ActivityRecord p = (ActivityRecord)mHistory.get(srcPos);
1742 if (p.finishing) {
1743 continue;
1744 }
1745 if (lastReparentPos < 0) {
1746 lastReparentPos = taskTopI;
1747 taskTop = p;
1748 } else {
1749 lastReparentPos--;
1750 }
1751 mHistory.remove(srcPos);
1752 p.task.numActivities--;
1753 p.task = task;
1754 mHistory.add(lastReparentPos, p);
1755 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1756 + " in to resetting task " + task);
1757 task.numActivities++;
1758 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1759 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1760 if (VALIDATE_TOKENS) {
1761 mService.mWindowManager.validateAppTokens(mHistory);
1762 }
1763 }
1764 replyChainEnd = -1;
1765
1766 // Now we've moved it in to place... but what if this is
1767 // a singleTop activity and we have put it on top of another
1768 // instance of the same activity? Then we drop the instance
1769 // below so it remains singleTop.
1770 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1771 for (int j=lastReparentPos-1; j>=0; j--) {
1772 ActivityRecord p = (ActivityRecord)mHistory.get(j);
1773 if (p.finishing) {
1774 continue;
1775 }
1776 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1777 if (finishActivityLocked(p, j,
1778 Activity.RESULT_CANCELED, null, "replace")) {
1779 taskTopI--;
1780 lastReparentPos--;
1781 }
1782 }
1783 }
1784 }
1785 }
1786 }
1787
1788 target = below;
1789 targetI = i;
1790 }
1791
1792 return taskTop;
1793 }
1794
1795 /**
1796 * Perform clear operation as requested by
1797 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1798 * stack to the given task, then look for
1799 * an instance of that activity in the stack and, if found, finish all
1800 * activities on top of it and return the instance.
1801 *
1802 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001803 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 * or null if none was found.
1805 */
1806 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001807 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001808 int i = mHistory.size();
1809
1810 // First find the requested task.
1811 while (i > 0) {
1812 i--;
1813 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1814 if (r.task.taskId == taskId) {
1815 i++;
1816 break;
1817 }
1818 }
1819
1820 // Now clear it.
1821 while (i > 0) {
1822 i--;
1823 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1824 if (r.finishing) {
1825 continue;
1826 }
1827 if (r.task.taskId != taskId) {
1828 return null;
1829 }
1830 if (r.realActivity.equals(newR.realActivity)) {
1831 // Here it is! Now finish everything in front...
1832 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001833 while (i < (mHistory.size()-1)) {
1834 i++;
1835 r = (ActivityRecord)mHistory.get(i);
1836 if (r.task.taskId != taskId) {
1837 break;
1838 }
1839 if (r.finishing) {
1840 continue;
1841 }
1842 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1843 null, "clear")) {
1844 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001845 }
1846 }
1847
1848 // Finally, if this is a normal launch mode (that is, not
1849 // expecting onNewIntent()), then we will finish the current
1850 // instance of the activity so a new fresh one can be started.
1851 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
1852 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
1853 if (!ret.finishing) {
1854 int index = indexOfTokenLocked(ret);
1855 if (index >= 0) {
1856 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
1857 null, "clear");
1858 }
1859 return null;
1860 }
1861 }
1862
1863 return ret;
1864 }
1865 }
1866
1867 return null;
1868 }
1869
1870 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001871 * Completely remove all activities associated with an existing task.
1872 */
1873 private final void performClearTaskLocked(int taskId) {
1874 int i = mHistory.size();
1875
1876 // First find the requested task.
1877 while (i > 0) {
1878 i--;
1879 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1880 if (r.task.taskId == taskId) {
1881 i++;
1882 break;
1883 }
1884 }
1885
1886 // Now clear it.
1887 while (i > 0) {
1888 i--;
1889 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1890 if (r.finishing) {
1891 continue;
1892 }
1893 if (r.task.taskId != taskId) {
1894 // We hit the bottom. Now finish it all...
1895 while (i < (mHistory.size()-1)) {
1896 i++;
1897 r = (ActivityRecord)mHistory.get(i);
1898 if (r.task.taskId != taskId) {
1899 // Whoops hit the end.
1900 return;
1901 }
1902 if (r.finishing) {
1903 continue;
1904 }
1905 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1906 null, "clear")) {
1907 i--;
1908 }
1909 }
1910 return;
1911 }
1912 }
1913 }
1914
1915 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 * Find the activity in the history stack within the given task. Returns
1917 * the index within the history at which it's found, or < 0 if not found.
1918 */
1919 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
1920 int i = mHistory.size();
1921 while (i > 0) {
1922 i--;
1923 ActivityRecord candidate = (ActivityRecord)mHistory.get(i);
1924 if (candidate.task.taskId != task) {
1925 break;
1926 }
1927 if (candidate.realActivity.equals(r.realActivity)) {
1928 return i;
1929 }
1930 }
1931
1932 return -1;
1933 }
1934
1935 /**
1936 * Reorder the history stack so that the activity at the given index is
1937 * brought to the front.
1938 */
1939 private final ActivityRecord moveActivityToFrontLocked(int where) {
1940 ActivityRecord newTop = (ActivityRecord)mHistory.remove(where);
1941 int top = mHistory.size();
1942 ActivityRecord oldTop = (ActivityRecord)mHistory.get(top-1);
1943 mHistory.add(top, newTop);
1944 oldTop.frontOfTask = false;
1945 newTop.frontOfTask = true;
1946 return newTop;
1947 }
1948
1949 final int startActivityLocked(IApplicationThread caller,
1950 Intent intent, String resolvedType,
1951 Uri[] grantedUriPermissions,
1952 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
1953 String resultWho, int requestCode,
1954 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001955 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07001956
1957 int err = START_SUCCESS;
1958
1959 ProcessRecord callerApp = null;
1960 if (caller != null) {
1961 callerApp = mService.getRecordForAppLocked(caller);
1962 if (callerApp != null) {
1963 callingPid = callerApp.pid;
1964 callingUid = callerApp.info.uid;
1965 } else {
1966 Slog.w(TAG, "Unable to find app for caller " + caller
1967 + " (pid=" + callingPid + ") when starting: "
1968 + intent.toString());
1969 err = START_PERMISSION_DENIED;
1970 }
1971 }
1972
1973 if (err == START_SUCCESS) {
1974 Slog.i(TAG, "Starting: " + intent + " from pid "
1975 + (callerApp != null ? callerApp.pid : callingPid));
1976 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001977
1978 ActivityRecord sourceRecord = null;
1979 ActivityRecord resultRecord = null;
1980 if (resultTo != null) {
1981 int index = indexOfTokenLocked(resultTo);
1982 if (DEBUG_RESULTS) Slog.v(
1983 TAG, "Sending result to " + resultTo + " (index " + index + ")");
1984 if (index >= 0) {
1985 sourceRecord = (ActivityRecord)mHistory.get(index);
1986 if (requestCode >= 0 && !sourceRecord.finishing) {
1987 resultRecord = sourceRecord;
1988 }
1989 }
1990 }
1991
1992 int launchFlags = intent.getFlags();
1993
1994 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
1995 && sourceRecord != null) {
1996 // Transfer the result target from the source activity to the new
1997 // one being started, including any failures.
1998 if (requestCode >= 0) {
1999 return START_FORWARD_AND_REQUEST_CONFLICT;
2000 }
2001 resultRecord = sourceRecord.resultTo;
2002 resultWho = sourceRecord.resultWho;
2003 requestCode = sourceRecord.requestCode;
2004 sourceRecord.resultTo = null;
2005 if (resultRecord != null) {
2006 resultRecord.removeResultsLocked(
2007 sourceRecord, resultWho, requestCode);
2008 }
2009 }
2010
Dianne Hackbornefb58102010-10-14 16:47:34 -07002011 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002012 // We couldn't find a class that can handle the given Intent.
2013 // That's the end of that!
2014 err = START_INTENT_NOT_RESOLVED;
2015 }
2016
2017 if (err == START_SUCCESS && aInfo == null) {
2018 // We couldn't find the specific class specified in the Intent.
2019 // Also the end of the line.
2020 err = START_CLASS_NOT_FOUND;
2021 }
2022
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002023 if (err != START_SUCCESS) {
2024 if (resultRecord != null) {
2025 sendActivityResultLocked(-1,
2026 resultRecord, resultWho, requestCode,
2027 Activity.RESULT_CANCELED, null);
2028 }
2029 return err;
2030 }
2031
2032 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
2033 callingUid, aInfo.exported ? -1 : aInfo.applicationInfo.uid);
2034 if (perm != PackageManager.PERMISSION_GRANTED) {
2035 if (resultRecord != null) {
2036 sendActivityResultLocked(-1,
2037 resultRecord, resultWho, requestCode,
2038 Activity.RESULT_CANCELED, null);
2039 }
2040 String msg = "Permission Denial: starting " + intent.toString()
2041 + " from " + callerApp + " (pid=" + callingPid
2042 + ", uid=" + callingUid + ")"
2043 + " requires " + aInfo.permission;
2044 Slog.w(TAG, msg);
2045 throw new SecurityException(msg);
2046 }
2047
2048 if (mMainStack) {
2049 if (mService.mController != null) {
2050 boolean abort = false;
2051 try {
2052 // The Intent we give to the watcher has the extra data
2053 // stripped off, since it can contain private information.
2054 Intent watchIntent = intent.cloneFilter();
2055 abort = !mService.mController.activityStarting(watchIntent,
2056 aInfo.applicationInfo.packageName);
2057 } catch (RemoteException e) {
2058 mService.mController = null;
2059 }
2060
2061 if (abort) {
2062 if (resultRecord != null) {
2063 sendActivityResultLocked(-1,
2064 resultRecord, resultWho, requestCode,
2065 Activity.RESULT_CANCELED, null);
2066 }
2067 // We pretend to the caller that it was really started, but
2068 // they will just get a cancel result.
2069 return START_SUCCESS;
2070 }
2071 }
2072 }
2073
2074 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2075 intent, resolvedType, aInfo, mService.mConfiguration,
2076 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002077 if (outActivity != null) {
2078 outActivity[0] = r;
2079 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002080
2081 if (mMainStack) {
2082 if (mResumedActivity == null
2083 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2084 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2085 PendingActivityLaunch pal = new PendingActivityLaunch();
2086 pal.r = r;
2087 pal.sourceRecord = sourceRecord;
2088 pal.grantedUriPermissions = grantedUriPermissions;
2089 pal.grantedMode = grantedMode;
2090 pal.onlyIfNeeded = onlyIfNeeded;
2091 mService.mPendingActivityLaunches.add(pal);
2092 return START_SWITCHES_CANCELED;
2093 }
2094 }
2095
2096 if (mService.mDidAppSwitch) {
2097 // This is the second allowed switch since we stopped switches,
2098 // so now just generally allow switches. Use case: user presses
2099 // home (switches disabled, switch to home, mDidAppSwitch now true);
2100 // user taps a home icon (coming from home so allowed, we hit here
2101 // and now allow anyone to switch again).
2102 mService.mAppSwitchesAllowedTime = 0;
2103 } else {
2104 mService.mDidAppSwitch = true;
2105 }
2106
2107 mService.doPendingActivityLaunchesLocked(false);
2108 }
2109
2110 return startActivityUncheckedLocked(r, sourceRecord,
2111 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2112 }
2113
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002114 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2115 if ((launchFlags &
2116 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2117 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2118 // Caller wants to appear on home activity, so before starting
2119 // their own activity we will bring home to the front.
2120 moveHomeToFrontLocked();
2121 }
2122 }
2123
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002124 final int startActivityUncheckedLocked(ActivityRecord r,
2125 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2126 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2127 final Intent intent = r.intent;
2128 final int callingUid = r.launchedFromUid;
2129
2130 int launchFlags = intent.getFlags();
2131
2132 // We'll invoke onUserLeaving before onPause only if the launching
2133 // activity did not explicitly state that this is an automated launch.
2134 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2135 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2136 "startActivity() => mUserLeaving=" + mUserLeaving);
2137
2138 // If the caller has asked not to resume at this point, we make note
2139 // of this in the record so that we can skip it when trying to find
2140 // the top running activity.
2141 if (!doResume) {
2142 r.delayedResume = true;
2143 }
2144
2145 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2146 != 0 ? r : null;
2147
2148 // If the onlyIfNeeded flag is set, then we can do this if the activity
2149 // being launched is the same as the one making the call... or, as
2150 // a special case, if we do not know the caller then we count the
2151 // current top activity as the caller.
2152 if (onlyIfNeeded) {
2153 ActivityRecord checkedCaller = sourceRecord;
2154 if (checkedCaller == null) {
2155 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2156 }
2157 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2158 // Caller is not the same as launcher, so always needed.
2159 onlyIfNeeded = false;
2160 }
2161 }
2162
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002163 if (sourceRecord == null) {
2164 // This activity is not being started from another... in this
2165 // case we -always- start a new task.
2166 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2167 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2168 + intent);
2169 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2170 }
2171 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2172 // The original activity who is starting us is running as a single
2173 // instance... this new activity it is starting must go on its
2174 // own task.
2175 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2176 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2177 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2178 // The activity being started is a single instance... it always
2179 // gets launched into its own task.
2180 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2181 }
2182
2183 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2184 // For whatever reason this activity is being launched into a new
2185 // task... yet the caller has requested a result back. Well, that
2186 // is pretty messed up, so instead immediately send back a cancel
2187 // and let the new task continue launched as normal without a
2188 // dependency on its originator.
2189 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2190 sendActivityResultLocked(-1,
2191 r.resultTo, r.resultWho, r.requestCode,
2192 Activity.RESULT_CANCELED, null);
2193 r.resultTo = null;
2194 }
2195
2196 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002197 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002198 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2199 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2200 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2201 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2202 // If bring to front is requested, and no result is requested, and
2203 // we can find a task that was started with this same
2204 // component, then instead of launching bring that one to the front.
2205 if (r.resultTo == null) {
2206 // See if there is a task to bring to the front. If this is
2207 // a SINGLE_INSTANCE activity, there can be one and only one
2208 // instance of it in the history, and it is always in its own
2209 // unique task, so we do a special search.
2210 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2211 ? findTaskLocked(intent, r.info)
2212 : findActivityLocked(intent, r.info);
2213 if (taskTop != null) {
2214 if (taskTop.task.intent == null) {
2215 // This task was started because of movement of
2216 // the activity based on affinity... now that we
2217 // are actually launching it, we can assign the
2218 // base intent.
2219 taskTop.task.setIntent(intent, r.info);
2220 }
2221 // If the target task is not in the front, then we need
2222 // to bring it to the front... except... well, with
2223 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2224 // to have the same behavior as if a new instance was
2225 // being started, which means not bringing it to the front
2226 // if the caller is not itself in the front.
2227 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002228 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2230 boolean callerAtFront = sourceRecord == null
2231 || curTop.task == sourceRecord.task;
2232 if (callerAtFront) {
2233 // We really do want to push this one into the
2234 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002235 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002236 moveTaskToFrontLocked(taskTop.task, r);
2237 }
2238 }
2239 // If the caller has requested that the target task be
2240 // reset, then do so.
2241 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2242 taskTop = resetTaskIfNeededLocked(taskTop, r);
2243 }
2244 if (onlyIfNeeded) {
2245 // We don't need to start a new activity, and
2246 // the client said not to do anything if that
2247 // is the case, so this is it! And for paranoia, make
2248 // sure we have correctly resumed the top activity.
2249 if (doResume) {
2250 resumeTopActivityLocked(null);
2251 }
2252 return START_RETURN_INTENT_TO_CALLER;
2253 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002254 if ((launchFlags &
2255 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2256 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2257 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002258 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002259 // not be too hard...
2260 reuseTask = taskTop.task;
2261 performClearTaskLocked(taskTop.task.taskId);
2262 reuseTask.setIntent(r.intent, r.info);
2263 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002264 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2265 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2266 // In this situation we want to remove all activities
2267 // from the task up to the one being started. In most
2268 // cases this means we are resetting the task to its
2269 // initial state.
2270 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002271 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002272 if (top != null) {
2273 if (top.frontOfTask) {
2274 // Activity aliases may mean we use different
2275 // intents for the top activity, so make sure
2276 // the task now has the identity of the new
2277 // intent.
2278 top.task.setIntent(r.intent, r.info);
2279 }
2280 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002281 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002282 } else {
2283 // A special case: we need to
2284 // start the activity because it is not currently
2285 // running, and the caller has asked to clear the
2286 // current task to have this activity at the top.
2287 addingToTask = true;
2288 // Now pretend like this activity is being started
2289 // by the top of its task, so it is put in the
2290 // right place.
2291 sourceRecord = taskTop;
2292 }
2293 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2294 // In this case the top activity on the task is the
2295 // same as the one being launched, so we take that
2296 // as a request to bring the task to the foreground.
2297 // If the top activity in the task is the root
2298 // activity, deliver this new intent to it if it
2299 // desires.
2300 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2301 && taskTop.realActivity.equals(r.realActivity)) {
2302 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2303 if (taskTop.frontOfTask) {
2304 taskTop.task.setIntent(r.intent, r.info);
2305 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002306 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002307 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2308 // In this case we are launching the root activity
2309 // of the task, but with a different intent. We
2310 // should start a new instance on top.
2311 addingToTask = true;
2312 sourceRecord = taskTop;
2313 }
2314 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2315 // In this case an activity is being launched in to an
2316 // existing task, without resetting that task. This
2317 // is typically the situation of launching an activity
2318 // from a notification or shortcut. We want to place
2319 // the new activity on top of the current task.
2320 addingToTask = true;
2321 sourceRecord = taskTop;
2322 } else if (!taskTop.task.rootWasReset) {
2323 // In this case we are launching in to an existing task
2324 // that has not yet been started from its front door.
2325 // The current task has been brought to the front.
2326 // Ideally, we'd probably like to place this new task
2327 // at the bottom of its stack, but that's a little hard
2328 // to do with the current organization of the code so
2329 // for now we'll just drop it.
2330 taskTop.task.setIntent(r.intent, r.info);
2331 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002332 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 // We didn't do anything... but it was needed (a.k.a., client
2334 // don't use that intent!) And for paranoia, make
2335 // sure we have correctly resumed the top activity.
2336 if (doResume) {
2337 resumeTopActivityLocked(null);
2338 }
2339 return START_TASK_TO_FRONT;
2340 }
2341 }
2342 }
2343 }
2344
2345 //String uri = r.intent.toURI();
2346 //Intent intent2 = new Intent(uri);
2347 //Slog.i(TAG, "Given intent: " + r.intent);
2348 //Slog.i(TAG, "URI is: " + uri);
2349 //Slog.i(TAG, "To intent: " + intent2);
2350
2351 if (r.packageName != null) {
2352 // If the activity being launched is the same as the one currently
2353 // at the top, then we need to check if it should only be launched
2354 // once.
2355 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2356 if (top != null && r.resultTo == null) {
2357 if (top.realActivity.equals(r.realActivity)) {
2358 if (top.app != null && top.app.thread != null) {
2359 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2360 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2361 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2362 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2363 // For paranoia, make sure we have correctly
2364 // resumed the top activity.
2365 if (doResume) {
2366 resumeTopActivityLocked(null);
2367 }
2368 if (onlyIfNeeded) {
2369 // We don't need to start a new activity, and
2370 // the client said not to do anything if that
2371 // is the case, so this is it!
2372 return START_RETURN_INTENT_TO_CALLER;
2373 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002374 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002375 return START_DELIVERED_TO_TOP;
2376 }
2377 }
2378 }
2379 }
2380
2381 } else {
2382 if (r.resultTo != null) {
2383 sendActivityResultLocked(-1,
2384 r.resultTo, r.resultWho, r.requestCode,
2385 Activity.RESULT_CANCELED, null);
2386 }
2387 return START_CLASS_NOT_FOUND;
2388 }
2389
2390 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002391 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002392
2393 // Should this be considered a new task?
2394 if (r.resultTo == null && !addingToTask
2395 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002396 if (reuseTask == null) {
2397 // todo: should do better management of integers.
2398 mService.mCurTask++;
2399 if (mService.mCurTask <= 0) {
2400 mService.mCurTask = 1;
2401 }
2402 r.task = new TaskRecord(mService.mCurTask, r.info, intent);
2403 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2404 + " in new task " + r.task);
2405 } else {
2406 r.task = reuseTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002407 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002408 newTask = true;
2409 if (mMainStack) {
2410 mService.addRecentTaskLocked(r.task);
2411 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002412 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002413
2414 } else if (sourceRecord != null) {
2415 if (!addingToTask &&
2416 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2417 // In this case, we are adding the activity to an existing
2418 // task, but the caller has asked to clear that task if the
2419 // activity is already running.
2420 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002421 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002422 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002423 if (top != null) {
2424 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002425 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 // For paranoia, make sure we have correctly
2427 // resumed the top activity.
2428 if (doResume) {
2429 resumeTopActivityLocked(null);
2430 }
2431 return START_DELIVERED_TO_TOP;
2432 }
2433 } else if (!addingToTask &&
2434 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2435 // In this case, we are launching an activity in our own task
2436 // that may already be running somewhere in the history, and
2437 // we want to shuffle it to the front of the stack if so.
2438 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2439 if (where >= 0) {
2440 ActivityRecord top = moveActivityToFrontLocked(where);
2441 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002442 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002443 if (doResume) {
2444 resumeTopActivityLocked(null);
2445 }
2446 return START_DELIVERED_TO_TOP;
2447 }
2448 }
2449 // An existing activity is starting this new activity, so we want
2450 // to keep the new one in the same task as the one that is starting
2451 // it.
2452 r.task = sourceRecord.task;
2453 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2454 + " in existing task " + r.task);
2455
2456 } else {
2457 // This not being started from an existing activity, and not part
2458 // of a new task... just put it in the top task, though these days
2459 // this case should never happen.
2460 final int N = mHistory.size();
2461 ActivityRecord prev =
2462 N > 0 ? (ActivityRecord)mHistory.get(N-1) : null;
2463 r.task = prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002464 ? prev.task
2465 : new TaskRecord(mService.mCurTask, r.info, intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002466 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2467 + " in new guessed " + r.task);
2468 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002469
2470 if (grantedUriPermissions != null && callingUid > 0) {
2471 for (int i=0; i<grantedUriPermissions.length; i++) {
2472 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002473 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002474 }
2475 }
2476
2477 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002478 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002479
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002480 if (newTask) {
2481 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2482 }
2483 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002484 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 return START_SUCCESS;
2486 }
2487
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002488 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002489 // Collect information about the target of the Intent.
2490 ActivityInfo aInfo;
2491 try {
2492 ResolveInfo rInfo =
2493 AppGlobals.getPackageManager().resolveIntent(
2494 intent, resolvedType,
2495 PackageManager.MATCH_DEFAULT_ONLY
2496 | ActivityManagerService.STOCK_PM_FLAGS);
2497 aInfo = rInfo != null ? rInfo.activityInfo : null;
2498 } catch (RemoteException e) {
2499 aInfo = null;
2500 }
2501
2502 if (aInfo != null) {
2503 // Store the found target back into the intent, because now that
2504 // we have it we never want to do this again. For example, if the
2505 // user navigates back to this point in the history, we should
2506 // always restart the exact same activity.
2507 intent.setComponent(new ComponentName(
2508 aInfo.applicationInfo.packageName, aInfo.name));
2509
2510 // Don't debug things in the system process
2511 if (debug) {
2512 if (!aInfo.processName.equals("system")) {
2513 mService.setDebugApp(aInfo.processName, true, false);
2514 }
2515 }
2516 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002517 return aInfo;
2518 }
2519
2520 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2521 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2522 int grantedMode, IBinder resultTo,
2523 String resultWho, int requestCode, boolean onlyIfNeeded,
2524 boolean debug, WaitResult outResult, Configuration config) {
2525 // Refuse possible leaked file descriptors
2526 if (intent != null && intent.hasFileDescriptors()) {
2527 throw new IllegalArgumentException("File descriptors passed in Intent");
2528 }
2529
2530 boolean componentSpecified = intent.getComponent() != null;
2531
2532 // Don't modify the client's object!
2533 intent = new Intent(intent);
2534
2535 // Collect information about the target of the Intent.
2536 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002537
2538 synchronized (mService) {
2539 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002540 if (callingUid >= 0) {
2541 callingPid = -1;
2542 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 callingPid = Binder.getCallingPid();
2544 callingUid = Binder.getCallingUid();
2545 } else {
2546 callingPid = callingUid = -1;
2547 }
2548
2549 mConfigWillChange = config != null
2550 && mService.mConfiguration.diff(config) != 0;
2551 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2552 "Starting activity when config will change = " + mConfigWillChange);
2553
2554 final long origId = Binder.clearCallingIdentity();
2555
2556 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002557 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002558 // This may be a heavy-weight process! Check to see if we already
2559 // have another, different heavy-weight process running.
2560 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2561 if (mService.mHeavyWeightProcess != null &&
2562 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2563 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2564 int realCallingPid = callingPid;
2565 int realCallingUid = callingUid;
2566 if (caller != null) {
2567 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2568 if (callerApp != null) {
2569 realCallingPid = callerApp.pid;
2570 realCallingUid = callerApp.info.uid;
2571 } else {
2572 Slog.w(TAG, "Unable to find app for caller " + caller
2573 + " (pid=" + realCallingPid + ") when starting: "
2574 + intent.toString());
2575 return START_PERMISSION_DENIED;
2576 }
2577 }
2578
2579 IIntentSender target = mService.getIntentSenderLocked(
2580 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002581 realCallingUid, null, null, 0, new Intent[] { intent },
2582 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002583 | PendingIntent.FLAG_ONE_SHOT);
2584
2585 Intent newIntent = new Intent();
2586 if (requestCode >= 0) {
2587 // Caller is requesting a result.
2588 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2589 }
2590 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2591 new IntentSender(target));
2592 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2593 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2594 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2595 hist.packageName);
2596 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2597 hist.task.taskId);
2598 }
2599 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2600 aInfo.packageName);
2601 newIntent.setFlags(intent.getFlags());
2602 newIntent.setClassName("android",
2603 HeavyWeightSwitcherActivity.class.getName());
2604 intent = newIntent;
2605 resolvedType = null;
2606 caller = null;
2607 callingUid = Binder.getCallingUid();
2608 callingPid = Binder.getCallingPid();
2609 componentSpecified = true;
2610 try {
2611 ResolveInfo rInfo =
2612 AppGlobals.getPackageManager().resolveIntent(
2613 intent, null,
2614 PackageManager.MATCH_DEFAULT_ONLY
2615 | ActivityManagerService.STOCK_PM_FLAGS);
2616 aInfo = rInfo != null ? rInfo.activityInfo : null;
2617 } catch (RemoteException e) {
2618 aInfo = null;
2619 }
2620 }
2621 }
2622 }
2623
2624 int res = startActivityLocked(caller, intent, resolvedType,
2625 grantedUriPermissions, grantedMode, aInfo,
2626 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002627 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628
2629 if (mConfigWillChange && mMainStack) {
2630 // If the caller also wants to switch to a new configuration,
2631 // do so now. This allows a clean switch, as we are waiting
2632 // for the current activity to pause (so we will not destroy
2633 // it), and have not yet started the next activity.
2634 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2635 "updateConfiguration()");
2636 mConfigWillChange = false;
2637 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2638 "Updating to new configuration after starting activity.");
2639 mService.updateConfigurationLocked(config, null);
2640 }
2641
2642 Binder.restoreCallingIdentity(origId);
2643
2644 if (outResult != null) {
2645 outResult.result = res;
2646 if (res == IActivityManager.START_SUCCESS) {
2647 mWaitingActivityLaunched.add(outResult);
2648 do {
2649 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002650 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002651 } catch (InterruptedException e) {
2652 }
2653 } while (!outResult.timeout && outResult.who == null);
2654 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2655 ActivityRecord r = this.topRunningActivityLocked(null);
2656 if (r.nowVisible) {
2657 outResult.timeout = false;
2658 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2659 outResult.totalTime = 0;
2660 outResult.thisTime = 0;
2661 } else {
2662 outResult.thisTime = SystemClock.uptimeMillis();
2663 mWaitingActivityVisible.add(outResult);
2664 do {
2665 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002666 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002667 } catch (InterruptedException e) {
2668 }
2669 } while (!outResult.timeout && outResult.who == null);
2670 }
2671 }
2672 }
2673
2674 return res;
2675 }
2676 }
2677
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002678 final int startActivities(IApplicationThread caller, int callingUid,
2679 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2680 if (intents == null) {
2681 throw new NullPointerException("intents is null");
2682 }
2683 if (resolvedTypes == null) {
2684 throw new NullPointerException("resolvedTypes is null");
2685 }
2686 if (intents.length != resolvedTypes.length) {
2687 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2688 }
2689
2690 ActivityRecord[] outActivity = new ActivityRecord[1];
2691
2692 int callingPid;
2693 if (callingUid >= 0) {
2694 callingPid = -1;
2695 } else if (caller == null) {
2696 callingPid = Binder.getCallingPid();
2697 callingUid = Binder.getCallingUid();
2698 } else {
2699 callingPid = callingUid = -1;
2700 }
2701 final long origId = Binder.clearCallingIdentity();
2702 try {
2703 synchronized (mService) {
2704
2705 for (int i=0; i<intents.length; i++) {
2706 Intent intent = intents[i];
2707 if (intent == null) {
2708 continue;
2709 }
2710
2711 // Refuse possible leaked file descriptors
2712 if (intent != null && intent.hasFileDescriptors()) {
2713 throw new IllegalArgumentException("File descriptors passed in Intent");
2714 }
2715
2716 boolean componentSpecified = intent.getComponent() != null;
2717
2718 // Don't modify the client's object!
2719 intent = new Intent(intent);
2720
2721 // Collect information about the target of the Intent.
2722 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2723
2724 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2725 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2726 throw new IllegalArgumentException(
2727 "FLAG_CANT_SAVE_STATE not supported here");
2728 }
2729
2730 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2731 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2732 false, componentSpecified, outActivity);
2733 if (res < 0) {
2734 return res;
2735 }
2736
2737 resultTo = outActivity[0];
2738 }
2739 }
2740 } finally {
2741 Binder.restoreCallingIdentity(origId);
2742 }
2743
2744 return IActivityManager.START_SUCCESS;
2745 }
2746
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002747 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2748 long thisTime, long totalTime) {
2749 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2750 WaitResult w = mWaitingActivityLaunched.get(i);
2751 w.timeout = timeout;
2752 if (r != null) {
2753 w.who = new ComponentName(r.info.packageName, r.info.name);
2754 }
2755 w.thisTime = thisTime;
2756 w.totalTime = totalTime;
2757 }
2758 mService.notifyAll();
2759 }
2760
2761 void reportActivityVisibleLocked(ActivityRecord r) {
2762 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2763 WaitResult w = mWaitingActivityVisible.get(i);
2764 w.timeout = false;
2765 if (r != null) {
2766 w.who = new ComponentName(r.info.packageName, r.info.name);
2767 }
2768 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2769 w.thisTime = w.totalTime;
2770 }
2771 mService.notifyAll();
2772 }
2773
2774 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2775 String resultWho, int requestCode, int resultCode, Intent data) {
2776
2777 if (callingUid > 0) {
2778 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002779 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002780 }
2781
2782 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2783 + " : who=" + resultWho + " req=" + requestCode
2784 + " res=" + resultCode + " data=" + data);
2785 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2786 try {
2787 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2788 list.add(new ResultInfo(resultWho, requestCode,
2789 resultCode, data));
2790 r.app.thread.scheduleSendResult(r, list);
2791 return;
2792 } catch (Exception e) {
2793 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2794 }
2795 }
2796
2797 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2798 }
2799
2800 private final void stopActivityLocked(ActivityRecord r) {
2801 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2802 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2803 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2804 if (!r.finishing) {
2805 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2806 "no-history");
2807 }
2808 } else if (r.app != null && r.app.thread != null) {
2809 if (mMainStack) {
2810 if (mService.mFocusedActivity == r) {
2811 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2812 }
2813 }
2814 r.resumeKeyDispatchingLocked();
2815 try {
2816 r.stopped = false;
2817 r.state = ActivityState.STOPPING;
2818 if (DEBUG_VISBILITY) Slog.v(
2819 TAG, "Stopping visible=" + r.visible + " for " + r);
2820 if (!r.visible) {
2821 mService.mWindowManager.setAppVisibility(r, false);
2822 }
2823 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
2824 } catch (Exception e) {
2825 // Maybe just ignore exceptions here... if the process
2826 // has crashed, our death notification will clean things
2827 // up.
2828 Slog.w(TAG, "Exception thrown during pause", e);
2829 // Just in case, assume it to be stopped.
2830 r.stopped = true;
2831 r.state = ActivityState.STOPPED;
2832 if (r.configDestroy) {
2833 destroyActivityLocked(r, true);
2834 }
2835 }
2836 }
2837 }
2838
2839 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
2840 boolean remove) {
2841 int N = mStoppingActivities.size();
2842 if (N <= 0) return null;
2843
2844 ArrayList<ActivityRecord> stops = null;
2845
2846 final boolean nowVisible = mResumedActivity != null
2847 && mResumedActivity.nowVisible
2848 && !mResumedActivity.waitingVisible;
2849 for (int i=0; i<N; i++) {
2850 ActivityRecord s = mStoppingActivities.get(i);
2851 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
2852 + nowVisible + " waitingVisible=" + s.waitingVisible
2853 + " finishing=" + s.finishing);
2854 if (s.waitingVisible && nowVisible) {
2855 mWaitingVisibleActivities.remove(s);
2856 s.waitingVisible = false;
2857 if (s.finishing) {
2858 // If this activity is finishing, it is sitting on top of
2859 // everyone else but we now know it is no longer needed...
2860 // so get rid of it. Otherwise, we need to go through the
2861 // normal flow and hide it once we determine that it is
2862 // hidden by the activities in front of it.
2863 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
2864 mService.mWindowManager.setAppVisibility(s, false);
2865 }
2866 }
2867 if (!s.waitingVisible && remove) {
2868 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
2869 if (stops == null) {
2870 stops = new ArrayList<ActivityRecord>();
2871 }
2872 stops.add(s);
2873 mStoppingActivities.remove(i);
2874 N--;
2875 i--;
2876 }
2877 }
2878
2879 return stops;
2880 }
2881
2882 final void activityIdleInternal(IBinder token, boolean fromTimeout,
2883 Configuration config) {
2884 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
2885
2886 ArrayList<ActivityRecord> stops = null;
2887 ArrayList<ActivityRecord> finishes = null;
2888 ArrayList<ActivityRecord> thumbnails = null;
2889 int NS = 0;
2890 int NF = 0;
2891 int NT = 0;
2892 IApplicationThread sendThumbnail = null;
2893 boolean booting = false;
2894 boolean enableScreen = false;
2895
2896 synchronized (mService) {
2897 if (token != null) {
2898 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
2899 }
2900
2901 // Get the activity record.
2902 int index = indexOfTokenLocked(token);
2903 if (index >= 0) {
2904 ActivityRecord r = (ActivityRecord)mHistory.get(index);
2905
2906 if (fromTimeout) {
2907 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
2908 }
2909
2910 // This is a hack to semi-deal with a race condition
2911 // in the client where it can be constructed with a
2912 // newer configuration from when we asked it to launch.
2913 // We'll update with whatever configuration it now says
2914 // it used to launch.
2915 if (config != null) {
2916 r.configuration = config;
2917 }
2918
2919 // No longer need to keep the device awake.
2920 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
2921 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
2922 mLaunchingActivity.release();
2923 }
2924
2925 // We are now idle. If someone is waiting for a thumbnail from
2926 // us, we can now deliver.
2927 r.idle = true;
2928 mService.scheduleAppGcsLocked();
2929 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
2930 sendThumbnail = r.app.thread;
2931 r.thumbnailNeeded = false;
2932 }
2933
2934 // If this activity is fullscreen, set up to hide those under it.
2935
2936 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
2937 ensureActivitiesVisibleLocked(null, 0);
2938
2939 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
2940 if (mMainStack) {
2941 if (!mService.mBooted && !fromTimeout) {
2942 mService.mBooted = true;
2943 enableScreen = true;
2944 }
2945 }
2946
2947 } else if (fromTimeout) {
2948 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
2949 }
2950
2951 // Atomically retrieve all of the other things to do.
2952 stops = processStoppingActivitiesLocked(true);
2953 NS = stops != null ? stops.size() : 0;
2954 if ((NF=mFinishingActivities.size()) > 0) {
2955 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
2956 mFinishingActivities.clear();
2957 }
2958 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
2959 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
2960 mService.mCancelledThumbnails.clear();
2961 }
2962
2963 if (mMainStack) {
2964 booting = mService.mBooting;
2965 mService.mBooting = false;
2966 }
2967 }
2968
2969 int i;
2970
2971 // Send thumbnail if requested.
2972 if (sendThumbnail != null) {
2973 try {
2974 sendThumbnail.requestThumbnail(token);
2975 } catch (Exception e) {
2976 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
2977 mService.sendPendingThumbnail(null, token, null, null, true);
2978 }
2979 }
2980
2981 // Stop any activities that are scheduled to do so but have been
2982 // waiting for the next one to start.
2983 for (i=0; i<NS; i++) {
2984 ActivityRecord r = (ActivityRecord)stops.get(i);
2985 synchronized (mService) {
2986 if (r.finishing) {
2987 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
2988 } else {
2989 stopActivityLocked(r);
2990 }
2991 }
2992 }
2993
2994 // Finish any activities that are scheduled to do so but have been
2995 // waiting for the next one to start.
2996 for (i=0; i<NF; i++) {
2997 ActivityRecord r = (ActivityRecord)finishes.get(i);
2998 synchronized (mService) {
2999 destroyActivityLocked(r, true);
3000 }
3001 }
3002
3003 // Report back to any thumbnail receivers.
3004 for (i=0; i<NT; i++) {
3005 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3006 mService.sendPendingThumbnail(r, null, null, null, true);
3007 }
3008
3009 if (booting) {
3010 mService.finishBooting();
3011 }
3012
3013 mService.trimApplications();
3014 //dump();
3015 //mWindowManager.dump();
3016
3017 if (enableScreen) {
3018 mService.enableScreenAfterBoot();
3019 }
3020 }
3021
3022 /**
3023 * @return Returns true if the activity is being finished, false if for
3024 * some reason it is being left as-is.
3025 */
3026 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3027 Intent resultData, String reason) {
3028 if (DEBUG_RESULTS) Slog.v(
3029 TAG, "Finishing activity: token=" + token
3030 + ", result=" + resultCode + ", data=" + resultData);
3031
3032 int index = indexOfTokenLocked(token);
3033 if (index < 0) {
3034 return false;
3035 }
3036 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3037
3038 // Is this the last activity left?
3039 boolean lastActivity = true;
3040 for (int i=mHistory.size()-1; i>=0; i--) {
3041 ActivityRecord p = (ActivityRecord)mHistory.get(i);
3042 if (!p.finishing && p != r) {
3043 lastActivity = false;
3044 break;
3045 }
3046 }
3047
3048 // If this is the last activity, but it is the home activity, then
3049 // just don't finish it.
3050 if (lastActivity) {
3051 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3052 return false;
3053 }
3054 }
3055
3056 finishActivityLocked(r, index, resultCode, resultData, reason);
3057 return true;
3058 }
3059
3060 /**
3061 * @return Returns true if this activity has been removed from the history
3062 * list, or false if it is still in the list and will be removed later.
3063 */
3064 final boolean finishActivityLocked(ActivityRecord r, int index,
3065 int resultCode, Intent resultData, String reason) {
3066 if (r.finishing) {
3067 Slog.w(TAG, "Duplicate finish request for " + r);
3068 return false;
3069 }
3070
3071 r.finishing = true;
3072 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3073 System.identityHashCode(r),
3074 r.task.taskId, r.shortComponentName, reason);
3075 r.task.numActivities--;
3076 if (index < (mHistory.size()-1)) {
3077 ActivityRecord next = (ActivityRecord)mHistory.get(index+1);
3078 if (next.task == r.task) {
3079 if (r.frontOfTask) {
3080 // The next activity is now the front of the task.
3081 next.frontOfTask = true;
3082 }
3083 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3084 // If the caller asked that this activity (and all above it)
3085 // be cleared when the task is reset, don't lose that information,
3086 // but propagate it up to the next activity.
3087 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3088 }
3089 }
3090 }
3091
3092 r.pauseKeyDispatchingLocked();
3093 if (mMainStack) {
3094 if (mService.mFocusedActivity == r) {
3095 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3096 }
3097 }
3098
3099 // send the result
3100 ActivityRecord resultTo = r.resultTo;
3101 if (resultTo != null) {
3102 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3103 + " who=" + r.resultWho + " req=" + r.requestCode
3104 + " res=" + resultCode + " data=" + resultData);
3105 if (r.info.applicationInfo.uid > 0) {
3106 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003107 resultTo.packageName, resultData,
3108 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003109 }
3110 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3111 resultData);
3112 r.resultTo = null;
3113 }
3114 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3115
3116 // Make sure this HistoryRecord is not holding on to other resources,
3117 // because clients have remote IPC references to this object so we
3118 // can't assume that will go away and want to avoid circular IPC refs.
3119 r.results = null;
3120 r.pendingResults = null;
3121 r.newIntents = null;
3122 r.icicle = null;
3123
3124 if (mService.mPendingThumbnails.size() > 0) {
3125 // There are clients waiting to receive thumbnails so, in case
3126 // this is an activity that someone is waiting for, add it
3127 // to the pending list so we can correctly update the clients.
3128 mService.mCancelledThumbnails.add(r);
3129 }
3130
3131 if (mResumedActivity == r) {
3132 boolean endTask = index <= 0
3133 || ((ActivityRecord)mHistory.get(index-1)).task != r.task;
3134 if (DEBUG_TRANSITION) Slog.v(TAG,
3135 "Prepare close transition: finishing " + r);
3136 mService.mWindowManager.prepareAppTransition(endTask
3137 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003138 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003139
3140 // Tell window manager to prepare for this one to be removed.
3141 mService.mWindowManager.setAppVisibility(r, false);
3142
3143 if (mPausingActivity == null) {
3144 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3145 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3146 startPausingLocked(false, false);
3147 }
3148
3149 } else if (r.state != ActivityState.PAUSING) {
3150 // If the activity is PAUSING, we will complete the finish once
3151 // it is done pausing; else we can just directly finish it here.
3152 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3153 return finishCurrentActivityLocked(r, index,
3154 FINISH_AFTER_PAUSE) == null;
3155 } else {
3156 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3157 }
3158
3159 return false;
3160 }
3161
3162 private static final int FINISH_IMMEDIATELY = 0;
3163 private static final int FINISH_AFTER_PAUSE = 1;
3164 private static final int FINISH_AFTER_VISIBLE = 2;
3165
3166 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3167 int mode) {
3168 final int index = indexOfTokenLocked(r);
3169 if (index < 0) {
3170 return null;
3171 }
3172
3173 return finishCurrentActivityLocked(r, index, mode);
3174 }
3175
3176 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3177 int index, int mode) {
3178 // First things first: if this activity is currently visible,
3179 // and the resumed activity is not yet visible, then hold off on
3180 // finishing until the resumed one becomes visible.
3181 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3182 if (!mStoppingActivities.contains(r)) {
3183 mStoppingActivities.add(r);
3184 if (mStoppingActivities.size() > 3) {
3185 // If we already have a few activities waiting to stop,
3186 // then give up on things going idle and start clearing
3187 // them out.
3188 Message msg = Message.obtain();
3189 msg.what = IDLE_NOW_MSG;
3190 mHandler.sendMessage(msg);
3191 }
3192 }
3193 r.state = ActivityState.STOPPING;
3194 mService.updateOomAdjLocked();
3195 return r;
3196 }
3197
3198 // make sure the record is cleaned out of other places.
3199 mStoppingActivities.remove(r);
3200 mWaitingVisibleActivities.remove(r);
3201 if (mResumedActivity == r) {
3202 mResumedActivity = null;
3203 }
3204 final ActivityState prevState = r.state;
3205 r.state = ActivityState.FINISHING;
3206
3207 if (mode == FINISH_IMMEDIATELY
3208 || prevState == ActivityState.STOPPED
3209 || prevState == ActivityState.INITIALIZING) {
3210 // If this activity is already stopped, we can just finish
3211 // it right now.
3212 return destroyActivityLocked(r, true) ? null : r;
3213 } else {
3214 // Need to go through the full pause cycle to get this
3215 // activity into the stopped state and then finish it.
3216 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3217 mFinishingActivities.add(r);
3218 resumeTopActivityLocked(null);
3219 }
3220 return r;
3221 }
3222
3223 /**
3224 * Perform the common clean-up of an activity record. This is called both
3225 * as part of destroyActivityLocked() (when destroying the client-side
3226 * representation) and cleaning things up as a result of its hosting
3227 * processing going away, in which case there is no remaining client-side
3228 * state to destroy so only the cleanup here is needed.
3229 */
3230 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices) {
3231 if (mResumedActivity == r) {
3232 mResumedActivity = null;
3233 }
3234 if (mService.mFocusedActivity == r) {
3235 mService.mFocusedActivity = null;
3236 }
3237
3238 r.configDestroy = false;
3239 r.frozenBeforeDestroy = false;
3240
3241 // Make sure this record is no longer in the pending finishes list.
3242 // This could happen, for example, if we are trimming activities
3243 // down to the max limit while they are still waiting to finish.
3244 mFinishingActivities.remove(r);
3245 mWaitingVisibleActivities.remove(r);
3246
3247 // Remove any pending results.
3248 if (r.finishing && r.pendingResults != null) {
3249 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3250 PendingIntentRecord rec = apr.get();
3251 if (rec != null) {
3252 mService.cancelIntentSenderLocked(rec, false);
3253 }
3254 }
3255 r.pendingResults = null;
3256 }
3257
3258 if (cleanServices) {
3259 cleanUpActivityServicesLocked(r);
3260 }
3261
3262 if (mService.mPendingThumbnails.size() > 0) {
3263 // There are clients waiting to receive thumbnails so, in case
3264 // this is an activity that someone is waiting for, add it
3265 // to the pending list so we can correctly update the clients.
3266 mService.mCancelledThumbnails.add(r);
3267 }
3268
3269 // Get rid of any pending idle timeouts.
3270 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3271 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3272 }
3273
3274 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3275 if (r.state != ActivityState.DESTROYED) {
3276 mHistory.remove(r);
3277 r.inHistory = false;
3278 r.state = ActivityState.DESTROYED;
3279 mService.mWindowManager.removeAppToken(r);
3280 if (VALIDATE_TOKENS) {
3281 mService.mWindowManager.validateAppTokens(mHistory);
3282 }
3283 cleanUpActivityServicesLocked(r);
3284 r.removeUriPermissionsLocked();
3285 }
3286 }
3287
3288 /**
3289 * Perform clean-up of service connections in an activity record.
3290 */
3291 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3292 // Throw away any services that have been bound by this activity.
3293 if (r.connections != null) {
3294 Iterator<ConnectionRecord> it = r.connections.iterator();
3295 while (it.hasNext()) {
3296 ConnectionRecord c = it.next();
3297 mService.removeConnectionLocked(c, null, r);
3298 }
3299 r.connections = null;
3300 }
3301 }
3302
3303 /**
3304 * Destroy the current CLIENT SIDE instance of an activity. This may be
3305 * called both when actually finishing an activity, or when performing
3306 * a configuration switch where we destroy the current client-side object
3307 * but then create a new client-side object for this same HistoryRecord.
3308 */
3309 final boolean destroyActivityLocked(ActivityRecord r,
3310 boolean removeFromApp) {
3311 if (DEBUG_SWITCH) Slog.v(
3312 TAG, "Removing activity: token=" + r
3313 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3314 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3315 System.identityHashCode(r),
3316 r.task.taskId, r.shortComponentName);
3317
3318 boolean removedFromHistory = false;
3319
3320 cleanUpActivityLocked(r, false);
3321
3322 final boolean hadApp = r.app != null;
3323
3324 if (hadApp) {
3325 if (removeFromApp) {
3326 int idx = r.app.activities.indexOf(r);
3327 if (idx >= 0) {
3328 r.app.activities.remove(idx);
3329 }
3330 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3331 mService.mHeavyWeightProcess = null;
3332 mService.mHandler.sendEmptyMessage(
3333 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3334 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003335 if (r.app.activities.size() == 0) {
3336 // No longer have activities, so update location in
3337 // LRU list.
3338 mService.updateLruProcessLocked(r.app, true, false);
3339 }
3340 }
3341
3342 boolean skipDestroy = false;
3343
3344 try {
3345 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3346 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3347 r.configChangeFlags);
3348 } catch (Exception e) {
3349 // We can just ignore exceptions here... if the process
3350 // has crashed, our death notification will clean things
3351 // up.
3352 //Slog.w(TAG, "Exception thrown during finish", e);
3353 if (r.finishing) {
3354 removeActivityFromHistoryLocked(r);
3355 removedFromHistory = true;
3356 skipDestroy = true;
3357 }
3358 }
3359
3360 r.app = null;
3361 r.nowVisible = false;
3362
3363 if (r.finishing && !skipDestroy) {
3364 r.state = ActivityState.DESTROYING;
3365 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3366 msg.obj = r;
3367 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3368 } else {
3369 r.state = ActivityState.DESTROYED;
3370 }
3371 } else {
3372 // remove this record from the history.
3373 if (r.finishing) {
3374 removeActivityFromHistoryLocked(r);
3375 removedFromHistory = true;
3376 } else {
3377 r.state = ActivityState.DESTROYED;
3378 }
3379 }
3380
3381 r.configChangeFlags = 0;
3382
3383 if (!mLRUActivities.remove(r) && hadApp) {
3384 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3385 }
3386
3387 return removedFromHistory;
3388 }
3389
3390 final void activityDestroyed(IBinder token) {
3391 synchronized (mService) {
3392 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3393
3394 int index = indexOfTokenLocked(token);
3395 if (index >= 0) {
3396 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3397 if (r.state == ActivityState.DESTROYING) {
3398 final long origId = Binder.clearCallingIdentity();
3399 removeActivityFromHistoryLocked(r);
3400 Binder.restoreCallingIdentity(origId);
3401 }
3402 }
3403 }
3404 }
3405
3406 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3407 int i = list.size();
3408 if (localLOGV) Slog.v(
3409 TAG, "Removing app " + app + " from list " + list
3410 + " with " + i + " entries");
3411 while (i > 0) {
3412 i--;
3413 ActivityRecord r = (ActivityRecord)list.get(i);
3414 if (localLOGV) Slog.v(
3415 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3416 if (r.app == app) {
3417 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3418 list.remove(i);
3419 }
3420 }
3421 }
3422
3423 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3424 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3425 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
3426 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3427 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3428 }
3429
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003430 /**
3431 * Move the current home activity's task (if one exists) to the front
3432 * of the stack.
3433 */
3434 final void moveHomeToFrontLocked() {
3435 TaskRecord homeTask = null;
3436 for (int i=mHistory.size()-1; i>=0; i--) {
3437 ActivityRecord hr = (ActivityRecord)mHistory.get(i);
3438 if (hr.isHomeActivity) {
3439 homeTask = hr.task;
3440 }
3441 }
3442 if (homeTask != null) {
3443 moveTaskToFrontLocked(homeTask, null);
3444 }
3445 }
3446
3447
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003448 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3449 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3450
3451 final int task = tr.taskId;
3452 int top = mHistory.size()-1;
3453
3454 if (top < 0 || ((ActivityRecord)mHistory.get(top)).task.taskId == task) {
3455 // nothing to do!
3456 return;
3457 }
3458
3459 ArrayList moved = new ArrayList();
3460
3461 // Applying the affinities may have removed entries from the history,
3462 // so get the size again.
3463 top = mHistory.size()-1;
3464 int pos = top;
3465
3466 // Shift all activities with this task up to the top
3467 // of the stack, keeping them in the same internal order.
3468 while (pos >= 0) {
3469 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3470 if (localLOGV) Slog.v(
3471 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3472 boolean first = true;
3473 if (r.task.taskId == task) {
3474 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3475 mHistory.remove(pos);
3476 mHistory.add(top, r);
3477 moved.add(0, r);
3478 top--;
3479 if (first && mMainStack) {
3480 mService.addRecentTaskLocked(r.task);
3481 first = false;
3482 }
3483 }
3484 pos--;
3485 }
3486
3487 if (DEBUG_TRANSITION) Slog.v(TAG,
3488 "Prepare to front transition: task=" + tr);
3489 if (reason != null &&
3490 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003491 mService.mWindowManager.prepareAppTransition(
3492 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003493 ActivityRecord r = topRunningActivityLocked(null);
3494 if (r != null) {
3495 mNoAnimActivities.add(r);
3496 }
3497 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003498 mService.mWindowManager.prepareAppTransition(
3499 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003500 }
3501
3502 mService.mWindowManager.moveAppTokensToTop(moved);
3503 if (VALIDATE_TOKENS) {
3504 mService.mWindowManager.validateAppTokens(mHistory);
3505 }
3506
3507 finishTaskMoveLocked(task);
3508 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3509 }
3510
3511 private final void finishTaskMoveLocked(int task) {
3512 resumeTopActivityLocked(null);
3513 }
3514
3515 /**
3516 * Worker method for rearranging history stack. Implements the function of moving all
3517 * activities for a specific task (gathering them if disjoint) into a single group at the
3518 * bottom of the stack.
3519 *
3520 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3521 * to premeptively cancel the move.
3522 *
3523 * @param task The taskId to collect and move to the bottom.
3524 * @return Returns true if the move completed, false if not.
3525 */
3526 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3527 Slog.i(TAG, "moveTaskToBack: " + task);
3528
3529 // If we have a watcher, preflight the move before committing to it. First check
3530 // for *other* available tasks, but if none are available, then try again allowing the
3531 // current task to be selected.
3532 if (mMainStack && mService.mController != null) {
3533 ActivityRecord next = topRunningActivityLocked(null, task);
3534 if (next == null) {
3535 next = topRunningActivityLocked(null, 0);
3536 }
3537 if (next != null) {
3538 // ask watcher if this is allowed
3539 boolean moveOK = true;
3540 try {
3541 moveOK = mService.mController.activityResuming(next.packageName);
3542 } catch (RemoteException e) {
3543 mService.mController = null;
3544 }
3545 if (!moveOK) {
3546 return false;
3547 }
3548 }
3549 }
3550
3551 ArrayList moved = new ArrayList();
3552
3553 if (DEBUG_TRANSITION) Slog.v(TAG,
3554 "Prepare to back transition: task=" + task);
3555
3556 final int N = mHistory.size();
3557 int bottom = 0;
3558 int pos = 0;
3559
3560 // Shift all activities with this task down to the bottom
3561 // of the stack, keeping them in the same internal order.
3562 while (pos < N) {
3563 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3564 if (localLOGV) Slog.v(
3565 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3566 if (r.task.taskId == task) {
3567 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3568 mHistory.remove(pos);
3569 mHistory.add(bottom, r);
3570 moved.add(r);
3571 bottom++;
3572 }
3573 pos++;
3574 }
3575
3576 if (reason != null &&
3577 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003578 mService.mWindowManager.prepareAppTransition(
3579 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003580 ActivityRecord r = topRunningActivityLocked(null);
3581 if (r != null) {
3582 mNoAnimActivities.add(r);
3583 }
3584 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003585 mService.mWindowManager.prepareAppTransition(
3586 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003587 }
3588 mService.mWindowManager.moveAppTokensToBottom(moved);
3589 if (VALIDATE_TOKENS) {
3590 mService.mWindowManager.validateAppTokens(mHistory);
3591 }
3592
3593 finishTaskMoveLocked(task);
3594 return true;
3595 }
3596
3597 private final void logStartActivity(int tag, ActivityRecord r,
3598 TaskRecord task) {
3599 EventLog.writeEvent(tag,
3600 System.identityHashCode(r), task.taskId,
3601 r.shortComponentName, r.intent.getAction(),
3602 r.intent.getType(), r.intent.getDataString(),
3603 r.intent.getFlags());
3604 }
3605
3606 /**
3607 * Make sure the given activity matches the current configuration. Returns
3608 * false if the activity had to be destroyed. Returns true if the
3609 * configuration is the same, or the activity will remain running as-is
3610 * for whatever reason. Ensures the HistoryRecord is updated with the
3611 * correct configuration and all other bookkeeping is handled.
3612 */
3613 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3614 int globalChanges) {
3615 if (mConfigWillChange) {
3616 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3617 "Skipping config check (will change): " + r);
3618 return true;
3619 }
3620
3621 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3622 "Ensuring correct configuration: " + r);
3623
3624 // Short circuit: if the two configurations are the exact same
3625 // object (the common case), then there is nothing to do.
3626 Configuration newConfig = mService.mConfiguration;
3627 if (r.configuration == newConfig) {
3628 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3629 "Configuration unchanged in " + r);
3630 return true;
3631 }
3632
3633 // We don't worry about activities that are finishing.
3634 if (r.finishing) {
3635 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3636 "Configuration doesn't matter in finishing " + r);
3637 r.stopFreezingScreenLocked(false);
3638 return true;
3639 }
3640
3641 // Okay we now are going to make this activity have the new config.
3642 // But then we need to figure out how it needs to deal with that.
3643 Configuration oldConfig = r.configuration;
3644 r.configuration = newConfig;
3645
3646 // If the activity isn't currently running, just leave the new
3647 // configuration and it will pick that up next time it starts.
3648 if (r.app == null || r.app.thread == null) {
3649 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3650 "Configuration doesn't matter not running " + r);
3651 r.stopFreezingScreenLocked(false);
3652 return true;
3653 }
3654
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003655 // Figure out what has changed between the two configurations.
3656 int changes = oldConfig.diff(newConfig);
3657 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3658 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3659 + Integer.toHexString(changes) + ", handles=0x"
3660 + Integer.toHexString(r.info.configChanges)
3661 + ", newConfig=" + newConfig);
3662 }
3663 if ((changes&(~r.info.configChanges)) != 0) {
3664 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3665 r.configChangeFlags |= changes;
3666 r.startFreezingScreenLocked(r.app, globalChanges);
3667 if (r.app == null || r.app.thread == null) {
3668 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3669 "Switch is destroying non-running " + r);
3670 destroyActivityLocked(r, true);
3671 } else if (r.state == ActivityState.PAUSING) {
3672 // A little annoying: we are waiting for this activity to
3673 // finish pausing. Let's not do anything now, but just
3674 // flag that it needs to be restarted when done pausing.
3675 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3676 "Switch is skipping already pausing " + r);
3677 r.configDestroy = true;
3678 return true;
3679 } else if (r.state == ActivityState.RESUMED) {
3680 // Try to optimize this case: the configuration is changing
3681 // and we need to restart the top, resumed activity.
3682 // Instead of doing the normal handshaking, just say
3683 // "restart!".
3684 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3685 "Switch is restarting resumed " + r);
3686 relaunchActivityLocked(r, r.configChangeFlags, true);
3687 r.configChangeFlags = 0;
3688 } else {
3689 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3690 "Switch is restarting non-resumed " + r);
3691 relaunchActivityLocked(r, r.configChangeFlags, false);
3692 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003693 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003694
3695 // All done... tell the caller we weren't able to keep this
3696 // activity around.
3697 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003698 }
3699
3700 // Default case: the activity can handle this new configuration, so
3701 // hand it over. Note that we don't need to give it the new
3702 // configuration, since we always send configuration changes to all
3703 // process when they happen so it can just use whatever configuration
3704 // it last got.
3705 if (r.app != null && r.app.thread != null) {
3706 try {
3707 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3708 r.app.thread.scheduleActivityConfigurationChanged(r);
3709 } catch (RemoteException e) {
3710 // If process died, whatever.
3711 }
3712 }
3713 r.stopFreezingScreenLocked(false);
3714
3715 return true;
3716 }
3717
3718 private final boolean relaunchActivityLocked(ActivityRecord r,
3719 int changes, boolean andResume) {
3720 List<ResultInfo> results = null;
3721 List<Intent> newIntents = null;
3722 if (andResume) {
3723 results = r.results;
3724 newIntents = r.newIntents;
3725 }
3726 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3727 + " with results=" + results + " newIntents=" + newIntents
3728 + " andResume=" + andResume);
3729 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3730 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
3731 r.task.taskId, r.shortComponentName);
3732
3733 r.startFreezingScreenLocked(r.app, 0);
3734
3735 try {
3736 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
3737 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
3738 changes, !andResume, mService.mConfiguration);
3739 // Note: don't need to call pauseIfSleepingLocked() here, because
3740 // the caller will only pass in 'andResume' if this activity is
3741 // currently resumed, which implies we aren't sleeping.
3742 } catch (RemoteException e) {
3743 return false;
3744 }
3745
3746 if (andResume) {
3747 r.results = null;
3748 r.newIntents = null;
3749 if (mMainStack) {
3750 mService.reportResumedActivityLocked(r);
3751 }
3752 }
3753
3754 return true;
3755 }
3756}