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