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