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