blob: 920bbc9c38516d86e292dda134ef70fe478d7917 [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 Hackbornd2835932010-12-13 16:28:46 -0800653 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800654 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) {
Dianne Hackbornd2835932010-12-13 16:28:46 -0800665 //return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800666 }
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 Hackbornd2835932010-12-13 16:28:46 -0800689 prev.thumbnail = screenshotActivities(prev);
690 if (prev.task != null) {
691 prev.task.lastThumbnail = prev.thumbnail;
692 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700693
694 mService.updateCpuStats();
695
696 if (prev.app != null && prev.app.thread != null) {
697 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
698 try {
699 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
700 System.identityHashCode(prev),
701 prev.shortComponentName);
702 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
703 prev.configChangeFlags);
704 if (mMainStack) {
705 mService.updateUsageStats(prev, false);
706 }
707 } catch (Exception e) {
708 // Ignore exception, if process died other code will cleanup.
709 Slog.w(TAG, "Exception thrown during pause", e);
710 mPausingActivity = null;
711 mLastPausedActivity = null;
712 }
713 } else {
714 mPausingActivity = null;
715 mLastPausedActivity = null;
716 }
717
718 // If we are not going to sleep, we want to ensure the device is
719 // awake until the next activity is started.
720 if (!mService.mSleeping && !mService.mShuttingDown) {
721 mLaunchingActivity.acquire();
722 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
723 // To be safe, don't allow the wake lock to be held for too long.
724 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
725 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
726 }
727 }
728
729
730 if (mPausingActivity != null) {
731 // Have the window manager pause its key dispatching until the new
732 // activity has started. If we're pausing the activity just because
733 // the screen is being turned off and the UI is sleeping, don't interrupt
734 // key dispatch; the same activity will pick it up again on wakeup.
735 if (!uiSleeping) {
736 prev.pauseKeyDispatchingLocked();
737 } else {
738 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
739 }
740
741 // Schedule a pause timeout in case the app doesn't respond.
742 // We don't give it much time because this directly impacts the
743 // responsiveness seen by the user.
744 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
745 msg.obj = prev;
746 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
747 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
748 } else {
749 // This activity failed to schedule the
750 // pause, so just treat it as being paused now.
751 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
752 resumeTopActivityLocked(null);
753 }
754 }
755
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800756 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700757 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800758 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700759
760 ActivityRecord r = null;
761
762 synchronized (mService) {
763 int index = indexOfTokenLocked(token);
764 if (index >= 0) {
765 r = (ActivityRecord)mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700766 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
767 if (mPausingActivity == r) {
768 r.state = ActivityState.PAUSED;
769 completePauseLocked();
770 } else {
771 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
772 System.identityHashCode(r), r.shortComponentName,
773 mPausingActivity != null
774 ? mPausingActivity.shortComponentName : "(none)");
775 }
776 }
777 }
778 }
779
780 private final void completePauseLocked() {
781 ActivityRecord prev = mPausingActivity;
782 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
783
784 if (prev != null) {
785 if (prev.finishing) {
786 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
787 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
788 } else if (prev.app != null) {
789 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
790 if (prev.waitingVisible) {
791 prev.waitingVisible = false;
792 mWaitingVisibleActivities.remove(prev);
793 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
794 TAG, "Complete pause, no longer waiting: " + prev);
795 }
796 if (prev.configDestroy) {
797 // The previous is being paused because the configuration
798 // is changing, which means it is actually stopping...
799 // To juggle the fact that we are also starting a new
800 // instance right now, we need to first completely stop
801 // the current instance before starting the new one.
802 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
803 destroyActivityLocked(prev, true);
804 } else {
805 mStoppingActivities.add(prev);
806 if (mStoppingActivities.size() > 3) {
807 // If we already have a few activities waiting to stop,
808 // then give up on things going idle and start clearing
809 // them out.
810 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
811 Message msg = Message.obtain();
812 msg.what = IDLE_NOW_MSG;
813 mHandler.sendMessage(msg);
814 }
815 }
816 } else {
817 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
818 prev = null;
819 }
820 mPausingActivity = null;
821 }
822
823 if (!mService.mSleeping && !mService.mShuttingDown) {
824 resumeTopActivityLocked(prev);
825 } else {
826 if (mGoingToSleep.isHeld()) {
827 mGoingToSleep.release();
828 }
829 if (mService.mShuttingDown) {
830 mService.notifyAll();
831 }
832 }
833
834 if (prev != null) {
835 prev.resumeKeyDispatchingLocked();
836 }
837
838 if (prev.app != null && prev.cpuTimeAtResume > 0
839 && mService.mBatteryStatsService.isOnBattery()) {
840 long diff = 0;
841 synchronized (mService.mProcessStatsThread) {
842 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
843 - prev.cpuTimeAtResume;
844 }
845 if (diff > 0) {
846 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
847 synchronized (bsi) {
848 BatteryStatsImpl.Uid.Proc ps =
849 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
850 prev.info.packageName);
851 if (ps != null) {
852 ps.addForegroundTimeLocked(diff);
853 }
854 }
855 }
856 }
857 prev.cpuTimeAtResume = 0; // reset it
858 }
859
860 /**
861 * Once we know that we have asked an application to put an activity in
862 * the resumed state (either by launching it or explicitly telling it),
863 * this function updates the rest of our state to match that fact.
864 */
865 private final void completeResumeLocked(ActivityRecord next) {
866 next.idle = false;
867 next.results = null;
868 next.newIntents = null;
869
870 // schedule an idle timeout in case the app doesn't do it for us.
871 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
872 msg.obj = next;
873 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
874
875 if (false) {
876 // The activity was never told to pause, so just keep
877 // things going as-is. To maintain our own state,
878 // we need to emulate it coming back and saying it is
879 // idle.
880 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
881 msg.obj = next;
882 mHandler.sendMessage(msg);
883 }
884
885 if (mMainStack) {
886 mService.reportResumedActivityLocked(next);
887 }
888
889 next.thumbnail = null;
890 if (mMainStack) {
891 mService.setFocusedActivityLocked(next);
892 }
893 next.resumeKeyDispatchingLocked();
894 ensureActivitiesVisibleLocked(null, 0);
895 mService.mWindowManager.executeAppTransition();
896 mNoAnimActivities.clear();
897
898 // Mark the point when the activity is resuming
899 // TODO: To be more accurate, the mark should be before the onCreate,
900 // not after the onResume. But for subsequent starts, onResume is fine.
901 if (next.app != null) {
902 synchronized (mService.mProcessStatsThread) {
903 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
904 }
905 } else {
906 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
907 }
908 }
909
910 /**
911 * Make sure that all activities that need to be visible (that is, they
912 * currently can be seen by the user) actually are.
913 */
914 final void ensureActivitiesVisibleLocked(ActivityRecord top,
915 ActivityRecord starting, String onlyThisProcess, int configChanges) {
916 if (DEBUG_VISBILITY) Slog.v(
917 TAG, "ensureActivitiesVisible behind " + top
918 + " configChanges=0x" + Integer.toHexString(configChanges));
919
920 // If the top activity is not fullscreen, then we need to
921 // make sure any activities under it are now visible.
922 final int count = mHistory.size();
923 int i = count-1;
924 while (mHistory.get(i) != top) {
925 i--;
926 }
927 ActivityRecord r;
928 boolean behindFullscreen = false;
929 for (; i>=0; i--) {
930 r = (ActivityRecord)mHistory.get(i);
931 if (DEBUG_VISBILITY) Slog.v(
932 TAG, "Make visible? " + r + " finishing=" + r.finishing
933 + " state=" + r.state);
934 if (r.finishing) {
935 continue;
936 }
937
938 final boolean doThisProcess = onlyThisProcess == null
939 || onlyThisProcess.equals(r.processName);
940
941 // First: if this is not the current activity being started, make
942 // sure it matches the current configuration.
943 if (r != starting && doThisProcess) {
944 ensureActivityConfigurationLocked(r, 0);
945 }
946
947 if (r.app == null || r.app.thread == null) {
948 if (onlyThisProcess == null
949 || onlyThisProcess.equals(r.processName)) {
950 // This activity needs to be visible, but isn't even
951 // running... get it started, but don't resume it
952 // at this point.
953 if (DEBUG_VISBILITY) Slog.v(
954 TAG, "Start and freeze screen for " + r);
955 if (r != starting) {
956 r.startFreezingScreenLocked(r.app, configChanges);
957 }
958 if (!r.visible) {
959 if (DEBUG_VISBILITY) Slog.v(
960 TAG, "Starting and making visible: " + r);
961 mService.mWindowManager.setAppVisibility(r, true);
962 }
963 if (r != starting) {
964 startSpecificActivityLocked(r, false, false);
965 }
966 }
967
968 } else if (r.visible) {
969 // If this activity is already visible, then there is nothing
970 // else to do here.
971 if (DEBUG_VISBILITY) Slog.v(
972 TAG, "Skipping: already visible at " + r);
973 r.stopFreezingScreenLocked(false);
974
975 } else if (onlyThisProcess == null) {
976 // This activity is not currently visible, but is running.
977 // Tell it to become visible.
978 r.visible = true;
979 if (r.state != ActivityState.RESUMED && r != starting) {
980 // If this activity is paused, tell it
981 // to now show its window.
982 if (DEBUG_VISBILITY) Slog.v(
983 TAG, "Making visible and scheduling visibility: " + r);
984 try {
985 mService.mWindowManager.setAppVisibility(r, true);
986 r.app.thread.scheduleWindowVisibility(r, true);
987 r.stopFreezingScreenLocked(false);
988 } catch (Exception e) {
989 // Just skip on any failure; we'll make it
990 // visible when it next restarts.
991 Slog.w(TAG, "Exception thrown making visibile: "
992 + r.intent.getComponent(), e);
993 }
994 }
995 }
996
997 // Aggregate current change flags.
998 configChanges |= r.configChangeFlags;
999
1000 if (r.fullscreen) {
1001 // At this point, nothing else needs to be shown
1002 if (DEBUG_VISBILITY) Slog.v(
1003 TAG, "Stopping: fullscreen at " + r);
1004 behindFullscreen = true;
1005 i--;
1006 break;
1007 }
1008 }
1009
1010 // Now for any activities that aren't visible to the user, make
1011 // sure they no longer are keeping the screen frozen.
1012 while (i >= 0) {
1013 r = (ActivityRecord)mHistory.get(i);
1014 if (DEBUG_VISBILITY) Slog.v(
1015 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1016 + " state=" + r.state
1017 + " behindFullscreen=" + behindFullscreen);
1018 if (!r.finishing) {
1019 if (behindFullscreen) {
1020 if (r.visible) {
1021 if (DEBUG_VISBILITY) Slog.v(
1022 TAG, "Making invisible: " + r);
1023 r.visible = false;
1024 try {
1025 mService.mWindowManager.setAppVisibility(r, false);
1026 if ((r.state == ActivityState.STOPPING
1027 || r.state == ActivityState.STOPPED)
1028 && r.app != null && r.app.thread != null) {
1029 if (DEBUG_VISBILITY) Slog.v(
1030 TAG, "Scheduling invisibility: " + r);
1031 r.app.thread.scheduleWindowVisibility(r, false);
1032 }
1033 } catch (Exception e) {
1034 // Just skip on any failure; we'll make it
1035 // visible when it next restarts.
1036 Slog.w(TAG, "Exception thrown making hidden: "
1037 + r.intent.getComponent(), e);
1038 }
1039 } else {
1040 if (DEBUG_VISBILITY) Slog.v(
1041 TAG, "Already invisible: " + r);
1042 }
1043 } else if (r.fullscreen) {
1044 if (DEBUG_VISBILITY) Slog.v(
1045 TAG, "Now behindFullscreen: " + r);
1046 behindFullscreen = true;
1047 }
1048 }
1049 i--;
1050 }
1051 }
1052
1053 /**
1054 * Version of ensureActivitiesVisible that can easily be called anywhere.
1055 */
1056 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1057 int configChanges) {
1058 ActivityRecord r = topRunningActivityLocked(null);
1059 if (r != null) {
1060 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1061 }
1062 }
1063
1064 /**
1065 * Ensure that the top activity in the stack is resumed.
1066 *
1067 * @param prev The previously resumed activity, for when in the process
1068 * of pausing; can be null to call from elsewhere.
1069 *
1070 * @return Returns true if something is being resumed, or false if
1071 * nothing happened.
1072 */
1073 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1074 // Find the first activity that is not finishing.
1075 ActivityRecord next = topRunningActivityLocked(null);
1076
1077 // Remember how we'll process this pause/resume situation, and ensure
1078 // that the state is reset however we wind up proceeding.
1079 final boolean userLeaving = mUserLeaving;
1080 mUserLeaving = false;
1081
1082 if (next == null) {
1083 // There are no more activities! Let's just start up the
1084 // Launcher...
1085 if (mMainStack) {
1086 return mService.startHomeActivityLocked();
1087 }
1088 }
1089
1090 next.delayedResume = false;
1091
1092 // If the top activity is the resumed one, nothing to do.
1093 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1094 // Make sure we have executed any pending transitions, since there
1095 // should be nothing left to do at this point.
1096 mService.mWindowManager.executeAppTransition();
1097 mNoAnimActivities.clear();
1098 return false;
1099 }
1100
1101 // If we are sleeping, and there is no resumed activity, and the top
1102 // activity is paused, well that is the state we want.
1103 if ((mService.mSleeping || mService.mShuttingDown)
1104 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1105 // Make sure we have executed any pending transitions, since there
1106 // should be nothing left to do at this point.
1107 mService.mWindowManager.executeAppTransition();
1108 mNoAnimActivities.clear();
1109 return false;
1110 }
1111
1112 // The activity may be waiting for stop, but that is no longer
1113 // appropriate for it.
1114 mStoppingActivities.remove(next);
1115 mWaitingVisibleActivities.remove(next);
1116
1117 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1118
1119 // If we are currently pausing an activity, then don't do anything
1120 // until that is done.
1121 if (mPausingActivity != null) {
1122 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1123 return false;
1124 }
1125
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001126 // Okay we are now going to start a switch, to 'next'. We may first
1127 // have to pause the current activity, but this is an important point
1128 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001129 // XXX "App Redirected" dialog is getting too many false positives
1130 // at this point, so turn off for now.
1131 if (false) {
1132 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1133 long now = SystemClock.uptimeMillis();
1134 final boolean inTime = mLastStartedActivity.startTime != 0
1135 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1136 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1137 final int nextUid = next.info.applicationInfo.uid;
1138 if (inTime && lastUid != nextUid
1139 && lastUid != next.launchedFromUid
1140 && mService.checkPermission(
1141 android.Manifest.permission.STOP_APP_SWITCHES,
1142 -1, next.launchedFromUid)
1143 != PackageManager.PERMISSION_GRANTED) {
1144 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1145 } else {
1146 next.startTime = now;
1147 mLastStartedActivity = next;
1148 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001149 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001150 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001151 mLastStartedActivity = next;
1152 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001153 }
1154
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001155 // We need to start pausing the current activity so the top one
1156 // can be resumed...
1157 if (mResumedActivity != null) {
1158 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1159 startPausingLocked(userLeaving, false);
1160 return true;
1161 }
1162
1163 if (prev != null && prev != next) {
1164 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1165 prev.waitingVisible = true;
1166 mWaitingVisibleActivities.add(prev);
1167 if (DEBUG_SWITCH) Slog.v(
1168 TAG, "Resuming top, waiting visible to hide: " + prev);
1169 } else {
1170 // The next activity is already visible, so hide the previous
1171 // activity's windows right now so we can show the new one ASAP.
1172 // We only do this if the previous is finishing, which should mean
1173 // it is on top of the one being resumed so hiding it quickly
1174 // is good. Otherwise, we want to do the normal route of allowing
1175 // the resumed activity to be shown so we can decide if the
1176 // previous should actually be hidden depending on whether the
1177 // new one is found to be full-screen or not.
1178 if (prev.finishing) {
1179 mService.mWindowManager.setAppVisibility(prev, false);
1180 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1181 + prev + ", waitingVisible="
1182 + (prev != null ? prev.waitingVisible : null)
1183 + ", nowVisible=" + next.nowVisible);
1184 } else {
1185 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1186 + prev + ", waitingVisible="
1187 + (prev != null ? prev.waitingVisible : null)
1188 + ", nowVisible=" + next.nowVisible);
1189 }
1190 }
1191 }
1192
1193 // We are starting up the next activity, so tell the window manager
1194 // that the previous one will be hidden soon. This way it can know
1195 // to ignore it when computing the desired screen orientation.
1196 if (prev != null) {
1197 if (prev.finishing) {
1198 if (DEBUG_TRANSITION) Slog.v(TAG,
1199 "Prepare close transition: prev=" + prev);
1200 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001201 mService.mWindowManager.prepareAppTransition(
1202 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001203 } else {
1204 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1205 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001206 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001207 }
1208 mService.mWindowManager.setAppWillBeHidden(prev);
1209 mService.mWindowManager.setAppVisibility(prev, false);
1210 } else {
1211 if (DEBUG_TRANSITION) Slog.v(TAG,
1212 "Prepare open transition: prev=" + prev);
1213 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001214 mService.mWindowManager.prepareAppTransition(
1215 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001216 } else {
1217 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1218 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001219 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001220 }
1221 }
1222 if (false) {
1223 mService.mWindowManager.setAppWillBeHidden(prev);
1224 mService.mWindowManager.setAppVisibility(prev, false);
1225 }
1226 } else if (mHistory.size() > 1) {
1227 if (DEBUG_TRANSITION) Slog.v(TAG,
1228 "Prepare open transition: no previous");
1229 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001230 mService.mWindowManager.prepareAppTransition(
1231 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001232 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001233 mService.mWindowManager.prepareAppTransition(
1234 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001235 }
1236 }
1237
1238 if (next.app != null && next.app.thread != null) {
1239 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1240
1241 // This activity is now becoming visible.
1242 mService.mWindowManager.setAppVisibility(next, true);
1243
1244 ActivityRecord lastResumedActivity = mResumedActivity;
1245 ActivityState lastState = next.state;
1246
1247 mService.updateCpuStats();
1248
1249 next.state = ActivityState.RESUMED;
1250 mResumedActivity = next;
1251 next.task.touchActiveTime();
1252 mService.updateLruProcessLocked(next.app, true, true);
1253 updateLRUListLocked(next);
1254
1255 // Have the window manager re-evaluate the orientation of
1256 // the screen based on the new activity order.
1257 boolean updated = false;
1258 if (mMainStack) {
1259 synchronized (mService) {
1260 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1261 mService.mConfiguration,
1262 next.mayFreezeScreenLocked(next.app) ? next : null);
1263 if (config != null) {
1264 next.frozenBeforeDestroy = true;
1265 }
1266 updated = mService.updateConfigurationLocked(config, next);
1267 }
1268 }
1269 if (!updated) {
1270 // The configuration update wasn't able to keep the existing
1271 // instance of the activity, and instead started a new one.
1272 // We should be all done, but let's just make sure our activity
1273 // is still at the top and schedule another run if something
1274 // weird happened.
1275 ActivityRecord nextNext = topRunningActivityLocked(null);
1276 if (DEBUG_SWITCH) Slog.i(TAG,
1277 "Activity config changed during resume: " + next
1278 + ", new next: " + nextNext);
1279 if (nextNext != next) {
1280 // Do over!
1281 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1282 }
1283 if (mMainStack) {
1284 mService.setFocusedActivityLocked(next);
1285 }
1286 ensureActivitiesVisibleLocked(null, 0);
1287 mService.mWindowManager.executeAppTransition();
1288 mNoAnimActivities.clear();
1289 return true;
1290 }
1291
1292 try {
1293 // Deliver all pending results.
1294 ArrayList a = next.results;
1295 if (a != null) {
1296 final int N = a.size();
1297 if (!next.finishing && N > 0) {
1298 if (DEBUG_RESULTS) Slog.v(
1299 TAG, "Delivering results to " + next
1300 + ": " + a);
1301 next.app.thread.scheduleSendResult(next, a);
1302 }
1303 }
1304
1305 if (next.newIntents != null) {
1306 next.app.thread.scheduleNewIntent(next.newIntents, next);
1307 }
1308
1309 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1310 System.identityHashCode(next),
1311 next.task.taskId, next.shortComponentName);
1312
1313 next.app.thread.scheduleResumeActivity(next,
1314 mService.isNextTransitionForward());
1315
1316 pauseIfSleepingLocked();
1317
1318 } catch (Exception e) {
1319 // Whoops, need to restart this activity!
1320 next.state = lastState;
1321 mResumedActivity = lastResumedActivity;
1322 Slog.i(TAG, "Restarting because process died: " + next);
1323 if (!next.hasBeenLaunched) {
1324 next.hasBeenLaunched = true;
1325 } else {
1326 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1327 mService.mWindowManager.setAppStartingWindow(
1328 next, next.packageName, next.theme,
1329 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001330 next.labelRes, next.icon, next.windowFlags,
1331 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001332 }
1333 }
1334 startSpecificActivityLocked(next, true, false);
1335 return true;
1336 }
1337
1338 // From this point on, if something goes wrong there is no way
1339 // to recover the activity.
1340 try {
1341 next.visible = true;
1342 completeResumeLocked(next);
1343 } catch (Exception e) {
1344 // If any exception gets thrown, toss away this
1345 // activity and try the next one.
1346 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1347 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1348 "resume-exception");
1349 return true;
1350 }
1351
1352 // Didn't need to use the icicle, and it is now out of date.
1353 next.icicle = null;
1354 next.haveState = false;
1355 next.stopped = false;
1356
1357 } else {
1358 // Whoops, need to restart this activity!
1359 if (!next.hasBeenLaunched) {
1360 next.hasBeenLaunched = true;
1361 } else {
1362 if (SHOW_APP_STARTING_PREVIEW) {
1363 mService.mWindowManager.setAppStartingWindow(
1364 next, next.packageName, next.theme,
1365 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001366 next.labelRes, next.icon, next.windowFlags,
1367 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001368 }
1369 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1370 }
1371 startSpecificActivityLocked(next, true, true);
1372 }
1373
1374 return true;
1375 }
1376
1377 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001378 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001379 final int NH = mHistory.size();
1380
1381 int addPos = -1;
1382
1383 if (!newTask) {
1384 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001385 boolean startIt = true;
1386 for (int i = NH-1; i >= 0; i--) {
1387 ActivityRecord p = (ActivityRecord)mHistory.get(i);
1388 if (p.finishing) {
1389 continue;
1390 }
1391 if (p.task == r.task) {
1392 // Here it is! Now, if this is not yet visible to the
1393 // user, then just add it without starting; it will
1394 // get started when the user navigates back to it.
1395 addPos = i+1;
1396 if (!startIt) {
1397 mHistory.add(addPos, r);
1398 r.inHistory = true;
1399 r.task.numActivities++;
1400 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1401 r.info.screenOrientation, r.fullscreen);
1402 if (VALIDATE_TOKENS) {
1403 mService.mWindowManager.validateAppTokens(mHistory);
1404 }
1405 return;
1406 }
1407 break;
1408 }
1409 if (p.fullscreen) {
1410 startIt = false;
1411 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001412 }
1413 }
1414
1415 // Place a new activity at top of stack, so it is next to interact
1416 // with the user.
1417 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001418 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001419 }
1420
1421 // If we are not placing the new activity frontmost, we do not want
1422 // to deliver the onUserLeaving callback to the actual frontmost
1423 // activity
1424 if (addPos < NH) {
1425 mUserLeaving = false;
1426 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1427 }
1428
1429 // Slot the activity into the history stack and proceed
1430 mHistory.add(addPos, r);
1431 r.inHistory = true;
1432 r.frontOfTask = newTask;
1433 r.task.numActivities++;
1434 if (NH > 0) {
1435 // We want to show the starting preview window if we are
1436 // switching to a new task, or the next activity's process is
1437 // not currently running.
1438 boolean showStartingIcon = newTask;
1439 ProcessRecord proc = r.app;
1440 if (proc == null) {
1441 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1442 }
1443 if (proc == null || proc.thread == null) {
1444 showStartingIcon = true;
1445 }
1446 if (DEBUG_TRANSITION) Slog.v(TAG,
1447 "Prepare open transition: starting " + r);
1448 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001449 mService.mWindowManager.prepareAppTransition(
1450 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001451 mNoAnimActivities.add(r);
1452 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1453 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001454 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001455 mNoAnimActivities.remove(r);
1456 } else {
1457 mService.mWindowManager.prepareAppTransition(newTask
1458 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001459 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001460 mNoAnimActivities.remove(r);
1461 }
1462 mService.mWindowManager.addAppToken(
1463 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1464 boolean doShow = true;
1465 if (newTask) {
1466 // Even though this activity is starting fresh, we still need
1467 // to reset it to make sure we apply affinities to move any
1468 // existing activities from other tasks in to it.
1469 // If the caller has requested that the target task be
1470 // reset, then do so.
1471 if ((r.intent.getFlags()
1472 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1473 resetTaskIfNeededLocked(r, r);
1474 doShow = topRunningNonDelayedActivityLocked(null) == r;
1475 }
1476 }
1477 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1478 // Figure out if we are transitioning from another activity that is
1479 // "has the same starting icon" as the next one. This allows the
1480 // window manager to keep the previous window it had previously
1481 // created, if it still had one.
1482 ActivityRecord prev = mResumedActivity;
1483 if (prev != null) {
1484 // We don't want to reuse the previous starting preview if:
1485 // (1) The current activity is in a different task.
1486 if (prev.task != r.task) prev = null;
1487 // (2) The current activity is already displayed.
1488 else if (prev.nowVisible) prev = null;
1489 }
1490 mService.mWindowManager.setAppStartingWindow(
1491 r, r.packageName, r.theme, r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001492 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001493 }
1494 } else {
1495 // If this is the first activity, don't do any fancy animations,
1496 // because there is nothing for it to animate on top of.
1497 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1498 r.info.screenOrientation, r.fullscreen);
1499 }
1500 if (VALIDATE_TOKENS) {
1501 mService.mWindowManager.validateAppTokens(mHistory);
1502 }
1503
1504 if (doResume) {
1505 resumeTopActivityLocked(null);
1506 }
1507 }
1508
1509 /**
1510 * Perform a reset of the given task, if needed as part of launching it.
1511 * Returns the new HistoryRecord at the top of the task.
1512 */
1513 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1514 ActivityRecord newActivity) {
1515 boolean forceReset = (newActivity.info.flags
1516 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001517 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1518 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001519 if ((newActivity.info.flags
1520 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1521 forceReset = true;
1522 }
1523 }
1524
1525 final TaskRecord task = taskTop.task;
1526
1527 // We are going to move through the history list so that we can look
1528 // at each activity 'target' with 'below' either the interesting
1529 // activity immediately below it in the stack or null.
1530 ActivityRecord target = null;
1531 int targetI = 0;
1532 int taskTopI = -1;
1533 int replyChainEnd = -1;
1534 int lastReparentPos = -1;
1535 for (int i=mHistory.size()-1; i>=-1; i--) {
1536 ActivityRecord below = i >= 0 ? (ActivityRecord)mHistory.get(i) : null;
1537
1538 if (below != null && below.finishing) {
1539 continue;
1540 }
1541 if (target == null) {
1542 target = below;
1543 targetI = i;
1544 // If we were in the middle of a reply chain before this
1545 // task, it doesn't appear like the root of the chain wants
1546 // anything interesting, so drop it.
1547 replyChainEnd = -1;
1548 continue;
1549 }
1550
1551 final int flags = target.info.flags;
1552
1553 final boolean finishOnTaskLaunch =
1554 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1555 final boolean allowTaskReparenting =
1556 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1557
1558 if (target.task == task) {
1559 // We are inside of the task being reset... we'll either
1560 // finish this activity, push it out for another task,
1561 // or leave it as-is. We only do this
1562 // for activities that are not the root of the task (since
1563 // if we finish the root, we may no longer have the task!).
1564 if (taskTopI < 0) {
1565 taskTopI = targetI;
1566 }
1567 if (below != null && below.task == task) {
1568 final boolean clearWhenTaskReset =
1569 (target.intent.getFlags()
1570 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1571 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1572 // If this activity is sending a reply to a previous
1573 // activity, we can't do anything with it now until
1574 // we reach the start of the reply chain.
1575 // XXX note that we are assuming the result is always
1576 // to the previous activity, which is almost always
1577 // the case but we really shouldn't count on.
1578 if (replyChainEnd < 0) {
1579 replyChainEnd = targetI;
1580 }
1581 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1582 && target.taskAffinity != null
1583 && !target.taskAffinity.equals(task.affinity)) {
1584 // If this activity has an affinity for another
1585 // task, then we need to move it out of here. We will
1586 // move it as far out of the way as possible, to the
1587 // bottom of the activity stack. This also keeps it
1588 // correctly ordered with any activities we previously
1589 // moved.
1590 ActivityRecord p = (ActivityRecord)mHistory.get(0);
1591 if (target.taskAffinity != null
1592 && target.taskAffinity.equals(p.task.affinity)) {
1593 // If the activity currently at the bottom has the
1594 // same task affinity as the one we are moving,
1595 // then merge it into the same task.
1596 target.task = p.task;
1597 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1598 + " out to bottom task " + p.task);
1599 } else {
1600 mService.mCurTask++;
1601 if (mService.mCurTask <= 0) {
1602 mService.mCurTask = 1;
1603 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001604 target.task = new TaskRecord(mService.mCurTask, target.info, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001605 target.task.affinityIntent = target.intent;
1606 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1607 + " out to new task " + target.task);
1608 }
1609 mService.mWindowManager.setAppGroupId(target, task.taskId);
1610 if (replyChainEnd < 0) {
1611 replyChainEnd = targetI;
1612 }
1613 int dstPos = 0;
1614 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1615 p = (ActivityRecord)mHistory.get(srcPos);
1616 if (p.finishing) {
1617 continue;
1618 }
1619 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1620 + " out to target's task " + target.task);
1621 task.numActivities--;
1622 p.task = target.task;
1623 target.task.numActivities++;
1624 mHistory.remove(srcPos);
1625 mHistory.add(dstPos, p);
1626 mService.mWindowManager.moveAppToken(dstPos, p);
1627 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1628 dstPos++;
1629 if (VALIDATE_TOKENS) {
1630 mService.mWindowManager.validateAppTokens(mHistory);
1631 }
1632 i++;
1633 }
1634 if (taskTop == p) {
1635 taskTop = below;
1636 }
1637 if (taskTopI == replyChainEnd) {
1638 taskTopI = -1;
1639 }
1640 replyChainEnd = -1;
1641 if (mMainStack) {
1642 mService.addRecentTaskLocked(target.task);
1643 }
1644 } else if (forceReset || finishOnTaskLaunch
1645 || clearWhenTaskReset) {
1646 // If the activity should just be removed -- either
1647 // because it asks for it, or the task should be
1648 // cleared -- then finish it and anything that is
1649 // part of its reply chain.
1650 if (clearWhenTaskReset) {
1651 // In this case, we want to finish this activity
1652 // and everything above it, so be sneaky and pretend
1653 // like these are all in the reply chain.
1654 replyChainEnd = targetI+1;
1655 while (replyChainEnd < mHistory.size() &&
1656 ((ActivityRecord)mHistory.get(
1657 replyChainEnd)).task == task) {
1658 replyChainEnd++;
1659 }
1660 replyChainEnd--;
1661 } else if (replyChainEnd < 0) {
1662 replyChainEnd = targetI;
1663 }
1664 ActivityRecord p = null;
1665 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1666 p = (ActivityRecord)mHistory.get(srcPos);
1667 if (p.finishing) {
1668 continue;
1669 }
1670 if (finishActivityLocked(p, srcPos,
1671 Activity.RESULT_CANCELED, null, "reset")) {
1672 replyChainEnd--;
1673 srcPos--;
1674 }
1675 }
1676 if (taskTop == p) {
1677 taskTop = below;
1678 }
1679 if (taskTopI == replyChainEnd) {
1680 taskTopI = -1;
1681 }
1682 replyChainEnd = -1;
1683 } else {
1684 // If we were in the middle of a chain, well the
1685 // activity that started it all doesn't want anything
1686 // special, so leave it all as-is.
1687 replyChainEnd = -1;
1688 }
1689 } else {
1690 // Reached the bottom of the task -- any reply chain
1691 // should be left as-is.
1692 replyChainEnd = -1;
1693 }
1694
1695 } else if (target.resultTo != null) {
1696 // If this activity is sending a reply to a previous
1697 // activity, we can't do anything with it now until
1698 // we reach the start of the reply chain.
1699 // XXX note that we are assuming the result is always
1700 // to the previous activity, which is almost always
1701 // the case but we really shouldn't count on.
1702 if (replyChainEnd < 0) {
1703 replyChainEnd = targetI;
1704 }
1705
1706 } else if (taskTopI >= 0 && allowTaskReparenting
1707 && task.affinity != null
1708 && task.affinity.equals(target.taskAffinity)) {
1709 // We are inside of another task... if this activity has
1710 // an affinity for our task, then either remove it if we are
1711 // clearing or move it over to our task. Note that
1712 // we currently punt on the case where we are resetting a
1713 // task that is not at the top but who has activities above
1714 // with an affinity to it... this is really not a normal
1715 // case, and we will need to later pull that task to the front
1716 // and usually at that point we will do the reset and pick
1717 // up those remaining activities. (This only happens if
1718 // someone starts an activity in a new task from an activity
1719 // in a task that is not currently on top.)
1720 if (forceReset || finishOnTaskLaunch) {
1721 if (replyChainEnd < 0) {
1722 replyChainEnd = targetI;
1723 }
1724 ActivityRecord p = null;
1725 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
1726 p = (ActivityRecord)mHistory.get(srcPos);
1727 if (p.finishing) {
1728 continue;
1729 }
1730 if (finishActivityLocked(p, srcPos,
1731 Activity.RESULT_CANCELED, null, "reset")) {
1732 taskTopI--;
1733 lastReparentPos--;
1734 replyChainEnd--;
1735 srcPos--;
1736 }
1737 }
1738 replyChainEnd = -1;
1739 } else {
1740 if (replyChainEnd < 0) {
1741 replyChainEnd = targetI;
1742 }
1743 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
1744 ActivityRecord p = (ActivityRecord)mHistory.get(srcPos);
1745 if (p.finishing) {
1746 continue;
1747 }
1748 if (lastReparentPos < 0) {
1749 lastReparentPos = taskTopI;
1750 taskTop = p;
1751 } else {
1752 lastReparentPos--;
1753 }
1754 mHistory.remove(srcPos);
1755 p.task.numActivities--;
1756 p.task = task;
1757 mHistory.add(lastReparentPos, p);
1758 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1759 + " in to resetting task " + task);
1760 task.numActivities++;
1761 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1762 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1763 if (VALIDATE_TOKENS) {
1764 mService.mWindowManager.validateAppTokens(mHistory);
1765 }
1766 }
1767 replyChainEnd = -1;
1768
1769 // Now we've moved it in to place... but what if this is
1770 // a singleTop activity and we have put it on top of another
1771 // instance of the same activity? Then we drop the instance
1772 // below so it remains singleTop.
1773 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1774 for (int j=lastReparentPos-1; j>=0; j--) {
1775 ActivityRecord p = (ActivityRecord)mHistory.get(j);
1776 if (p.finishing) {
1777 continue;
1778 }
1779 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1780 if (finishActivityLocked(p, j,
1781 Activity.RESULT_CANCELED, null, "replace")) {
1782 taskTopI--;
1783 lastReparentPos--;
1784 }
1785 }
1786 }
1787 }
1788 }
1789 }
1790
1791 target = below;
1792 targetI = i;
1793 }
1794
1795 return taskTop;
1796 }
1797
1798 /**
1799 * Perform clear operation as requested by
1800 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1801 * stack to the given task, then look for
1802 * an instance of that activity in the stack and, if found, finish all
1803 * activities on top of it and return the instance.
1804 *
1805 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001806 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001807 * or null if none was found.
1808 */
1809 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001810 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811 int i = mHistory.size();
1812
1813 // First find the requested task.
1814 while (i > 0) {
1815 i--;
1816 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1817 if (r.task.taskId == taskId) {
1818 i++;
1819 break;
1820 }
1821 }
1822
1823 // Now clear it.
1824 while (i > 0) {
1825 i--;
1826 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1827 if (r.finishing) {
1828 continue;
1829 }
1830 if (r.task.taskId != taskId) {
1831 return null;
1832 }
1833 if (r.realActivity.equals(newR.realActivity)) {
1834 // Here it is! Now finish everything in front...
1835 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001836 while (i < (mHistory.size()-1)) {
1837 i++;
1838 r = (ActivityRecord)mHistory.get(i);
1839 if (r.task.taskId != taskId) {
1840 break;
1841 }
1842 if (r.finishing) {
1843 continue;
1844 }
1845 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1846 null, "clear")) {
1847 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001848 }
1849 }
1850
1851 // Finally, if this is a normal launch mode (that is, not
1852 // expecting onNewIntent()), then we will finish the current
1853 // instance of the activity so a new fresh one can be started.
1854 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
1855 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
1856 if (!ret.finishing) {
1857 int index = indexOfTokenLocked(ret);
1858 if (index >= 0) {
1859 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
1860 null, "clear");
1861 }
1862 return null;
1863 }
1864 }
1865
1866 return ret;
1867 }
1868 }
1869
1870 return null;
1871 }
1872
1873 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001874 * Completely remove all activities associated with an existing task.
1875 */
1876 private final void performClearTaskLocked(int taskId) {
1877 int i = mHistory.size();
1878
1879 // First find the requested task.
1880 while (i > 0) {
1881 i--;
1882 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1883 if (r.task.taskId == taskId) {
1884 i++;
1885 break;
1886 }
1887 }
1888
1889 // Now clear it.
1890 while (i > 0) {
1891 i--;
1892 ActivityRecord r = (ActivityRecord)mHistory.get(i);
1893 if (r.finishing) {
1894 continue;
1895 }
1896 if (r.task.taskId != taskId) {
1897 // We hit the bottom. Now finish it all...
1898 while (i < (mHistory.size()-1)) {
1899 i++;
1900 r = (ActivityRecord)mHistory.get(i);
1901 if (r.task.taskId != taskId) {
1902 // Whoops hit the end.
1903 return;
1904 }
1905 if (r.finishing) {
1906 continue;
1907 }
1908 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
1909 null, "clear")) {
1910 i--;
1911 }
1912 }
1913 return;
1914 }
1915 }
1916 }
1917
1918 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001919 * Find the activity in the history stack within the given task. Returns
1920 * the index within the history at which it's found, or < 0 if not found.
1921 */
1922 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
1923 int i = mHistory.size();
1924 while (i > 0) {
1925 i--;
1926 ActivityRecord candidate = (ActivityRecord)mHistory.get(i);
1927 if (candidate.task.taskId != task) {
1928 break;
1929 }
1930 if (candidate.realActivity.equals(r.realActivity)) {
1931 return i;
1932 }
1933 }
1934
1935 return -1;
1936 }
1937
1938 /**
1939 * Reorder the history stack so that the activity at the given index is
1940 * brought to the front.
1941 */
1942 private final ActivityRecord moveActivityToFrontLocked(int where) {
1943 ActivityRecord newTop = (ActivityRecord)mHistory.remove(where);
1944 int top = mHistory.size();
1945 ActivityRecord oldTop = (ActivityRecord)mHistory.get(top-1);
1946 mHistory.add(top, newTop);
1947 oldTop.frontOfTask = false;
1948 newTop.frontOfTask = true;
1949 return newTop;
1950 }
1951
1952 final int startActivityLocked(IApplicationThread caller,
1953 Intent intent, String resolvedType,
1954 Uri[] grantedUriPermissions,
1955 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
1956 String resultWho, int requestCode,
1957 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001958 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07001959
1960 int err = START_SUCCESS;
1961
1962 ProcessRecord callerApp = null;
1963 if (caller != null) {
1964 callerApp = mService.getRecordForAppLocked(caller);
1965 if (callerApp != null) {
1966 callingPid = callerApp.pid;
1967 callingUid = callerApp.info.uid;
1968 } else {
1969 Slog.w(TAG, "Unable to find app for caller " + caller
1970 + " (pid=" + callingPid + ") when starting: "
1971 + intent.toString());
1972 err = START_PERMISSION_DENIED;
1973 }
1974 }
1975
1976 if (err == START_SUCCESS) {
1977 Slog.i(TAG, "Starting: " + intent + " from pid "
1978 + (callerApp != null ? callerApp.pid : callingPid));
1979 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001980
1981 ActivityRecord sourceRecord = null;
1982 ActivityRecord resultRecord = null;
1983 if (resultTo != null) {
1984 int index = indexOfTokenLocked(resultTo);
1985 if (DEBUG_RESULTS) Slog.v(
1986 TAG, "Sending result to " + resultTo + " (index " + index + ")");
1987 if (index >= 0) {
1988 sourceRecord = (ActivityRecord)mHistory.get(index);
1989 if (requestCode >= 0 && !sourceRecord.finishing) {
1990 resultRecord = sourceRecord;
1991 }
1992 }
1993 }
1994
1995 int launchFlags = intent.getFlags();
1996
1997 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
1998 && sourceRecord != null) {
1999 // Transfer the result target from the source activity to the new
2000 // one being started, including any failures.
2001 if (requestCode >= 0) {
2002 return START_FORWARD_AND_REQUEST_CONFLICT;
2003 }
2004 resultRecord = sourceRecord.resultTo;
2005 resultWho = sourceRecord.resultWho;
2006 requestCode = sourceRecord.requestCode;
2007 sourceRecord.resultTo = null;
2008 if (resultRecord != null) {
2009 resultRecord.removeResultsLocked(
2010 sourceRecord, resultWho, requestCode);
2011 }
2012 }
2013
Dianne Hackbornefb58102010-10-14 16:47:34 -07002014 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002015 // We couldn't find a class that can handle the given Intent.
2016 // That's the end of that!
2017 err = START_INTENT_NOT_RESOLVED;
2018 }
2019
2020 if (err == START_SUCCESS && aInfo == null) {
2021 // We couldn't find the specific class specified in the Intent.
2022 // Also the end of the line.
2023 err = START_CLASS_NOT_FOUND;
2024 }
2025
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002026 if (err != START_SUCCESS) {
2027 if (resultRecord != null) {
2028 sendActivityResultLocked(-1,
2029 resultRecord, resultWho, requestCode,
2030 Activity.RESULT_CANCELED, null);
2031 }
2032 return err;
2033 }
2034
2035 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
2036 callingUid, aInfo.exported ? -1 : aInfo.applicationInfo.uid);
2037 if (perm != PackageManager.PERMISSION_GRANTED) {
2038 if (resultRecord != null) {
2039 sendActivityResultLocked(-1,
2040 resultRecord, resultWho, requestCode,
2041 Activity.RESULT_CANCELED, null);
2042 }
2043 String msg = "Permission Denial: starting " + intent.toString()
2044 + " from " + callerApp + " (pid=" + callingPid
2045 + ", uid=" + callingUid + ")"
2046 + " requires " + aInfo.permission;
2047 Slog.w(TAG, msg);
2048 throw new SecurityException(msg);
2049 }
2050
2051 if (mMainStack) {
2052 if (mService.mController != null) {
2053 boolean abort = false;
2054 try {
2055 // The Intent we give to the watcher has the extra data
2056 // stripped off, since it can contain private information.
2057 Intent watchIntent = intent.cloneFilter();
2058 abort = !mService.mController.activityStarting(watchIntent,
2059 aInfo.applicationInfo.packageName);
2060 } catch (RemoteException e) {
2061 mService.mController = null;
2062 }
2063
2064 if (abort) {
2065 if (resultRecord != null) {
2066 sendActivityResultLocked(-1,
2067 resultRecord, resultWho, requestCode,
2068 Activity.RESULT_CANCELED, null);
2069 }
2070 // We pretend to the caller that it was really started, but
2071 // they will just get a cancel result.
2072 return START_SUCCESS;
2073 }
2074 }
2075 }
2076
2077 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2078 intent, resolvedType, aInfo, mService.mConfiguration,
2079 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002080 if (outActivity != null) {
2081 outActivity[0] = r;
2082 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083
2084 if (mMainStack) {
2085 if (mResumedActivity == null
2086 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2087 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2088 PendingActivityLaunch pal = new PendingActivityLaunch();
2089 pal.r = r;
2090 pal.sourceRecord = sourceRecord;
2091 pal.grantedUriPermissions = grantedUriPermissions;
2092 pal.grantedMode = grantedMode;
2093 pal.onlyIfNeeded = onlyIfNeeded;
2094 mService.mPendingActivityLaunches.add(pal);
2095 return START_SWITCHES_CANCELED;
2096 }
2097 }
2098
2099 if (mService.mDidAppSwitch) {
2100 // This is the second allowed switch since we stopped switches,
2101 // so now just generally allow switches. Use case: user presses
2102 // home (switches disabled, switch to home, mDidAppSwitch now true);
2103 // user taps a home icon (coming from home so allowed, we hit here
2104 // and now allow anyone to switch again).
2105 mService.mAppSwitchesAllowedTime = 0;
2106 } else {
2107 mService.mDidAppSwitch = true;
2108 }
2109
2110 mService.doPendingActivityLaunchesLocked(false);
2111 }
2112
2113 return startActivityUncheckedLocked(r, sourceRecord,
2114 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2115 }
2116
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002117 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2118 if ((launchFlags &
2119 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2120 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2121 // Caller wants to appear on home activity, so before starting
2122 // their own activity we will bring home to the front.
2123 moveHomeToFrontLocked();
2124 }
2125 }
2126
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002127 final int startActivityUncheckedLocked(ActivityRecord r,
2128 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2129 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2130 final Intent intent = r.intent;
2131 final int callingUid = r.launchedFromUid;
2132
2133 int launchFlags = intent.getFlags();
2134
2135 // We'll invoke onUserLeaving before onPause only if the launching
2136 // activity did not explicitly state that this is an automated launch.
2137 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2138 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2139 "startActivity() => mUserLeaving=" + mUserLeaving);
2140
2141 // If the caller has asked not to resume at this point, we make note
2142 // of this in the record so that we can skip it when trying to find
2143 // the top running activity.
2144 if (!doResume) {
2145 r.delayedResume = true;
2146 }
2147
2148 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2149 != 0 ? r : null;
2150
2151 // If the onlyIfNeeded flag is set, then we can do this if the activity
2152 // being launched is the same as the one making the call... or, as
2153 // a special case, if we do not know the caller then we count the
2154 // current top activity as the caller.
2155 if (onlyIfNeeded) {
2156 ActivityRecord checkedCaller = sourceRecord;
2157 if (checkedCaller == null) {
2158 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2159 }
2160 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2161 // Caller is not the same as launcher, so always needed.
2162 onlyIfNeeded = false;
2163 }
2164 }
2165
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002166 if (sourceRecord == null) {
2167 // This activity is not being started from another... in this
2168 // case we -always- start a new task.
2169 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2170 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2171 + intent);
2172 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2173 }
2174 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2175 // The original activity who is starting us is running as a single
2176 // instance... this new activity it is starting must go on its
2177 // own task.
2178 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2179 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2180 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2181 // The activity being started is a single instance... it always
2182 // gets launched into its own task.
2183 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2184 }
2185
2186 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2187 // For whatever reason this activity is being launched into a new
2188 // task... yet the caller has requested a result back. Well, that
2189 // is pretty messed up, so instead immediately send back a cancel
2190 // and let the new task continue launched as normal without a
2191 // dependency on its originator.
2192 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2193 sendActivityResultLocked(-1,
2194 r.resultTo, r.resultWho, r.requestCode,
2195 Activity.RESULT_CANCELED, null);
2196 r.resultTo = null;
2197 }
2198
2199 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002200 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002201 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2202 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2203 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2204 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2205 // If bring to front is requested, and no result is requested, and
2206 // we can find a task that was started with this same
2207 // component, then instead of launching bring that one to the front.
2208 if (r.resultTo == null) {
2209 // See if there is a task to bring to the front. If this is
2210 // a SINGLE_INSTANCE activity, there can be one and only one
2211 // instance of it in the history, and it is always in its own
2212 // unique task, so we do a special search.
2213 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2214 ? findTaskLocked(intent, r.info)
2215 : findActivityLocked(intent, r.info);
2216 if (taskTop != null) {
2217 if (taskTop.task.intent == null) {
2218 // This task was started because of movement of
2219 // the activity based on affinity... now that we
2220 // are actually launching it, we can assign the
2221 // base intent.
2222 taskTop.task.setIntent(intent, r.info);
2223 }
2224 // If the target task is not in the front, then we need
2225 // to bring it to the front... except... well, with
2226 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2227 // to have the same behavior as if a new instance was
2228 // being started, which means not bringing it to the front
2229 // if the caller is not itself in the front.
2230 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002231 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002232 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2233 boolean callerAtFront = sourceRecord == null
2234 || curTop.task == sourceRecord.task;
2235 if (callerAtFront) {
2236 // We really do want to push this one into the
2237 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002238 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002239 moveTaskToFrontLocked(taskTop.task, r);
2240 }
2241 }
2242 // If the caller has requested that the target task be
2243 // reset, then do so.
2244 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2245 taskTop = resetTaskIfNeededLocked(taskTop, r);
2246 }
2247 if (onlyIfNeeded) {
2248 // We don't need to start a new activity, and
2249 // the client said not to do anything if that
2250 // is the case, so this is it! And for paranoia, make
2251 // sure we have correctly resumed the top activity.
2252 if (doResume) {
2253 resumeTopActivityLocked(null);
2254 }
2255 return START_RETURN_INTENT_TO_CALLER;
2256 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002257 if ((launchFlags &
2258 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2259 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2260 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002261 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262 // not be too hard...
2263 reuseTask = taskTop.task;
2264 performClearTaskLocked(taskTop.task.taskId);
2265 reuseTask.setIntent(r.intent, r.info);
2266 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002267 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2268 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2269 // In this situation we want to remove all activities
2270 // from the task up to the one being started. In most
2271 // cases this means we are resetting the task to its
2272 // initial state.
2273 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002274 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002275 if (top != null) {
2276 if (top.frontOfTask) {
2277 // Activity aliases may mean we use different
2278 // intents for the top activity, so make sure
2279 // the task now has the identity of the new
2280 // intent.
2281 top.task.setIntent(r.intent, r.info);
2282 }
2283 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002284 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002285 } else {
2286 // A special case: we need to
2287 // start the activity because it is not currently
2288 // running, and the caller has asked to clear the
2289 // current task to have this activity at the top.
2290 addingToTask = true;
2291 // Now pretend like this activity is being started
2292 // by the top of its task, so it is put in the
2293 // right place.
2294 sourceRecord = taskTop;
2295 }
2296 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2297 // In this case the top activity on the task is the
2298 // same as the one being launched, so we take that
2299 // as a request to bring the task to the foreground.
2300 // If the top activity in the task is the root
2301 // activity, deliver this new intent to it if it
2302 // desires.
2303 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2304 && taskTop.realActivity.equals(r.realActivity)) {
2305 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2306 if (taskTop.frontOfTask) {
2307 taskTop.task.setIntent(r.intent, r.info);
2308 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002309 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002310 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2311 // In this case we are launching the root activity
2312 // of the task, but with a different intent. We
2313 // should start a new instance on top.
2314 addingToTask = true;
2315 sourceRecord = taskTop;
2316 }
2317 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2318 // In this case an activity is being launched in to an
2319 // existing task, without resetting that task. This
2320 // is typically the situation of launching an activity
2321 // from a notification or shortcut. We want to place
2322 // the new activity on top of the current task.
2323 addingToTask = true;
2324 sourceRecord = taskTop;
2325 } else if (!taskTop.task.rootWasReset) {
2326 // In this case we are launching in to an existing task
2327 // that has not yet been started from its front door.
2328 // The current task has been brought to the front.
2329 // Ideally, we'd probably like to place this new task
2330 // at the bottom of its stack, but that's a little hard
2331 // to do with the current organization of the code so
2332 // for now we'll just drop it.
2333 taskTop.task.setIntent(r.intent, r.info);
2334 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002335 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002336 // We didn't do anything... but it was needed (a.k.a., client
2337 // don't use that intent!) And for paranoia, make
2338 // sure we have correctly resumed the top activity.
2339 if (doResume) {
2340 resumeTopActivityLocked(null);
2341 }
2342 return START_TASK_TO_FRONT;
2343 }
2344 }
2345 }
2346 }
2347
2348 //String uri = r.intent.toURI();
2349 //Intent intent2 = new Intent(uri);
2350 //Slog.i(TAG, "Given intent: " + r.intent);
2351 //Slog.i(TAG, "URI is: " + uri);
2352 //Slog.i(TAG, "To intent: " + intent2);
2353
2354 if (r.packageName != null) {
2355 // If the activity being launched is the same as the one currently
2356 // at the top, then we need to check if it should only be launched
2357 // once.
2358 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2359 if (top != null && r.resultTo == null) {
2360 if (top.realActivity.equals(r.realActivity)) {
2361 if (top.app != null && top.app.thread != null) {
2362 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2363 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2364 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2365 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2366 // For paranoia, make sure we have correctly
2367 // resumed the top activity.
2368 if (doResume) {
2369 resumeTopActivityLocked(null);
2370 }
2371 if (onlyIfNeeded) {
2372 // We don't need to start a new activity, and
2373 // the client said not to do anything if that
2374 // is the case, so this is it!
2375 return START_RETURN_INTENT_TO_CALLER;
2376 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002377 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002378 return START_DELIVERED_TO_TOP;
2379 }
2380 }
2381 }
2382 }
2383
2384 } else {
2385 if (r.resultTo != null) {
2386 sendActivityResultLocked(-1,
2387 r.resultTo, r.resultWho, r.requestCode,
2388 Activity.RESULT_CANCELED, null);
2389 }
2390 return START_CLASS_NOT_FOUND;
2391 }
2392
2393 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002394 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002395
2396 // Should this be considered a new task?
2397 if (r.resultTo == null && !addingToTask
2398 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 if (reuseTask == null) {
2400 // todo: should do better management of integers.
2401 mService.mCurTask++;
2402 if (mService.mCurTask <= 0) {
2403 mService.mCurTask = 1;
2404 }
2405 r.task = new TaskRecord(mService.mCurTask, r.info, intent);
2406 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2407 + " in new task " + r.task);
2408 } else {
2409 r.task = reuseTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002410 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002411 newTask = true;
2412 if (mMainStack) {
2413 mService.addRecentTaskLocked(r.task);
2414 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002415 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002416
2417 } else if (sourceRecord != null) {
2418 if (!addingToTask &&
2419 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2420 // In this case, we are adding the activity to an existing
2421 // task, but the caller has asked to clear that task if the
2422 // activity is already running.
2423 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002424 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002425 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 if (top != null) {
2427 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002428 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 // For paranoia, make sure we have correctly
2430 // resumed the top activity.
2431 if (doResume) {
2432 resumeTopActivityLocked(null);
2433 }
2434 return START_DELIVERED_TO_TOP;
2435 }
2436 } else if (!addingToTask &&
2437 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2438 // In this case, we are launching an activity in our own task
2439 // that may already be running somewhere in the history, and
2440 // we want to shuffle it to the front of the stack if so.
2441 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2442 if (where >= 0) {
2443 ActivityRecord top = moveActivityToFrontLocked(where);
2444 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002445 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002446 if (doResume) {
2447 resumeTopActivityLocked(null);
2448 }
2449 return START_DELIVERED_TO_TOP;
2450 }
2451 }
2452 // An existing activity is starting this new activity, so we want
2453 // to keep the new one in the same task as the one that is starting
2454 // it.
2455 r.task = sourceRecord.task;
2456 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2457 + " in existing task " + r.task);
2458
2459 } else {
2460 // This not being started from an existing activity, and not part
2461 // of a new task... just put it in the top task, though these days
2462 // this case should never happen.
2463 final int N = mHistory.size();
2464 ActivityRecord prev =
2465 N > 0 ? (ActivityRecord)mHistory.get(N-1) : null;
2466 r.task = prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002467 ? prev.task
2468 : new TaskRecord(mService.mCurTask, r.info, intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002469 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2470 + " in new guessed " + r.task);
2471 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002472
2473 if (grantedUriPermissions != null && callingUid > 0) {
2474 for (int i=0; i<grantedUriPermissions.length; i++) {
2475 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002476 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002477 }
2478 }
2479
2480 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002481 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002483 if (newTask) {
2484 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2485 }
2486 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002487 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002488 return START_SUCCESS;
2489 }
2490
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002491 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 // Collect information about the target of the Intent.
2493 ActivityInfo aInfo;
2494 try {
2495 ResolveInfo rInfo =
2496 AppGlobals.getPackageManager().resolveIntent(
2497 intent, resolvedType,
2498 PackageManager.MATCH_DEFAULT_ONLY
2499 | ActivityManagerService.STOCK_PM_FLAGS);
2500 aInfo = rInfo != null ? rInfo.activityInfo : null;
2501 } catch (RemoteException e) {
2502 aInfo = null;
2503 }
2504
2505 if (aInfo != null) {
2506 // Store the found target back into the intent, because now that
2507 // we have it we never want to do this again. For example, if the
2508 // user navigates back to this point in the history, we should
2509 // always restart the exact same activity.
2510 intent.setComponent(new ComponentName(
2511 aInfo.applicationInfo.packageName, aInfo.name));
2512
2513 // Don't debug things in the system process
2514 if (debug) {
2515 if (!aInfo.processName.equals("system")) {
2516 mService.setDebugApp(aInfo.processName, true, false);
2517 }
2518 }
2519 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002520 return aInfo;
2521 }
2522
2523 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2524 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2525 int grantedMode, IBinder resultTo,
2526 String resultWho, int requestCode, boolean onlyIfNeeded,
2527 boolean debug, WaitResult outResult, Configuration config) {
2528 // Refuse possible leaked file descriptors
2529 if (intent != null && intent.hasFileDescriptors()) {
2530 throw new IllegalArgumentException("File descriptors passed in Intent");
2531 }
2532
2533 boolean componentSpecified = intent.getComponent() != null;
2534
2535 // Don't modify the client's object!
2536 intent = new Intent(intent);
2537
2538 // Collect information about the target of the Intent.
2539 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002540
2541 synchronized (mService) {
2542 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002543 if (callingUid >= 0) {
2544 callingPid = -1;
2545 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002546 callingPid = Binder.getCallingPid();
2547 callingUid = Binder.getCallingUid();
2548 } else {
2549 callingPid = callingUid = -1;
2550 }
2551
2552 mConfigWillChange = config != null
2553 && mService.mConfiguration.diff(config) != 0;
2554 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2555 "Starting activity when config will change = " + mConfigWillChange);
2556
2557 final long origId = Binder.clearCallingIdentity();
2558
2559 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002560 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 // This may be a heavy-weight process! Check to see if we already
2562 // have another, different heavy-weight process running.
2563 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2564 if (mService.mHeavyWeightProcess != null &&
2565 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2566 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2567 int realCallingPid = callingPid;
2568 int realCallingUid = callingUid;
2569 if (caller != null) {
2570 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2571 if (callerApp != null) {
2572 realCallingPid = callerApp.pid;
2573 realCallingUid = callerApp.info.uid;
2574 } else {
2575 Slog.w(TAG, "Unable to find app for caller " + caller
2576 + " (pid=" + realCallingPid + ") when starting: "
2577 + intent.toString());
2578 return START_PERMISSION_DENIED;
2579 }
2580 }
2581
2582 IIntentSender target = mService.getIntentSenderLocked(
2583 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002584 realCallingUid, null, null, 0, new Intent[] { intent },
2585 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002586 | PendingIntent.FLAG_ONE_SHOT);
2587
2588 Intent newIntent = new Intent();
2589 if (requestCode >= 0) {
2590 // Caller is requesting a result.
2591 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2592 }
2593 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2594 new IntentSender(target));
2595 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2596 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2597 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2598 hist.packageName);
2599 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2600 hist.task.taskId);
2601 }
2602 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2603 aInfo.packageName);
2604 newIntent.setFlags(intent.getFlags());
2605 newIntent.setClassName("android",
2606 HeavyWeightSwitcherActivity.class.getName());
2607 intent = newIntent;
2608 resolvedType = null;
2609 caller = null;
2610 callingUid = Binder.getCallingUid();
2611 callingPid = Binder.getCallingPid();
2612 componentSpecified = true;
2613 try {
2614 ResolveInfo rInfo =
2615 AppGlobals.getPackageManager().resolveIntent(
2616 intent, null,
2617 PackageManager.MATCH_DEFAULT_ONLY
2618 | ActivityManagerService.STOCK_PM_FLAGS);
2619 aInfo = rInfo != null ? rInfo.activityInfo : null;
2620 } catch (RemoteException e) {
2621 aInfo = null;
2622 }
2623 }
2624 }
2625 }
2626
2627 int res = startActivityLocked(caller, intent, resolvedType,
2628 grantedUriPermissions, grantedMode, aInfo,
2629 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002630 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002631
2632 if (mConfigWillChange && mMainStack) {
2633 // If the caller also wants to switch to a new configuration,
2634 // do so now. This allows a clean switch, as we are waiting
2635 // for the current activity to pause (so we will not destroy
2636 // it), and have not yet started the next activity.
2637 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2638 "updateConfiguration()");
2639 mConfigWillChange = false;
2640 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2641 "Updating to new configuration after starting activity.");
2642 mService.updateConfigurationLocked(config, null);
2643 }
2644
2645 Binder.restoreCallingIdentity(origId);
2646
2647 if (outResult != null) {
2648 outResult.result = res;
2649 if (res == IActivityManager.START_SUCCESS) {
2650 mWaitingActivityLaunched.add(outResult);
2651 do {
2652 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002653 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002654 } catch (InterruptedException e) {
2655 }
2656 } while (!outResult.timeout && outResult.who == null);
2657 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2658 ActivityRecord r = this.topRunningActivityLocked(null);
2659 if (r.nowVisible) {
2660 outResult.timeout = false;
2661 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2662 outResult.totalTime = 0;
2663 outResult.thisTime = 0;
2664 } else {
2665 outResult.thisTime = SystemClock.uptimeMillis();
2666 mWaitingActivityVisible.add(outResult);
2667 do {
2668 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002669 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002670 } catch (InterruptedException e) {
2671 }
2672 } while (!outResult.timeout && outResult.who == null);
2673 }
2674 }
2675 }
2676
2677 return res;
2678 }
2679 }
2680
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002681 final int startActivities(IApplicationThread caller, int callingUid,
2682 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2683 if (intents == null) {
2684 throw new NullPointerException("intents is null");
2685 }
2686 if (resolvedTypes == null) {
2687 throw new NullPointerException("resolvedTypes is null");
2688 }
2689 if (intents.length != resolvedTypes.length) {
2690 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2691 }
2692
2693 ActivityRecord[] outActivity = new ActivityRecord[1];
2694
2695 int callingPid;
2696 if (callingUid >= 0) {
2697 callingPid = -1;
2698 } else if (caller == null) {
2699 callingPid = Binder.getCallingPid();
2700 callingUid = Binder.getCallingUid();
2701 } else {
2702 callingPid = callingUid = -1;
2703 }
2704 final long origId = Binder.clearCallingIdentity();
2705 try {
2706 synchronized (mService) {
2707
2708 for (int i=0; i<intents.length; i++) {
2709 Intent intent = intents[i];
2710 if (intent == null) {
2711 continue;
2712 }
2713
2714 // Refuse possible leaked file descriptors
2715 if (intent != null && intent.hasFileDescriptors()) {
2716 throw new IllegalArgumentException("File descriptors passed in Intent");
2717 }
2718
2719 boolean componentSpecified = intent.getComponent() != null;
2720
2721 // Don't modify the client's object!
2722 intent = new Intent(intent);
2723
2724 // Collect information about the target of the Intent.
2725 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2726
2727 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2728 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2729 throw new IllegalArgumentException(
2730 "FLAG_CANT_SAVE_STATE not supported here");
2731 }
2732
2733 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2734 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2735 false, componentSpecified, outActivity);
2736 if (res < 0) {
2737 return res;
2738 }
2739
2740 resultTo = outActivity[0];
2741 }
2742 }
2743 } finally {
2744 Binder.restoreCallingIdentity(origId);
2745 }
2746
2747 return IActivityManager.START_SUCCESS;
2748 }
2749
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002750 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2751 long thisTime, long totalTime) {
2752 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2753 WaitResult w = mWaitingActivityLaunched.get(i);
2754 w.timeout = timeout;
2755 if (r != null) {
2756 w.who = new ComponentName(r.info.packageName, r.info.name);
2757 }
2758 w.thisTime = thisTime;
2759 w.totalTime = totalTime;
2760 }
2761 mService.notifyAll();
2762 }
2763
2764 void reportActivityVisibleLocked(ActivityRecord r) {
2765 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2766 WaitResult w = mWaitingActivityVisible.get(i);
2767 w.timeout = false;
2768 if (r != null) {
2769 w.who = new ComponentName(r.info.packageName, r.info.name);
2770 }
2771 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2772 w.thisTime = w.totalTime;
2773 }
2774 mService.notifyAll();
2775 }
2776
2777 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2778 String resultWho, int requestCode, int resultCode, Intent data) {
2779
2780 if (callingUid > 0) {
2781 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002782 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 }
2784
2785 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2786 + " : who=" + resultWho + " req=" + requestCode
2787 + " res=" + resultCode + " data=" + data);
2788 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2789 try {
2790 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2791 list.add(new ResultInfo(resultWho, requestCode,
2792 resultCode, data));
2793 r.app.thread.scheduleSendResult(r, list);
2794 return;
2795 } catch (Exception e) {
2796 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2797 }
2798 }
2799
2800 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2801 }
2802
2803 private final void stopActivityLocked(ActivityRecord r) {
2804 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2805 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2806 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2807 if (!r.finishing) {
2808 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2809 "no-history");
2810 }
2811 } else if (r.app != null && r.app.thread != null) {
2812 if (mMainStack) {
2813 if (mService.mFocusedActivity == r) {
2814 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2815 }
2816 }
2817 r.resumeKeyDispatchingLocked();
2818 try {
2819 r.stopped = false;
2820 r.state = ActivityState.STOPPING;
2821 if (DEBUG_VISBILITY) Slog.v(
2822 TAG, "Stopping visible=" + r.visible + " for " + r);
2823 if (!r.visible) {
2824 mService.mWindowManager.setAppVisibility(r, false);
2825 }
2826 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
2827 } catch (Exception e) {
2828 // Maybe just ignore exceptions here... if the process
2829 // has crashed, our death notification will clean things
2830 // up.
2831 Slog.w(TAG, "Exception thrown during pause", e);
2832 // Just in case, assume it to be stopped.
2833 r.stopped = true;
2834 r.state = ActivityState.STOPPED;
2835 if (r.configDestroy) {
2836 destroyActivityLocked(r, true);
2837 }
2838 }
2839 }
2840 }
2841
2842 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
2843 boolean remove) {
2844 int N = mStoppingActivities.size();
2845 if (N <= 0) return null;
2846
2847 ArrayList<ActivityRecord> stops = null;
2848
2849 final boolean nowVisible = mResumedActivity != null
2850 && mResumedActivity.nowVisible
2851 && !mResumedActivity.waitingVisible;
2852 for (int i=0; i<N; i++) {
2853 ActivityRecord s = mStoppingActivities.get(i);
2854 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
2855 + nowVisible + " waitingVisible=" + s.waitingVisible
2856 + " finishing=" + s.finishing);
2857 if (s.waitingVisible && nowVisible) {
2858 mWaitingVisibleActivities.remove(s);
2859 s.waitingVisible = false;
2860 if (s.finishing) {
2861 // If this activity is finishing, it is sitting on top of
2862 // everyone else but we now know it is no longer needed...
2863 // so get rid of it. Otherwise, we need to go through the
2864 // normal flow and hide it once we determine that it is
2865 // hidden by the activities in front of it.
2866 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
2867 mService.mWindowManager.setAppVisibility(s, false);
2868 }
2869 }
2870 if (!s.waitingVisible && remove) {
2871 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
2872 if (stops == null) {
2873 stops = new ArrayList<ActivityRecord>();
2874 }
2875 stops.add(s);
2876 mStoppingActivities.remove(i);
2877 N--;
2878 i--;
2879 }
2880 }
2881
2882 return stops;
2883 }
2884
2885 final void activityIdleInternal(IBinder token, boolean fromTimeout,
2886 Configuration config) {
2887 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
2888
2889 ArrayList<ActivityRecord> stops = null;
2890 ArrayList<ActivityRecord> finishes = null;
2891 ArrayList<ActivityRecord> thumbnails = null;
2892 int NS = 0;
2893 int NF = 0;
2894 int NT = 0;
2895 IApplicationThread sendThumbnail = null;
2896 boolean booting = false;
2897 boolean enableScreen = false;
2898
2899 synchronized (mService) {
2900 if (token != null) {
2901 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
2902 }
2903
2904 // Get the activity record.
2905 int index = indexOfTokenLocked(token);
2906 if (index >= 0) {
2907 ActivityRecord r = (ActivityRecord)mHistory.get(index);
2908
2909 if (fromTimeout) {
2910 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
2911 }
2912
2913 // This is a hack to semi-deal with a race condition
2914 // in the client where it can be constructed with a
2915 // newer configuration from when we asked it to launch.
2916 // We'll update with whatever configuration it now says
2917 // it used to launch.
2918 if (config != null) {
2919 r.configuration = config;
2920 }
2921
2922 // No longer need to keep the device awake.
2923 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
2924 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
2925 mLaunchingActivity.release();
2926 }
2927
2928 // We are now idle. If someone is waiting for a thumbnail from
2929 // us, we can now deliver.
2930 r.idle = true;
2931 mService.scheduleAppGcsLocked();
2932 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
2933 sendThumbnail = r.app.thread;
2934 r.thumbnailNeeded = false;
2935 }
2936
2937 // If this activity is fullscreen, set up to hide those under it.
2938
2939 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
2940 ensureActivitiesVisibleLocked(null, 0);
2941
2942 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
2943 if (mMainStack) {
2944 if (!mService.mBooted && !fromTimeout) {
2945 mService.mBooted = true;
2946 enableScreen = true;
2947 }
2948 }
2949
2950 } else if (fromTimeout) {
2951 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
2952 }
2953
2954 // Atomically retrieve all of the other things to do.
2955 stops = processStoppingActivitiesLocked(true);
2956 NS = stops != null ? stops.size() : 0;
2957 if ((NF=mFinishingActivities.size()) > 0) {
2958 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
2959 mFinishingActivities.clear();
2960 }
2961 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
2962 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
2963 mService.mCancelledThumbnails.clear();
2964 }
2965
2966 if (mMainStack) {
2967 booting = mService.mBooting;
2968 mService.mBooting = false;
2969 }
2970 }
2971
2972 int i;
2973
2974 // Send thumbnail if requested.
2975 if (sendThumbnail != null) {
2976 try {
2977 sendThumbnail.requestThumbnail(token);
2978 } catch (Exception e) {
2979 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
2980 mService.sendPendingThumbnail(null, token, null, null, true);
2981 }
2982 }
2983
2984 // Stop any activities that are scheduled to do so but have been
2985 // waiting for the next one to start.
2986 for (i=0; i<NS; i++) {
2987 ActivityRecord r = (ActivityRecord)stops.get(i);
2988 synchronized (mService) {
2989 if (r.finishing) {
2990 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
2991 } else {
2992 stopActivityLocked(r);
2993 }
2994 }
2995 }
2996
2997 // Finish any activities that are scheduled to do so but have been
2998 // waiting for the next one to start.
2999 for (i=0; i<NF; i++) {
3000 ActivityRecord r = (ActivityRecord)finishes.get(i);
3001 synchronized (mService) {
3002 destroyActivityLocked(r, true);
3003 }
3004 }
3005
3006 // Report back to any thumbnail receivers.
3007 for (i=0; i<NT; i++) {
3008 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3009 mService.sendPendingThumbnail(r, null, null, null, true);
3010 }
3011
3012 if (booting) {
3013 mService.finishBooting();
3014 }
3015
3016 mService.trimApplications();
3017 //dump();
3018 //mWindowManager.dump();
3019
3020 if (enableScreen) {
3021 mService.enableScreenAfterBoot();
3022 }
3023 }
3024
3025 /**
3026 * @return Returns true if the activity is being finished, false if for
3027 * some reason it is being left as-is.
3028 */
3029 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3030 Intent resultData, String reason) {
3031 if (DEBUG_RESULTS) Slog.v(
3032 TAG, "Finishing activity: token=" + token
3033 + ", result=" + resultCode + ", data=" + resultData);
3034
3035 int index = indexOfTokenLocked(token);
3036 if (index < 0) {
3037 return false;
3038 }
3039 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3040
3041 // Is this the last activity left?
3042 boolean lastActivity = true;
3043 for (int i=mHistory.size()-1; i>=0; i--) {
3044 ActivityRecord p = (ActivityRecord)mHistory.get(i);
3045 if (!p.finishing && p != r) {
3046 lastActivity = false;
3047 break;
3048 }
3049 }
3050
3051 // If this is the last activity, but it is the home activity, then
3052 // just don't finish it.
3053 if (lastActivity) {
3054 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3055 return false;
3056 }
3057 }
3058
3059 finishActivityLocked(r, index, resultCode, resultData, reason);
3060 return true;
3061 }
3062
3063 /**
3064 * @return Returns true if this activity has been removed from the history
3065 * list, or false if it is still in the list and will be removed later.
3066 */
3067 final boolean finishActivityLocked(ActivityRecord r, int index,
3068 int resultCode, Intent resultData, String reason) {
3069 if (r.finishing) {
3070 Slog.w(TAG, "Duplicate finish request for " + r);
3071 return false;
3072 }
3073
3074 r.finishing = true;
3075 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3076 System.identityHashCode(r),
3077 r.task.taskId, r.shortComponentName, reason);
3078 r.task.numActivities--;
3079 if (index < (mHistory.size()-1)) {
3080 ActivityRecord next = (ActivityRecord)mHistory.get(index+1);
3081 if (next.task == r.task) {
3082 if (r.frontOfTask) {
3083 // The next activity is now the front of the task.
3084 next.frontOfTask = true;
3085 }
3086 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3087 // If the caller asked that this activity (and all above it)
3088 // be cleared when the task is reset, don't lose that information,
3089 // but propagate it up to the next activity.
3090 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3091 }
3092 }
3093 }
3094
3095 r.pauseKeyDispatchingLocked();
3096 if (mMainStack) {
3097 if (mService.mFocusedActivity == r) {
3098 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3099 }
3100 }
3101
3102 // send the result
3103 ActivityRecord resultTo = r.resultTo;
3104 if (resultTo != null) {
3105 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3106 + " who=" + r.resultWho + " req=" + r.requestCode
3107 + " res=" + resultCode + " data=" + resultData);
3108 if (r.info.applicationInfo.uid > 0) {
3109 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003110 resultTo.packageName, resultData,
3111 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003112 }
3113 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3114 resultData);
3115 r.resultTo = null;
3116 }
3117 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3118
3119 // Make sure this HistoryRecord is not holding on to other resources,
3120 // because clients have remote IPC references to this object so we
3121 // can't assume that will go away and want to avoid circular IPC refs.
3122 r.results = null;
3123 r.pendingResults = null;
3124 r.newIntents = null;
3125 r.icicle = null;
3126
3127 if (mService.mPendingThumbnails.size() > 0) {
3128 // There are clients waiting to receive thumbnails so, in case
3129 // this is an activity that someone is waiting for, add it
3130 // to the pending list so we can correctly update the clients.
3131 mService.mCancelledThumbnails.add(r);
3132 }
3133
3134 if (mResumedActivity == r) {
3135 boolean endTask = index <= 0
3136 || ((ActivityRecord)mHistory.get(index-1)).task != r.task;
3137 if (DEBUG_TRANSITION) Slog.v(TAG,
3138 "Prepare close transition: finishing " + r);
3139 mService.mWindowManager.prepareAppTransition(endTask
3140 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003141 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003142
3143 // Tell window manager to prepare for this one to be removed.
3144 mService.mWindowManager.setAppVisibility(r, false);
3145
3146 if (mPausingActivity == null) {
3147 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3148 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3149 startPausingLocked(false, false);
3150 }
3151
3152 } else if (r.state != ActivityState.PAUSING) {
3153 // If the activity is PAUSING, we will complete the finish once
3154 // it is done pausing; else we can just directly finish it here.
3155 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3156 return finishCurrentActivityLocked(r, index,
3157 FINISH_AFTER_PAUSE) == null;
3158 } else {
3159 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3160 }
3161
3162 return false;
3163 }
3164
3165 private static final int FINISH_IMMEDIATELY = 0;
3166 private static final int FINISH_AFTER_PAUSE = 1;
3167 private static final int FINISH_AFTER_VISIBLE = 2;
3168
3169 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3170 int mode) {
3171 final int index = indexOfTokenLocked(r);
3172 if (index < 0) {
3173 return null;
3174 }
3175
3176 return finishCurrentActivityLocked(r, index, mode);
3177 }
3178
3179 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3180 int index, int mode) {
3181 // First things first: if this activity is currently visible,
3182 // and the resumed activity is not yet visible, then hold off on
3183 // finishing until the resumed one becomes visible.
3184 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3185 if (!mStoppingActivities.contains(r)) {
3186 mStoppingActivities.add(r);
3187 if (mStoppingActivities.size() > 3) {
3188 // If we already have a few activities waiting to stop,
3189 // then give up on things going idle and start clearing
3190 // them out.
3191 Message msg = Message.obtain();
3192 msg.what = IDLE_NOW_MSG;
3193 mHandler.sendMessage(msg);
3194 }
3195 }
3196 r.state = ActivityState.STOPPING;
3197 mService.updateOomAdjLocked();
3198 return r;
3199 }
3200
3201 // make sure the record is cleaned out of other places.
3202 mStoppingActivities.remove(r);
3203 mWaitingVisibleActivities.remove(r);
3204 if (mResumedActivity == r) {
3205 mResumedActivity = null;
3206 }
3207 final ActivityState prevState = r.state;
3208 r.state = ActivityState.FINISHING;
3209
3210 if (mode == FINISH_IMMEDIATELY
3211 || prevState == ActivityState.STOPPED
3212 || prevState == ActivityState.INITIALIZING) {
3213 // If this activity is already stopped, we can just finish
3214 // it right now.
3215 return destroyActivityLocked(r, true) ? null : r;
3216 } else {
3217 // Need to go through the full pause cycle to get this
3218 // activity into the stopped state and then finish it.
3219 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3220 mFinishingActivities.add(r);
3221 resumeTopActivityLocked(null);
3222 }
3223 return r;
3224 }
3225
3226 /**
3227 * Perform the common clean-up of an activity record. This is called both
3228 * as part of destroyActivityLocked() (when destroying the client-side
3229 * representation) and cleaning things up as a result of its hosting
3230 * processing going away, in which case there is no remaining client-side
3231 * state to destroy so only the cleanup here is needed.
3232 */
3233 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices) {
3234 if (mResumedActivity == r) {
3235 mResumedActivity = null;
3236 }
3237 if (mService.mFocusedActivity == r) {
3238 mService.mFocusedActivity = null;
3239 }
3240
3241 r.configDestroy = false;
3242 r.frozenBeforeDestroy = false;
3243
3244 // Make sure this record is no longer in the pending finishes list.
3245 // This could happen, for example, if we are trimming activities
3246 // down to the max limit while they are still waiting to finish.
3247 mFinishingActivities.remove(r);
3248 mWaitingVisibleActivities.remove(r);
3249
3250 // Remove any pending results.
3251 if (r.finishing && r.pendingResults != null) {
3252 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3253 PendingIntentRecord rec = apr.get();
3254 if (rec != null) {
3255 mService.cancelIntentSenderLocked(rec, false);
3256 }
3257 }
3258 r.pendingResults = null;
3259 }
3260
3261 if (cleanServices) {
3262 cleanUpActivityServicesLocked(r);
3263 }
3264
3265 if (mService.mPendingThumbnails.size() > 0) {
3266 // There are clients waiting to receive thumbnails so, in case
3267 // this is an activity that someone is waiting for, add it
3268 // to the pending list so we can correctly update the clients.
3269 mService.mCancelledThumbnails.add(r);
3270 }
3271
3272 // Get rid of any pending idle timeouts.
3273 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3274 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
3275 }
3276
3277 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3278 if (r.state != ActivityState.DESTROYED) {
3279 mHistory.remove(r);
3280 r.inHistory = false;
3281 r.state = ActivityState.DESTROYED;
3282 mService.mWindowManager.removeAppToken(r);
3283 if (VALIDATE_TOKENS) {
3284 mService.mWindowManager.validateAppTokens(mHistory);
3285 }
3286 cleanUpActivityServicesLocked(r);
3287 r.removeUriPermissionsLocked();
3288 }
3289 }
3290
3291 /**
3292 * Perform clean-up of service connections in an activity record.
3293 */
3294 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3295 // Throw away any services that have been bound by this activity.
3296 if (r.connections != null) {
3297 Iterator<ConnectionRecord> it = r.connections.iterator();
3298 while (it.hasNext()) {
3299 ConnectionRecord c = it.next();
3300 mService.removeConnectionLocked(c, null, r);
3301 }
3302 r.connections = null;
3303 }
3304 }
3305
3306 /**
3307 * Destroy the current CLIENT SIDE instance of an activity. This may be
3308 * called both when actually finishing an activity, or when performing
3309 * a configuration switch where we destroy the current client-side object
3310 * but then create a new client-side object for this same HistoryRecord.
3311 */
3312 final boolean destroyActivityLocked(ActivityRecord r,
3313 boolean removeFromApp) {
3314 if (DEBUG_SWITCH) Slog.v(
3315 TAG, "Removing activity: token=" + r
3316 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3317 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3318 System.identityHashCode(r),
3319 r.task.taskId, r.shortComponentName);
3320
3321 boolean removedFromHistory = false;
3322
3323 cleanUpActivityLocked(r, false);
3324
3325 final boolean hadApp = r.app != null;
3326
3327 if (hadApp) {
3328 if (removeFromApp) {
3329 int idx = r.app.activities.indexOf(r);
3330 if (idx >= 0) {
3331 r.app.activities.remove(idx);
3332 }
3333 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3334 mService.mHeavyWeightProcess = null;
3335 mService.mHandler.sendEmptyMessage(
3336 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3337 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003338 if (r.app.activities.size() == 0) {
3339 // No longer have activities, so update location in
3340 // LRU list.
3341 mService.updateLruProcessLocked(r.app, true, false);
3342 }
3343 }
3344
3345 boolean skipDestroy = false;
3346
3347 try {
3348 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3349 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3350 r.configChangeFlags);
3351 } catch (Exception e) {
3352 // We can just ignore exceptions here... if the process
3353 // has crashed, our death notification will clean things
3354 // up.
3355 //Slog.w(TAG, "Exception thrown during finish", e);
3356 if (r.finishing) {
3357 removeActivityFromHistoryLocked(r);
3358 removedFromHistory = true;
3359 skipDestroy = true;
3360 }
3361 }
3362
3363 r.app = null;
3364 r.nowVisible = false;
3365
3366 if (r.finishing && !skipDestroy) {
3367 r.state = ActivityState.DESTROYING;
3368 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3369 msg.obj = r;
3370 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3371 } else {
3372 r.state = ActivityState.DESTROYED;
3373 }
3374 } else {
3375 // remove this record from the history.
3376 if (r.finishing) {
3377 removeActivityFromHistoryLocked(r);
3378 removedFromHistory = true;
3379 } else {
3380 r.state = ActivityState.DESTROYED;
3381 }
3382 }
3383
3384 r.configChangeFlags = 0;
3385
3386 if (!mLRUActivities.remove(r) && hadApp) {
3387 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3388 }
3389
3390 return removedFromHistory;
3391 }
3392
3393 final void activityDestroyed(IBinder token) {
3394 synchronized (mService) {
3395 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3396
3397 int index = indexOfTokenLocked(token);
3398 if (index >= 0) {
3399 ActivityRecord r = (ActivityRecord)mHistory.get(index);
3400 if (r.state == ActivityState.DESTROYING) {
3401 final long origId = Binder.clearCallingIdentity();
3402 removeActivityFromHistoryLocked(r);
3403 Binder.restoreCallingIdentity(origId);
3404 }
3405 }
3406 }
3407 }
3408
3409 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3410 int i = list.size();
3411 if (localLOGV) Slog.v(
3412 TAG, "Removing app " + app + " from list " + list
3413 + " with " + i + " entries");
3414 while (i > 0) {
3415 i--;
3416 ActivityRecord r = (ActivityRecord)list.get(i);
3417 if (localLOGV) Slog.v(
3418 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3419 if (r.app == app) {
3420 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3421 list.remove(i);
3422 }
3423 }
3424 }
3425
3426 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3427 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3428 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
3429 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3430 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3431 }
3432
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003433 /**
3434 * Move the current home activity's task (if one exists) to the front
3435 * of the stack.
3436 */
3437 final void moveHomeToFrontLocked() {
3438 TaskRecord homeTask = null;
3439 for (int i=mHistory.size()-1; i>=0; i--) {
3440 ActivityRecord hr = (ActivityRecord)mHistory.get(i);
3441 if (hr.isHomeActivity) {
3442 homeTask = hr.task;
3443 }
3444 }
3445 if (homeTask != null) {
3446 moveTaskToFrontLocked(homeTask, null);
3447 }
3448 }
3449
3450
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003451 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3452 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3453
3454 final int task = tr.taskId;
3455 int top = mHistory.size()-1;
3456
3457 if (top < 0 || ((ActivityRecord)mHistory.get(top)).task.taskId == task) {
3458 // nothing to do!
3459 return;
3460 }
3461
3462 ArrayList moved = new ArrayList();
3463
3464 // Applying the affinities may have removed entries from the history,
3465 // so get the size again.
3466 top = mHistory.size()-1;
3467 int pos = top;
3468
3469 // Shift all activities with this task up to the top
3470 // of the stack, keeping them in the same internal order.
3471 while (pos >= 0) {
3472 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3473 if (localLOGV) Slog.v(
3474 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3475 boolean first = true;
3476 if (r.task.taskId == task) {
3477 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3478 mHistory.remove(pos);
3479 mHistory.add(top, r);
3480 moved.add(0, r);
3481 top--;
3482 if (first && mMainStack) {
3483 mService.addRecentTaskLocked(r.task);
3484 first = false;
3485 }
3486 }
3487 pos--;
3488 }
3489
3490 if (DEBUG_TRANSITION) Slog.v(TAG,
3491 "Prepare to front transition: task=" + tr);
3492 if (reason != null &&
3493 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003494 mService.mWindowManager.prepareAppTransition(
3495 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003496 ActivityRecord r = topRunningActivityLocked(null);
3497 if (r != null) {
3498 mNoAnimActivities.add(r);
3499 }
3500 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003501 mService.mWindowManager.prepareAppTransition(
3502 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003503 }
3504
3505 mService.mWindowManager.moveAppTokensToTop(moved);
3506 if (VALIDATE_TOKENS) {
3507 mService.mWindowManager.validateAppTokens(mHistory);
3508 }
3509
3510 finishTaskMoveLocked(task);
3511 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3512 }
3513
3514 private final void finishTaskMoveLocked(int task) {
3515 resumeTopActivityLocked(null);
3516 }
3517
3518 /**
3519 * Worker method for rearranging history stack. Implements the function of moving all
3520 * activities for a specific task (gathering them if disjoint) into a single group at the
3521 * bottom of the stack.
3522 *
3523 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3524 * to premeptively cancel the move.
3525 *
3526 * @param task The taskId to collect and move to the bottom.
3527 * @return Returns true if the move completed, false if not.
3528 */
3529 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3530 Slog.i(TAG, "moveTaskToBack: " + task);
3531
3532 // If we have a watcher, preflight the move before committing to it. First check
3533 // for *other* available tasks, but if none are available, then try again allowing the
3534 // current task to be selected.
3535 if (mMainStack && mService.mController != null) {
3536 ActivityRecord next = topRunningActivityLocked(null, task);
3537 if (next == null) {
3538 next = topRunningActivityLocked(null, 0);
3539 }
3540 if (next != null) {
3541 // ask watcher if this is allowed
3542 boolean moveOK = true;
3543 try {
3544 moveOK = mService.mController.activityResuming(next.packageName);
3545 } catch (RemoteException e) {
3546 mService.mController = null;
3547 }
3548 if (!moveOK) {
3549 return false;
3550 }
3551 }
3552 }
3553
3554 ArrayList moved = new ArrayList();
3555
3556 if (DEBUG_TRANSITION) Slog.v(TAG,
3557 "Prepare to back transition: task=" + task);
3558
3559 final int N = mHistory.size();
3560 int bottom = 0;
3561 int pos = 0;
3562
3563 // Shift all activities with this task down to the bottom
3564 // of the stack, keeping them in the same internal order.
3565 while (pos < N) {
3566 ActivityRecord r = (ActivityRecord)mHistory.get(pos);
3567 if (localLOGV) Slog.v(
3568 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3569 if (r.task.taskId == task) {
3570 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3571 mHistory.remove(pos);
3572 mHistory.add(bottom, r);
3573 moved.add(r);
3574 bottom++;
3575 }
3576 pos++;
3577 }
3578
3579 if (reason != null &&
3580 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003581 mService.mWindowManager.prepareAppTransition(
3582 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003583 ActivityRecord r = topRunningActivityLocked(null);
3584 if (r != null) {
3585 mNoAnimActivities.add(r);
3586 }
3587 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003588 mService.mWindowManager.prepareAppTransition(
3589 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 }
3591 mService.mWindowManager.moveAppTokensToBottom(moved);
3592 if (VALIDATE_TOKENS) {
3593 mService.mWindowManager.validateAppTokens(mHistory);
3594 }
3595
3596 finishTaskMoveLocked(task);
3597 return true;
3598 }
3599
3600 private final void logStartActivity(int tag, ActivityRecord r,
3601 TaskRecord task) {
3602 EventLog.writeEvent(tag,
3603 System.identityHashCode(r), task.taskId,
3604 r.shortComponentName, r.intent.getAction(),
3605 r.intent.getType(), r.intent.getDataString(),
3606 r.intent.getFlags());
3607 }
3608
3609 /**
3610 * Make sure the given activity matches the current configuration. Returns
3611 * false if the activity had to be destroyed. Returns true if the
3612 * configuration is the same, or the activity will remain running as-is
3613 * for whatever reason. Ensures the HistoryRecord is updated with the
3614 * correct configuration and all other bookkeeping is handled.
3615 */
3616 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3617 int globalChanges) {
3618 if (mConfigWillChange) {
3619 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3620 "Skipping config check (will change): " + r);
3621 return true;
3622 }
3623
3624 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3625 "Ensuring correct configuration: " + r);
3626
3627 // Short circuit: if the two configurations are the exact same
3628 // object (the common case), then there is nothing to do.
3629 Configuration newConfig = mService.mConfiguration;
3630 if (r.configuration == newConfig) {
3631 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3632 "Configuration unchanged in " + r);
3633 return true;
3634 }
3635
3636 // We don't worry about activities that are finishing.
3637 if (r.finishing) {
3638 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3639 "Configuration doesn't matter in finishing " + r);
3640 r.stopFreezingScreenLocked(false);
3641 return true;
3642 }
3643
3644 // Okay we now are going to make this activity have the new config.
3645 // But then we need to figure out how it needs to deal with that.
3646 Configuration oldConfig = r.configuration;
3647 r.configuration = newConfig;
3648
3649 // If the activity isn't currently running, just leave the new
3650 // configuration and it will pick that up next time it starts.
3651 if (r.app == null || r.app.thread == null) {
3652 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3653 "Configuration doesn't matter not running " + r);
3654 r.stopFreezingScreenLocked(false);
3655 return true;
3656 }
3657
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003658 // Figure out what has changed between the two configurations.
3659 int changes = oldConfig.diff(newConfig);
3660 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3661 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3662 + Integer.toHexString(changes) + ", handles=0x"
3663 + Integer.toHexString(r.info.configChanges)
3664 + ", newConfig=" + newConfig);
3665 }
3666 if ((changes&(~r.info.configChanges)) != 0) {
3667 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3668 r.configChangeFlags |= changes;
3669 r.startFreezingScreenLocked(r.app, globalChanges);
3670 if (r.app == null || r.app.thread == null) {
3671 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3672 "Switch is destroying non-running " + r);
3673 destroyActivityLocked(r, true);
3674 } else if (r.state == ActivityState.PAUSING) {
3675 // A little annoying: we are waiting for this activity to
3676 // finish pausing. Let's not do anything now, but just
3677 // flag that it needs to be restarted when done pausing.
3678 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3679 "Switch is skipping already pausing " + r);
3680 r.configDestroy = true;
3681 return true;
3682 } else if (r.state == ActivityState.RESUMED) {
3683 // Try to optimize this case: the configuration is changing
3684 // and we need to restart the top, resumed activity.
3685 // Instead of doing the normal handshaking, just say
3686 // "restart!".
3687 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3688 "Switch is restarting resumed " + r);
3689 relaunchActivityLocked(r, r.configChangeFlags, true);
3690 r.configChangeFlags = 0;
3691 } else {
3692 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3693 "Switch is restarting non-resumed " + r);
3694 relaunchActivityLocked(r, r.configChangeFlags, false);
3695 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003696 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003697
3698 // All done... tell the caller we weren't able to keep this
3699 // activity around.
3700 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003701 }
3702
3703 // Default case: the activity can handle this new configuration, so
3704 // hand it over. Note that we don't need to give it the new
3705 // configuration, since we always send configuration changes to all
3706 // process when they happen so it can just use whatever configuration
3707 // it last got.
3708 if (r.app != null && r.app.thread != null) {
3709 try {
3710 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
3711 r.app.thread.scheduleActivityConfigurationChanged(r);
3712 } catch (RemoteException e) {
3713 // If process died, whatever.
3714 }
3715 }
3716 r.stopFreezingScreenLocked(false);
3717
3718 return true;
3719 }
3720
3721 private final boolean relaunchActivityLocked(ActivityRecord r,
3722 int changes, boolean andResume) {
3723 List<ResultInfo> results = null;
3724 List<Intent> newIntents = null;
3725 if (andResume) {
3726 results = r.results;
3727 newIntents = r.newIntents;
3728 }
3729 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
3730 + " with results=" + results + " newIntents=" + newIntents
3731 + " andResume=" + andResume);
3732 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
3733 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
3734 r.task.taskId, r.shortComponentName);
3735
3736 r.startFreezingScreenLocked(r.app, 0);
3737
3738 try {
3739 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
3740 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
3741 changes, !andResume, mService.mConfiguration);
3742 // Note: don't need to call pauseIfSleepingLocked() here, because
3743 // the caller will only pass in 'andResume' if this activity is
3744 // currently resumed, which implies we aren't sleeping.
3745 } catch (RemoteException e) {
3746 return false;
3747 }
3748
3749 if (andResume) {
3750 r.results = null;
3751 r.newIntents = null;
3752 if (mMainStack) {
3753 mService.reportResumedActivityLocked(r);
3754 }
3755 }
3756
3757 return true;
3758 }
3759}