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