blob: 93d816467e8b8d022add6677ce71dd394b08fb53 [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;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070024import android.app.ActivityManager;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070025import android.app.AppGlobals;
26import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028import static android.app.IActivityManager.START_CLASS_NOT_FOUND;
29import static android.app.IActivityManager.START_DELIVERED_TO_TOP;
30import static android.app.IActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
31import static android.app.IActivityManager.START_INTENT_NOT_RESOLVED;
32import static android.app.IActivityManager.START_PERMISSION_DENIED;
33import static android.app.IActivityManager.START_RETURN_INTENT_TO_CALLER;
34import static android.app.IActivityManager.START_SUCCESS;
35import static android.app.IActivityManager.START_SWITCHES_CANCELED;
36import static android.app.IActivityManager.START_TASK_TO_FRONT;
37import android.app.IApplicationThread;
38import android.app.PendingIntent;
39import android.app.ResultInfo;
40import android.app.IActivityManager.WaitResult;
41import android.content.ComponentName;
42import android.content.Context;
43import android.content.IIntentSender;
44import android.content.Intent;
45import android.content.IntentSender;
46import android.content.pm.ActivityInfo;
47import android.content.pm.ApplicationInfo;
48import android.content.pm.PackageManager;
49import android.content.pm.ResolveInfo;
50import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080051import android.content.res.Resources;
52import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070053import android.net.Uri;
54import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070055import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.Handler;
57import android.os.IBinder;
58import android.os.Message;
59import android.os.PowerManager;
60import android.os.RemoteException;
61import android.os.SystemClock;
62import android.util.EventLog;
63import android.util.Log;
64import android.util.Slog;
65import android.view.WindowManagerPolicy;
66
67import java.lang.ref.WeakReference;
68import java.util.ArrayList;
69import java.util.Iterator;
70import java.util.List;
71
72/**
73 * State and management of a single stack of activities.
74 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070075final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070077 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070078 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
79 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
80 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
81 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
82 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
83 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
84 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
85 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
86
Dianne Hackbornce86ba82011-07-13 19:33:41 -070087 static final boolean DEBUG_STATES = false;
88
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070089 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
90
91 // How long we wait until giving up on the last activity telling us it
92 // is idle.
93 static final int IDLE_TIMEOUT = 10*1000;
94
95 // How long we wait until giving up on the last activity to pause. This
96 // is short because it directly impacts the responsiveness of starting the
97 // next activity.
98 static final int PAUSE_TIMEOUT = 500;
99
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800100 // How long we can hold the sleep wake lock before giving up.
101 static final int SLEEP_TIMEOUT = 5*1000;
102
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700103 // How long we can hold the launch wake lock before giving up.
104 static final int LAUNCH_TIMEOUT = 10*1000;
105
106 // How long we wait until giving up on an activity telling us it has
107 // finished destroying itself.
108 static final int DESTROY_TIMEOUT = 10*1000;
109
110 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800111 // disabled.
112 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700113
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700114 // How long between activity launches that we consider safe to not warn
115 // the user about an unexpected activity being launched on top.
116 static final long START_WARN_TIME = 5*1000;
117
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700118 // Set to false to disable the preview that is shown while a new activity
119 // is being started.
120 static final boolean SHOW_APP_STARTING_PREVIEW = true;
121
122 enum ActivityState {
123 INITIALIZING,
124 RESUMED,
125 PAUSING,
126 PAUSED,
127 STOPPING,
128 STOPPED,
129 FINISHING,
130 DESTROYING,
131 DESTROYED
132 }
133
134 final ActivityManagerService mService;
135 final boolean mMainStack;
136
137 final Context mContext;
138
139 /**
140 * The back history of all previous (and possibly still
141 * running) activities. It contains HistoryRecord objects.
142 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700143 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700144
145 /**
146 * List of running activities, sorted by recent usage.
147 * The first entry in the list is the least recently used.
148 * It contains HistoryRecord objects.
149 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700150 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700151
152 /**
153 * List of activities that are waiting for a new activity
154 * to become visible before completing whatever operation they are
155 * supposed to do.
156 */
157 final ArrayList<ActivityRecord> mWaitingVisibleActivities
158 = new ArrayList<ActivityRecord>();
159
160 /**
161 * List of activities that are ready to be stopped, but waiting
162 * for the next activity to settle down before doing so. It contains
163 * HistoryRecord objects.
164 */
165 final ArrayList<ActivityRecord> mStoppingActivities
166 = new ArrayList<ActivityRecord>();
167
168 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800169 * List of activities that are in the process of going to sleep.
170 */
171 final ArrayList<ActivityRecord> mGoingToSleepActivities
172 = new ArrayList<ActivityRecord>();
173
174 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700175 * Animations that for the current transition have requested not to
176 * be considered for the transition animation.
177 */
178 final ArrayList<ActivityRecord> mNoAnimActivities
179 = new ArrayList<ActivityRecord>();
180
181 /**
182 * List of activities that are ready to be finished, but waiting
183 * for the previous activity to settle down before doing so. It contains
184 * HistoryRecord objects.
185 */
186 final ArrayList<ActivityRecord> mFinishingActivities
187 = new ArrayList<ActivityRecord>();
188
189 /**
190 * List of people waiting to find out about the next launched activity.
191 */
192 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
193 = new ArrayList<IActivityManager.WaitResult>();
194
195 /**
196 * List of people waiting to find out about the next visible activity.
197 */
198 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
199 = new ArrayList<IActivityManager.WaitResult>();
200
201 /**
202 * Set when the system is going to sleep, until we have
203 * successfully paused the current activity and released our wake lock.
204 * At that point the system is allowed to actually sleep.
205 */
206 final PowerManager.WakeLock mGoingToSleep;
207
208 /**
209 * We don't want to allow the device to go to sleep while in the process
210 * of launching an activity. This is primarily to allow alarm intent
211 * receivers to launch an activity and get that to run before the device
212 * goes back to sleep.
213 */
214 final PowerManager.WakeLock mLaunchingActivity;
215
216 /**
217 * When we are in the process of pausing an activity, before starting the
218 * next one, this variable holds the activity that is currently being paused.
219 */
220 ActivityRecord mPausingActivity = null;
221
222 /**
223 * This is the last activity that we put into the paused state. This is
224 * used to determine if we need to do an activity transition while sleeping,
225 * when we normally hold the top activity paused.
226 */
227 ActivityRecord mLastPausedActivity = null;
228
229 /**
230 * Current activity that is resumed, or null if there is none.
231 */
232 ActivityRecord mResumedActivity = null;
233
234 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700235 * This is the last activity that has been started. It is only used to
236 * identify when multiple activities are started at once so that the user
237 * can be warned they may not be in the activity they think they are.
238 */
239 ActivityRecord mLastStartedActivity = null;
240
241 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700242 * Set when we know we are going to be calling updateConfiguration()
243 * soon, so want to skip intermediate config checks.
244 */
245 boolean mConfigWillChange;
246
247 /**
248 * Set to indicate whether to issue an onUserLeaving callback when a
249 * newly launched activity is being brought in front of us.
250 */
251 boolean mUserLeaving = false;
252
253 long mInitialStartTime = 0;
254
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800255 /**
256 * Set when we have taken too long waiting to go to sleep.
257 */
258 boolean mSleepTimeout = false;
259
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800260 int mThumbnailWidth = -1;
261 int mThumbnailHeight = -1;
262
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800263 static final int SLEEP_TIMEOUT_MSG = 8;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700264 static final int PAUSE_TIMEOUT_MSG = 9;
265 static final int IDLE_TIMEOUT_MSG = 10;
266 static final int IDLE_NOW_MSG = 11;
267 static final int LAUNCH_TIMEOUT_MSG = 16;
268 static final int DESTROY_TIMEOUT_MSG = 17;
269 static final int RESUME_TOP_ACTIVITY_MSG = 19;
270
271 final Handler mHandler = new Handler() {
272 //public Handler() {
273 // if (localLOGV) Slog.v(TAG, "Handler started!");
274 //}
275
276 public void handleMessage(Message msg) {
277 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800278 case SLEEP_TIMEOUT_MSG: {
279 if (mService.isSleeping()) {
280 Slog.w(TAG, "Sleep timeout! Sleeping now.");
281 mSleepTimeout = true;
282 checkReadyForSleepLocked();
283 }
284 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700285 case PAUSE_TIMEOUT_MSG: {
286 IBinder token = (IBinder)msg.obj;
287 // We don't at this point know if the activity is fullscreen,
288 // so we need to be conservative and assume it isn't.
289 Slog.w(TAG, "Activity pause timeout for " + token);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800290 activityPaused(token, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700291 } break;
292 case IDLE_TIMEOUT_MSG: {
293 if (mService.mDidDexOpt) {
294 mService.mDidDexOpt = false;
295 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
296 nmsg.obj = msg.obj;
297 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
298 return;
299 }
300 // We don't at this point know if the activity is fullscreen,
301 // so we need to be conservative and assume it isn't.
302 IBinder token = (IBinder)msg.obj;
303 Slog.w(TAG, "Activity idle timeout for " + token);
304 activityIdleInternal(token, true, null);
305 } break;
306 case DESTROY_TIMEOUT_MSG: {
307 IBinder token = (IBinder)msg.obj;
308 // We don't at this point know if the activity is fullscreen,
309 // so we need to be conservative and assume it isn't.
310 Slog.w(TAG, "Activity destroy timeout for " + token);
311 activityDestroyed(token);
312 } break;
313 case IDLE_NOW_MSG: {
314 IBinder token = (IBinder)msg.obj;
315 activityIdleInternal(token, false, null);
316 } break;
317 case LAUNCH_TIMEOUT_MSG: {
318 if (mService.mDidDexOpt) {
319 mService.mDidDexOpt = false;
320 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
321 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
322 return;
323 }
324 synchronized (mService) {
325 if (mLaunchingActivity.isHeld()) {
326 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
327 mLaunchingActivity.release();
328 }
329 }
330 } break;
331 case RESUME_TOP_ACTIVITY_MSG: {
332 synchronized (mService) {
333 resumeTopActivityLocked(null);
334 }
335 } break;
336 }
337 }
338 };
339
340 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
341 mService = service;
342 mContext = context;
343 mMainStack = mainStack;
344 PowerManager pm =
345 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
346 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
347 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
348 mLaunchingActivity.setReferenceCounted(false);
349 }
350
351 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
352 int i = mHistory.size()-1;
353 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700354 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700355 if (!r.finishing && r != notTop) {
356 return r;
357 }
358 i--;
359 }
360 return null;
361 }
362
363 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
364 int i = mHistory.size()-1;
365 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700366 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 if (!r.finishing && !r.delayedResume && r != notTop) {
368 return r;
369 }
370 i--;
371 }
372 return null;
373 }
374
375 /**
376 * This is a simplified version of topRunningActivityLocked that provides a number of
377 * optional skip-over modes. It is intended for use with the ActivityController hook only.
378 *
379 * @param token If non-null, any history records matching this token will be skipped.
380 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
381 *
382 * @return Returns the HistoryRecord of the next activity on the stack.
383 */
384 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
385 int i = mHistory.size()-1;
386 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700387 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700388 // Note: the taskId check depends on real taskId fields being non-zero
389 if (!r.finishing && (token != r) && (taskId != r.task.taskId)) {
390 return r;
391 }
392 i--;
393 }
394 return null;
395 }
396
397 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700398 try {
399 ActivityRecord r = (ActivityRecord)token;
400 return mHistory.indexOf(r);
401 } catch (ClassCastException e) {
402 Slog.w(TAG, "Bad activity token: " + token, e);
403 return -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700404 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700405 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700406
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700407 final ActivityRecord isInStackLocked(IBinder token) {
408 try {
409 ActivityRecord r = (ActivityRecord)token;
410 if (mHistory.contains(r)) {
411 return r;
412 }
413 } catch (ClassCastException e) {
414 Slog.w(TAG, "Bad activity token: " + token, e);
415 }
416 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 }
418
419 private final boolean updateLRUListLocked(ActivityRecord r) {
420 final boolean hadit = mLRUActivities.remove(r);
421 mLRUActivities.add(r);
422 return hadit;
423 }
424
425 /**
426 * Returns the top activity in any existing task matching the given
427 * Intent. Returns null if no such task is found.
428 */
429 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
430 ComponentName cls = intent.getComponent();
431 if (info.targetActivity != null) {
432 cls = new ComponentName(info.packageName, info.targetActivity);
433 }
434
435 TaskRecord cp = null;
436
437 final int N = mHistory.size();
438 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700439 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 if (!r.finishing && r.task != cp
441 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
442 cp = r.task;
443 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
444 // + "/aff=" + r.task.affinity + " to new cls="
445 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
446 if (r.task.affinity != null) {
447 if (r.task.affinity.equals(info.taskAffinity)) {
448 //Slog.i(TAG, "Found matching affinity!");
449 return r;
450 }
451 } else if (r.task.intent != null
452 && r.task.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 } else if (r.task.affinityIntent != null
458 && r.task.affinityIntent.getComponent().equals(cls)) {
459 //Slog.i(TAG, "Found matching class!");
460 //dump();
461 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
462 return r;
463 }
464 }
465 }
466
467 return null;
468 }
469
470 /**
471 * Returns the first activity (starting from the top of the stack) that
472 * is the same as the given activity. Returns null if no such activity
473 * is found.
474 */
475 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
476 ComponentName cls = intent.getComponent();
477 if (info.targetActivity != null) {
478 cls = new ComponentName(info.packageName, info.targetActivity);
479 }
480
481 final int N = mHistory.size();
482 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700483 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700484 if (!r.finishing) {
485 if (r.intent.getComponent().equals(cls)) {
486 //Slog.i(TAG, "Found matching class!");
487 //dump();
488 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
489 return r;
490 }
491 }
492 }
493
494 return null;
495 }
496
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700497 final void showAskCompatModeDialogLocked(ActivityRecord r) {
498 Message msg = Message.obtain();
499 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
500 msg.obj = r.task.askedCompatMode ? null : r;
501 mService.mHandler.sendMessage(msg);
502 }
503
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700504 final boolean realStartActivityLocked(ActivityRecord r,
505 ProcessRecord app, boolean andResume, boolean checkConfig)
506 throws RemoteException {
507
508 r.startFreezingScreenLocked(app, 0);
509 mService.mWindowManager.setAppVisibility(r, true);
510
511 // Have the window manager re-evaluate the orientation of
512 // the screen based on the new activity order. Note that
513 // as a result of this, it can call back into the activity
514 // manager with a new orientation. We don't care about that,
515 // because the activity is not currently running so we are
516 // just restarting it anyway.
517 if (checkConfig) {
518 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
519 mService.mConfiguration,
520 r.mayFreezeScreenLocked(app) ? r : null);
521 mService.updateConfigurationLocked(config, r);
522 }
523
524 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700525 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700526
527 if (localLOGV) Slog.v(TAG, "Launching: " + r);
528
529 int idx = app.activities.indexOf(r);
530 if (idx < 0) {
531 app.activities.add(r);
532 }
533 mService.updateLruProcessLocked(app, true, true);
534
535 try {
536 if (app.thread == null) {
537 throw new RemoteException();
538 }
539 List<ResultInfo> results = null;
540 List<Intent> newIntents = null;
541 if (andResume) {
542 results = r.results;
543 newIntents = r.newIntents;
544 }
545 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
546 + " icicle=" + r.icicle
547 + " with results=" + results + " newIntents=" + newIntents
548 + " andResume=" + andResume);
549 if (andResume) {
550 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
551 System.identityHashCode(r),
552 r.task.taskId, r.shortComponentName);
553 }
554 if (r.isHomeActivity) {
555 mService.mHomeProcess = app;
556 }
557 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800558 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400559 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700560 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700561 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700562 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
563 System.identityHashCode(r),
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700564 r.info, r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700565 mService.isNextTransitionForward());
566
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700567 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700568 // This may be a heavy-weight process! Note that the package
569 // manager will ensure that only activity can run in the main
570 // process of the .apk, which is the only thing that will be
571 // considered heavy-weight.
572 if (app.processName.equals(app.info.packageName)) {
573 if (mService.mHeavyWeightProcess != null
574 && mService.mHeavyWeightProcess != app) {
575 Log.w(TAG, "Starting new heavy weight process " + app
576 + " when already running "
577 + mService.mHeavyWeightProcess);
578 }
579 mService.mHeavyWeightProcess = app;
580 Message msg = mService.mHandler.obtainMessage(
581 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
582 msg.obj = r;
583 mService.mHandler.sendMessage(msg);
584 }
585 }
586
587 } catch (RemoteException e) {
588 if (r.launchFailed) {
589 // This is the second time we failed -- finish activity
590 // and give up.
591 Slog.e(TAG, "Second failure launching "
592 + r.intent.getComponent().flattenToShortString()
593 + ", giving up", e);
594 mService.appDiedLocked(app, app.pid, app.thread);
595 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
596 "2nd-crash");
597 return false;
598 }
599
600 // This is the first time we failed -- restart process and
601 // retry.
602 app.activities.remove(r);
603 throw e;
604 }
605
606 r.launchFailed = false;
607 if (updateLRUListLocked(r)) {
608 Slog.w(TAG, "Activity " + r
609 + " being launched, but already in LRU list");
610 }
611
612 if (andResume) {
613 // As part of the process of launching, ActivityThread also performs
614 // a resume.
615 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700616 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
617 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700618 r.stopped = false;
619 mResumedActivity = r;
620 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800621 if (mMainStack) {
622 mService.addRecentTaskLocked(r.task);
623 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700624 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800625 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700626 } else {
627 // This activity is not starting in the resumed state... which
628 // should look like we asked it to pause+stop (but remain visible),
629 // and it has done so and reported back the current icicle and
630 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700631 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
632 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700633 r.state = ActivityState.STOPPED;
634 r.stopped = true;
635 }
636
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800637 r.icicle = null;
638 r.haveState = false;
639
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700640 // Launch the new version setup screen if needed. We do this -after-
641 // launching the initial activity (that is, home), so that it can have
642 // a chance to initialize itself while in the background, making the
643 // switch back to it faster and look better.
644 if (mMainStack) {
645 mService.startSetupActivityLocked();
646 }
647
648 return true;
649 }
650
651 private final void startSpecificActivityLocked(ActivityRecord r,
652 boolean andResume, boolean checkConfig) {
653 // Is this activity's application already running?
654 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
655 r.info.applicationInfo.uid);
656
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700657 if (r.launchTime == 0) {
658 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700659 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700660 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700661 }
662 } else if (mInitialStartTime == 0) {
663 mInitialStartTime = SystemClock.uptimeMillis();
664 }
665
666 if (app != null && app.thread != null) {
667 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700668 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700669 realStartActivityLocked(r, app, andResume, checkConfig);
670 return;
671 } catch (RemoteException e) {
672 Slog.w(TAG, "Exception when starting activity "
673 + r.intent.getComponent().flattenToShortString(), e);
674 }
675
676 // If a dead object exception was thrown -- fall through to
677 // restart the application.
678 }
679
680 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
681 "activity", r.intent.getComponent(), false);
682 }
683
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800684 void stopIfSleepingLocked() {
685 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700686 if (!mGoingToSleep.isHeld()) {
687 mGoingToSleep.acquire();
688 if (mLaunchingActivity.isHeld()) {
689 mLaunchingActivity.release();
690 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
691 }
692 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800693 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
694 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
695 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
696 checkReadyForSleepLocked();
697 }
698 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700699
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800700 void awakeFromSleepingLocked() {
701 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
702 mSleepTimeout = false;
703 if (mGoingToSleep.isHeld()) {
704 mGoingToSleep.release();
705 }
706 // Ensure activities are no longer sleeping.
707 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700708 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800709 r.setSleeping(false);
710 }
711 mGoingToSleepActivities.clear();
712 }
713
714 void activitySleptLocked(ActivityRecord r) {
715 mGoingToSleepActivities.remove(r);
716 checkReadyForSleepLocked();
717 }
718
719 void checkReadyForSleepLocked() {
720 if (!mService.isSleeping()) {
721 // Do not care.
722 return;
723 }
724
725 if (!mSleepTimeout) {
726 if (mResumedActivity != null) {
727 // Still have something resumed; can't sleep until it is paused.
728 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700729 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
730 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800731 return;
732 }
733 if (mPausingActivity != null) {
734 // Still waiting for something to pause; can't sleep yet.
735 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
736 return;
737 }
738
739 if (mStoppingActivities.size() > 0) {
740 // Still need to tell some activities to stop; can't sleep yet.
741 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
742 + mStoppingActivities.size() + " activities");
743 Message msg = Message.obtain();
744 msg.what = IDLE_NOW_MSG;
745 mHandler.sendMessage(msg);
746 return;
747 }
748
749 ensureActivitiesVisibleLocked(null, 0);
750
751 // Make sure any stopped but visible activities are now sleeping.
752 // This ensures that the activity's onStop() is called.
753 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700754 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800755 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
756 r.setSleeping(true);
757 }
758 }
759
760 if (mGoingToSleepActivities.size() > 0) {
761 // Still need to tell some activities to sleep; can't sleep yet.
762 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
763 + mGoingToSleepActivities.size() + " activities");
764 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700765 }
766 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800767
768 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
769
770 if (mGoingToSleep.isHeld()) {
771 mGoingToSleep.release();
772 }
773 if (mService.mShuttingDown) {
774 mService.notifyAll();
775 }
776
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700777 }
778
Dianne Hackbornd2835932010-12-13 16:28:46 -0800779 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800780 if (who.noDisplay) {
781 return null;
782 }
783
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800784 Resources res = mService.mContext.getResources();
785 int w = mThumbnailWidth;
786 int h = mThumbnailHeight;
787 if (w < 0) {
788 mThumbnailWidth = w =
789 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
790 mThumbnailHeight = h =
791 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
792 }
793
794 if (w > 0) {
Dianne Hackborn7c8a4b32010-12-15 14:58:00 -0800795 return mService.mWindowManager.screenshotApplications(who, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800796 }
797 return null;
798 }
799
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700800 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
801 if (mPausingActivity != null) {
802 RuntimeException e = new RuntimeException();
803 Slog.e(TAG, "Trying to pause when pause is already pending for "
804 + mPausingActivity, e);
805 }
806 ActivityRecord prev = mResumedActivity;
807 if (prev == null) {
808 RuntimeException e = new RuntimeException();
809 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
810 resumeTopActivityLocked(null);
811 return;
812 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700813 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
814 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700815 mResumedActivity = null;
816 mPausingActivity = prev;
817 mLastPausedActivity = prev;
818 prev.state = ActivityState.PAUSING;
819 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700820 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700821
822 mService.updateCpuStats();
823
824 if (prev.app != null && prev.app.thread != null) {
825 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
826 try {
827 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
828 System.identityHashCode(prev),
829 prev.shortComponentName);
830 prev.app.thread.schedulePauseActivity(prev, prev.finishing, userLeaving,
831 prev.configChangeFlags);
832 if (mMainStack) {
833 mService.updateUsageStats(prev, false);
834 }
835 } catch (Exception e) {
836 // Ignore exception, if process died other code will cleanup.
837 Slog.w(TAG, "Exception thrown during pause", e);
838 mPausingActivity = null;
839 mLastPausedActivity = null;
840 }
841 } else {
842 mPausingActivity = null;
843 mLastPausedActivity = null;
844 }
845
846 // If we are not going to sleep, we want to ensure the device is
847 // awake until the next activity is started.
848 if (!mService.mSleeping && !mService.mShuttingDown) {
849 mLaunchingActivity.acquire();
850 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
851 // To be safe, don't allow the wake lock to be held for too long.
852 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
853 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
854 }
855 }
856
857
858 if (mPausingActivity != null) {
859 // Have the window manager pause its key dispatching until the new
860 // activity has started. If we're pausing the activity just because
861 // the screen is being turned off and the UI is sleeping, don't interrupt
862 // key dispatch; the same activity will pick it up again on wakeup.
863 if (!uiSleeping) {
864 prev.pauseKeyDispatchingLocked();
865 } else {
866 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
867 }
868
869 // Schedule a pause timeout in case the app doesn't respond.
870 // We don't give it much time because this directly impacts the
871 // responsiveness seen by the user.
872 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
873 msg.obj = prev;
874 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
875 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
876 } else {
877 // This activity failed to schedule the
878 // pause, so just treat it as being paused now.
879 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
880 resumeTopActivityLocked(null);
881 }
882 }
883
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800884 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700885 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800886 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700887
888 ActivityRecord r = null;
889
890 synchronized (mService) {
891 int index = indexOfTokenLocked(token);
892 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700893 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700894 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
895 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700896 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
897 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700898 r.state = ActivityState.PAUSED;
899 completePauseLocked();
900 } else {
901 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
902 System.identityHashCode(r), r.shortComponentName,
903 mPausingActivity != null
904 ? mPausingActivity.shortComponentName : "(none)");
905 }
906 }
907 }
908 }
909
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700910 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
911 CharSequence description) {
912 r.icicle = icicle;
913 r.haveState = true;
914 r.updateThumbnail(thumbnail, description);
915 r.stopped = true;
916 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
917 r.state = ActivityState.STOPPED;
918 if (!r.finishing) {
919 if (r.configDestroy) {
920 destroyActivityLocked(r, true, false);
921 resumeTopActivityLocked(null);
922 }
923 }
924 }
925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700926 private final void completePauseLocked() {
927 ActivityRecord prev = mPausingActivity;
928 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
929
930 if (prev != null) {
931 if (prev.finishing) {
932 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
933 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE);
934 } else if (prev.app != null) {
935 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
936 if (prev.waitingVisible) {
937 prev.waitingVisible = false;
938 mWaitingVisibleActivities.remove(prev);
939 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
940 TAG, "Complete pause, no longer waiting: " + prev);
941 }
942 if (prev.configDestroy) {
943 // The previous is being paused because the configuration
944 // is changing, which means it is actually stopping...
945 // To juggle the fact that we are also starting a new
946 // instance right now, we need to first completely stop
947 // the current instance before starting the new one.
948 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700949 destroyActivityLocked(prev, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700950 } else {
951 mStoppingActivities.add(prev);
952 if (mStoppingActivities.size() > 3) {
953 // If we already have a few activities waiting to stop,
954 // then give up on things going idle and start clearing
955 // them out.
956 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
957 Message msg = Message.obtain();
958 msg.what = IDLE_NOW_MSG;
959 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800960 } else {
961 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700962 }
963 }
964 } else {
965 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
966 prev = null;
967 }
968 mPausingActivity = null;
969 }
970
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800971 if (!mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700972 resumeTopActivityLocked(prev);
973 } else {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800974 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700975 }
976
977 if (prev != null) {
978 prev.resumeKeyDispatchingLocked();
979 }
980
981 if (prev.app != null && prev.cpuTimeAtResume > 0
982 && mService.mBatteryStatsService.isOnBattery()) {
983 long diff = 0;
984 synchronized (mService.mProcessStatsThread) {
985 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
986 - prev.cpuTimeAtResume;
987 }
988 if (diff > 0) {
989 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
990 synchronized (bsi) {
991 BatteryStatsImpl.Uid.Proc ps =
992 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
993 prev.info.packageName);
994 if (ps != null) {
995 ps.addForegroundTimeLocked(diff);
996 }
997 }
998 }
999 }
1000 prev.cpuTimeAtResume = 0; // reset it
1001 }
1002
1003 /**
1004 * Once we know that we have asked an application to put an activity in
1005 * the resumed state (either by launching it or explicitly telling it),
1006 * this function updates the rest of our state to match that fact.
1007 */
1008 private final void completeResumeLocked(ActivityRecord next) {
1009 next.idle = false;
1010 next.results = null;
1011 next.newIntents = null;
1012
1013 // schedule an idle timeout in case the app doesn't do it for us.
1014 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1015 msg.obj = next;
1016 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1017
1018 if (false) {
1019 // The activity was never told to pause, so just keep
1020 // things going as-is. To maintain our own state,
1021 // we need to emulate it coming back and saying it is
1022 // idle.
1023 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1024 msg.obj = next;
1025 mHandler.sendMessage(msg);
1026 }
1027
1028 if (mMainStack) {
1029 mService.reportResumedActivityLocked(next);
1030 }
1031
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001032 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001033 if (mMainStack) {
1034 mService.setFocusedActivityLocked(next);
1035 }
1036 next.resumeKeyDispatchingLocked();
1037 ensureActivitiesVisibleLocked(null, 0);
1038 mService.mWindowManager.executeAppTransition();
1039 mNoAnimActivities.clear();
1040
1041 // Mark the point when the activity is resuming
1042 // TODO: To be more accurate, the mark should be before the onCreate,
1043 // not after the onResume. But for subsequent starts, onResume is fine.
1044 if (next.app != null) {
1045 synchronized (mService.mProcessStatsThread) {
1046 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1047 }
1048 } else {
1049 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1050 }
1051 }
1052
1053 /**
1054 * Make sure that all activities that need to be visible (that is, they
1055 * currently can be seen by the user) actually are.
1056 */
1057 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1058 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1059 if (DEBUG_VISBILITY) Slog.v(
1060 TAG, "ensureActivitiesVisible behind " + top
1061 + " configChanges=0x" + Integer.toHexString(configChanges));
1062
1063 // If the top activity is not fullscreen, then we need to
1064 // make sure any activities under it are now visible.
1065 final int count = mHistory.size();
1066 int i = count-1;
1067 while (mHistory.get(i) != top) {
1068 i--;
1069 }
1070 ActivityRecord r;
1071 boolean behindFullscreen = false;
1072 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001073 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001074 if (DEBUG_VISBILITY) Slog.v(
1075 TAG, "Make visible? " + r + " finishing=" + r.finishing
1076 + " state=" + r.state);
1077 if (r.finishing) {
1078 continue;
1079 }
1080
1081 final boolean doThisProcess = onlyThisProcess == null
1082 || onlyThisProcess.equals(r.processName);
1083
1084 // First: if this is not the current activity being started, make
1085 // sure it matches the current configuration.
1086 if (r != starting && doThisProcess) {
1087 ensureActivityConfigurationLocked(r, 0);
1088 }
1089
1090 if (r.app == null || r.app.thread == null) {
1091 if (onlyThisProcess == null
1092 || onlyThisProcess.equals(r.processName)) {
1093 // This activity needs to be visible, but isn't even
1094 // running... get it started, but don't resume it
1095 // at this point.
1096 if (DEBUG_VISBILITY) Slog.v(
1097 TAG, "Start and freeze screen for " + r);
1098 if (r != starting) {
1099 r.startFreezingScreenLocked(r.app, configChanges);
1100 }
1101 if (!r.visible) {
1102 if (DEBUG_VISBILITY) Slog.v(
1103 TAG, "Starting and making visible: " + r);
1104 mService.mWindowManager.setAppVisibility(r, true);
1105 }
1106 if (r != starting) {
1107 startSpecificActivityLocked(r, false, false);
1108 }
1109 }
1110
1111 } else if (r.visible) {
1112 // If this activity is already visible, then there is nothing
1113 // else to do here.
1114 if (DEBUG_VISBILITY) Slog.v(
1115 TAG, "Skipping: already visible at " + r);
1116 r.stopFreezingScreenLocked(false);
1117
1118 } else if (onlyThisProcess == null) {
1119 // This activity is not currently visible, but is running.
1120 // Tell it to become visible.
1121 r.visible = true;
1122 if (r.state != ActivityState.RESUMED && r != starting) {
1123 // If this activity is paused, tell it
1124 // to now show its window.
1125 if (DEBUG_VISBILITY) Slog.v(
1126 TAG, "Making visible and scheduling visibility: " + r);
1127 try {
1128 mService.mWindowManager.setAppVisibility(r, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001129 r.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001130 r.app.thread.scheduleWindowVisibility(r, true);
1131 r.stopFreezingScreenLocked(false);
1132 } catch (Exception e) {
1133 // Just skip on any failure; we'll make it
1134 // visible when it next restarts.
1135 Slog.w(TAG, "Exception thrown making visibile: "
1136 + r.intent.getComponent(), e);
1137 }
1138 }
1139 }
1140
1141 // Aggregate current change flags.
1142 configChanges |= r.configChangeFlags;
1143
1144 if (r.fullscreen) {
1145 // At this point, nothing else needs to be shown
1146 if (DEBUG_VISBILITY) Slog.v(
1147 TAG, "Stopping: fullscreen at " + r);
1148 behindFullscreen = true;
1149 i--;
1150 break;
1151 }
1152 }
1153
1154 // Now for any activities that aren't visible to the user, make
1155 // sure they no longer are keeping the screen frozen.
1156 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001157 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001158 if (DEBUG_VISBILITY) Slog.v(
1159 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1160 + " state=" + r.state
1161 + " behindFullscreen=" + behindFullscreen);
1162 if (!r.finishing) {
1163 if (behindFullscreen) {
1164 if (r.visible) {
1165 if (DEBUG_VISBILITY) Slog.v(
1166 TAG, "Making invisible: " + r);
1167 r.visible = false;
1168 try {
1169 mService.mWindowManager.setAppVisibility(r, false);
1170 if ((r.state == ActivityState.STOPPING
1171 || r.state == ActivityState.STOPPED)
1172 && r.app != null && r.app.thread != null) {
1173 if (DEBUG_VISBILITY) Slog.v(
1174 TAG, "Scheduling invisibility: " + r);
1175 r.app.thread.scheduleWindowVisibility(r, false);
1176 }
1177 } catch (Exception e) {
1178 // Just skip on any failure; we'll make it
1179 // visible when it next restarts.
1180 Slog.w(TAG, "Exception thrown making hidden: "
1181 + r.intent.getComponent(), e);
1182 }
1183 } else {
1184 if (DEBUG_VISBILITY) Slog.v(
1185 TAG, "Already invisible: " + r);
1186 }
1187 } else if (r.fullscreen) {
1188 if (DEBUG_VISBILITY) Slog.v(
1189 TAG, "Now behindFullscreen: " + r);
1190 behindFullscreen = true;
1191 }
1192 }
1193 i--;
1194 }
1195 }
1196
1197 /**
1198 * Version of ensureActivitiesVisible that can easily be called anywhere.
1199 */
1200 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1201 int configChanges) {
1202 ActivityRecord r = topRunningActivityLocked(null);
1203 if (r != null) {
1204 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1205 }
1206 }
1207
1208 /**
1209 * Ensure that the top activity in the stack is resumed.
1210 *
1211 * @param prev The previously resumed activity, for when in the process
1212 * of pausing; can be null to call from elsewhere.
1213 *
1214 * @return Returns true if something is being resumed, or false if
1215 * nothing happened.
1216 */
1217 final boolean resumeTopActivityLocked(ActivityRecord prev) {
1218 // Find the first activity that is not finishing.
1219 ActivityRecord next = topRunningActivityLocked(null);
1220
1221 // Remember how we'll process this pause/resume situation, and ensure
1222 // that the state is reset however we wind up proceeding.
1223 final boolean userLeaving = mUserLeaving;
1224 mUserLeaving = false;
1225
1226 if (next == null) {
1227 // There are no more activities! Let's just start up the
1228 // Launcher...
1229 if (mMainStack) {
1230 return mService.startHomeActivityLocked();
1231 }
1232 }
1233
1234 next.delayedResume = false;
1235
1236 // If the top activity is the resumed one, nothing to do.
1237 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1238 // Make sure we have executed any pending transitions, since there
1239 // should be nothing left to do at this point.
1240 mService.mWindowManager.executeAppTransition();
1241 mNoAnimActivities.clear();
1242 return false;
1243 }
1244
1245 // If we are sleeping, and there is no resumed activity, and the top
1246 // activity is paused, well that is the state we want.
1247 if ((mService.mSleeping || mService.mShuttingDown)
1248 && mLastPausedActivity == next && next.state == ActivityState.PAUSED) {
1249 // Make sure we have executed any pending transitions, since there
1250 // should be nothing left to do at this point.
1251 mService.mWindowManager.executeAppTransition();
1252 mNoAnimActivities.clear();
1253 return false;
1254 }
1255
1256 // The activity may be waiting for stop, but that is no longer
1257 // appropriate for it.
1258 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001259 mGoingToSleepActivities.remove(next);
1260 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001261 mWaitingVisibleActivities.remove(next);
1262
1263 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1264
1265 // If we are currently pausing an activity, then don't do anything
1266 // until that is done.
1267 if (mPausingActivity != null) {
1268 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1269 return false;
1270 }
1271
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001272 // Okay we are now going to start a switch, to 'next'. We may first
1273 // have to pause the current activity, but this is an important point
1274 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001275 // XXX "App Redirected" dialog is getting too many false positives
1276 // at this point, so turn off for now.
1277 if (false) {
1278 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1279 long now = SystemClock.uptimeMillis();
1280 final boolean inTime = mLastStartedActivity.startTime != 0
1281 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1282 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1283 final int nextUid = next.info.applicationInfo.uid;
1284 if (inTime && lastUid != nextUid
1285 && lastUid != next.launchedFromUid
1286 && mService.checkPermission(
1287 android.Manifest.permission.STOP_APP_SWITCHES,
1288 -1, next.launchedFromUid)
1289 != PackageManager.PERMISSION_GRANTED) {
1290 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1291 } else {
1292 next.startTime = now;
1293 mLastStartedActivity = next;
1294 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001295 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001296 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001297 mLastStartedActivity = next;
1298 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001299 }
1300
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001301 // We need to start pausing the current activity so the top one
1302 // can be resumed...
1303 if (mResumedActivity != null) {
1304 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1305 startPausingLocked(userLeaving, false);
1306 return true;
1307 }
1308
1309 if (prev != null && prev != next) {
1310 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1311 prev.waitingVisible = true;
1312 mWaitingVisibleActivities.add(prev);
1313 if (DEBUG_SWITCH) Slog.v(
1314 TAG, "Resuming top, waiting visible to hide: " + prev);
1315 } else {
1316 // The next activity is already visible, so hide the previous
1317 // activity's windows right now so we can show the new one ASAP.
1318 // We only do this if the previous is finishing, which should mean
1319 // it is on top of the one being resumed so hiding it quickly
1320 // is good. Otherwise, we want to do the normal route of allowing
1321 // the resumed activity to be shown so we can decide if the
1322 // previous should actually be hidden depending on whether the
1323 // new one is found to be full-screen or not.
1324 if (prev.finishing) {
1325 mService.mWindowManager.setAppVisibility(prev, false);
1326 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1327 + prev + ", waitingVisible="
1328 + (prev != null ? prev.waitingVisible : null)
1329 + ", nowVisible=" + next.nowVisible);
1330 } else {
1331 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1332 + prev + ", waitingVisible="
1333 + (prev != null ? prev.waitingVisible : null)
1334 + ", nowVisible=" + next.nowVisible);
1335 }
1336 }
1337 }
1338
Dianne Hackborne7f97212011-02-24 14:40:20 -08001339 // Launching this app's activity, make sure the app is no longer
1340 // considered stopped.
1341 try {
1342 AppGlobals.getPackageManager().setPackageStoppedState(
1343 next.packageName, false);
1344 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001345 } catch (IllegalArgumentException e) {
1346 Slog.w(TAG, "Failed trying to unstop package "
1347 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001348 }
1349
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001350 // We are starting up the next activity, so tell the window manager
1351 // that the previous one will be hidden soon. This way it can know
1352 // to ignore it when computing the desired screen orientation.
1353 if (prev != null) {
1354 if (prev.finishing) {
1355 if (DEBUG_TRANSITION) Slog.v(TAG,
1356 "Prepare close transition: prev=" + prev);
1357 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001358 mService.mWindowManager.prepareAppTransition(
1359 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001360 } else {
1361 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1362 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001363 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001364 }
1365 mService.mWindowManager.setAppWillBeHidden(prev);
1366 mService.mWindowManager.setAppVisibility(prev, false);
1367 } else {
1368 if (DEBUG_TRANSITION) Slog.v(TAG,
1369 "Prepare open transition: prev=" + prev);
1370 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001371 mService.mWindowManager.prepareAppTransition(
1372 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001373 } else {
1374 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1375 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001376 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001377 }
1378 }
1379 if (false) {
1380 mService.mWindowManager.setAppWillBeHidden(prev);
1381 mService.mWindowManager.setAppVisibility(prev, false);
1382 }
1383 } else if (mHistory.size() > 1) {
1384 if (DEBUG_TRANSITION) Slog.v(TAG,
1385 "Prepare open transition: no previous");
1386 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001387 mService.mWindowManager.prepareAppTransition(
1388 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001389 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001390 mService.mWindowManager.prepareAppTransition(
1391 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001392 }
1393 }
1394
1395 if (next.app != null && next.app.thread != null) {
1396 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1397
1398 // This activity is now becoming visible.
1399 mService.mWindowManager.setAppVisibility(next, true);
1400
1401 ActivityRecord lastResumedActivity = mResumedActivity;
1402 ActivityState lastState = next.state;
1403
1404 mService.updateCpuStats();
1405
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001406 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001407 next.state = ActivityState.RESUMED;
1408 mResumedActivity = next;
1409 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001410 if (mMainStack) {
1411 mService.addRecentTaskLocked(next.task);
1412 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001413 mService.updateLruProcessLocked(next.app, true, true);
1414 updateLRUListLocked(next);
1415
1416 // Have the window manager re-evaluate the orientation of
1417 // the screen based on the new activity order.
1418 boolean updated = false;
1419 if (mMainStack) {
1420 synchronized (mService) {
1421 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1422 mService.mConfiguration,
1423 next.mayFreezeScreenLocked(next.app) ? next : null);
1424 if (config != null) {
1425 next.frozenBeforeDestroy = true;
1426 }
1427 updated = mService.updateConfigurationLocked(config, next);
1428 }
1429 }
1430 if (!updated) {
1431 // The configuration update wasn't able to keep the existing
1432 // instance of the activity, and instead started a new one.
1433 // We should be all done, but let's just make sure our activity
1434 // is still at the top and schedule another run if something
1435 // weird happened.
1436 ActivityRecord nextNext = topRunningActivityLocked(null);
1437 if (DEBUG_SWITCH) Slog.i(TAG,
1438 "Activity config changed during resume: " + next
1439 + ", new next: " + nextNext);
1440 if (nextNext != next) {
1441 // Do over!
1442 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1443 }
1444 if (mMainStack) {
1445 mService.setFocusedActivityLocked(next);
1446 }
1447 ensureActivitiesVisibleLocked(null, 0);
1448 mService.mWindowManager.executeAppTransition();
1449 mNoAnimActivities.clear();
1450 return true;
1451 }
1452
1453 try {
1454 // Deliver all pending results.
1455 ArrayList a = next.results;
1456 if (a != null) {
1457 final int N = a.size();
1458 if (!next.finishing && N > 0) {
1459 if (DEBUG_RESULTS) Slog.v(
1460 TAG, "Delivering results to " + next
1461 + ": " + a);
1462 next.app.thread.scheduleSendResult(next, a);
1463 }
1464 }
1465
1466 if (next.newIntents != null) {
1467 next.app.thread.scheduleNewIntent(next.newIntents, next);
1468 }
1469
1470 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1471 System.identityHashCode(next),
1472 next.task.taskId, next.shortComponentName);
1473
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001474 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001475 showAskCompatModeDialogLocked(next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001476 next.app.thread.scheduleResumeActivity(next,
1477 mService.isNextTransitionForward());
1478
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001479 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001480
1481 } catch (Exception e) {
1482 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001483 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1484 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001485 next.state = lastState;
1486 mResumedActivity = lastResumedActivity;
1487 Slog.i(TAG, "Restarting because process died: " + next);
1488 if (!next.hasBeenLaunched) {
1489 next.hasBeenLaunched = true;
1490 } else {
1491 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1492 mService.mWindowManager.setAppStartingWindow(
1493 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001494 mService.compatibilityInfoForPackageLocked(
1495 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001496 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001497 next.labelRes, next.icon, next.windowFlags,
1498 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001499 }
1500 }
1501 startSpecificActivityLocked(next, true, false);
1502 return true;
1503 }
1504
1505 // From this point on, if something goes wrong there is no way
1506 // to recover the activity.
1507 try {
1508 next.visible = true;
1509 completeResumeLocked(next);
1510 } catch (Exception e) {
1511 // If any exception gets thrown, toss away this
1512 // activity and try the next one.
1513 Slog.w(TAG, "Exception thrown during resume of " + next, e);
1514 requestFinishActivityLocked(next, Activity.RESULT_CANCELED, null,
1515 "resume-exception");
1516 return true;
1517 }
1518
1519 // Didn't need to use the icicle, and it is now out of date.
1520 next.icicle = null;
1521 next.haveState = false;
1522 next.stopped = false;
1523
1524 } else {
1525 // Whoops, need to restart this activity!
1526 if (!next.hasBeenLaunched) {
1527 next.hasBeenLaunched = true;
1528 } else {
1529 if (SHOW_APP_STARTING_PREVIEW) {
1530 mService.mWindowManager.setAppStartingWindow(
1531 next, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001532 mService.compatibilityInfoForPackageLocked(
1533 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001534 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001535 next.labelRes, next.icon, next.windowFlags,
1536 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001537 }
1538 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1539 }
1540 startSpecificActivityLocked(next, true, true);
1541 }
1542
1543 return true;
1544 }
1545
1546 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001547 boolean doResume, boolean keepCurTransition) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001548 final int NH = mHistory.size();
1549
1550 int addPos = -1;
1551
1552 if (!newTask) {
1553 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001554 boolean startIt = true;
1555 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001556 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001557 if (p.finishing) {
1558 continue;
1559 }
1560 if (p.task == r.task) {
1561 // Here it is! Now, if this is not yet visible to the
1562 // user, then just add it without starting; it will
1563 // get started when the user navigates back to it.
1564 addPos = i+1;
1565 if (!startIt) {
1566 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001567 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001568 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1569 r.info.screenOrientation, r.fullscreen);
1570 if (VALIDATE_TOKENS) {
1571 mService.mWindowManager.validateAppTokens(mHistory);
1572 }
1573 return;
1574 }
1575 break;
1576 }
1577 if (p.fullscreen) {
1578 startIt = false;
1579 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001580 }
1581 }
1582
1583 // Place a new activity at top of stack, so it is next to interact
1584 // with the user.
1585 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001586 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001587 }
1588
1589 // If we are not placing the new activity frontmost, we do not want
1590 // to deliver the onUserLeaving callback to the actual frontmost
1591 // activity
1592 if (addPos < NH) {
1593 mUserLeaving = false;
1594 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1595 }
1596
1597 // Slot the activity into the history stack and proceed
1598 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001599 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001600 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001601 if (NH > 0) {
1602 // We want to show the starting preview window if we are
1603 // switching to a new task, or the next activity's process is
1604 // not currently running.
1605 boolean showStartingIcon = newTask;
1606 ProcessRecord proc = r.app;
1607 if (proc == null) {
1608 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1609 }
1610 if (proc == null || proc.thread == null) {
1611 showStartingIcon = true;
1612 }
1613 if (DEBUG_TRANSITION) Slog.v(TAG,
1614 "Prepare open transition: starting " + r);
1615 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001616 mService.mWindowManager.prepareAppTransition(
1617 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001618 mNoAnimActivities.add(r);
1619 } else if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
1620 mService.mWindowManager.prepareAppTransition(
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001621 WindowManagerPolicy.TRANSIT_TASK_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622 mNoAnimActivities.remove(r);
1623 } else {
1624 mService.mWindowManager.prepareAppTransition(newTask
1625 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001626 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001627 mNoAnimActivities.remove(r);
1628 }
1629 mService.mWindowManager.addAppToken(
1630 addPos, r, r.task.taskId, r.info.screenOrientation, r.fullscreen);
1631 boolean doShow = true;
1632 if (newTask) {
1633 // Even though this activity is starting fresh, we still need
1634 // to reset it to make sure we apply affinities to move any
1635 // existing activities from other tasks in to it.
1636 // If the caller has requested that the target task be
1637 // reset, then do so.
1638 if ((r.intent.getFlags()
1639 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1640 resetTaskIfNeededLocked(r, r);
1641 doShow = topRunningNonDelayedActivityLocked(null) == r;
1642 }
1643 }
1644 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1645 // Figure out if we are transitioning from another activity that is
1646 // "has the same starting icon" as the next one. This allows the
1647 // window manager to keep the previous window it had previously
1648 // created, if it still had one.
1649 ActivityRecord prev = mResumedActivity;
1650 if (prev != null) {
1651 // We don't want to reuse the previous starting preview if:
1652 // (1) The current activity is in a different task.
1653 if (prev.task != r.task) prev = null;
1654 // (2) The current activity is already displayed.
1655 else if (prev.nowVisible) prev = null;
1656 }
1657 mService.mWindowManager.setAppStartingWindow(
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001658 r, r.packageName, r.theme,
1659 mService.compatibilityInfoForPackageLocked(
1660 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001661 r.labelRes, r.icon, r.windowFlags, prev, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001662 }
1663 } else {
1664 // If this is the first activity, don't do any fancy animations,
1665 // because there is nothing for it to animate on top of.
1666 mService.mWindowManager.addAppToken(addPos, r, r.task.taskId,
1667 r.info.screenOrientation, r.fullscreen);
1668 }
1669 if (VALIDATE_TOKENS) {
1670 mService.mWindowManager.validateAppTokens(mHistory);
1671 }
1672
1673 if (doResume) {
1674 resumeTopActivityLocked(null);
1675 }
1676 }
1677
1678 /**
1679 * Perform a reset of the given task, if needed as part of launching it.
1680 * Returns the new HistoryRecord at the top of the task.
1681 */
1682 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1683 ActivityRecord newActivity) {
1684 boolean forceReset = (newActivity.info.flags
1685 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001686 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1687 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001688 if ((newActivity.info.flags
1689 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1690 forceReset = true;
1691 }
1692 }
1693
1694 final TaskRecord task = taskTop.task;
1695
1696 // We are going to move through the history list so that we can look
1697 // at each activity 'target' with 'below' either the interesting
1698 // activity immediately below it in the stack or null.
1699 ActivityRecord target = null;
1700 int targetI = 0;
1701 int taskTopI = -1;
1702 int replyChainEnd = -1;
1703 int lastReparentPos = -1;
1704 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001705 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001706
1707 if (below != null && below.finishing) {
1708 continue;
1709 }
1710 if (target == null) {
1711 target = below;
1712 targetI = i;
1713 // If we were in the middle of a reply chain before this
1714 // task, it doesn't appear like the root of the chain wants
1715 // anything interesting, so drop it.
1716 replyChainEnd = -1;
1717 continue;
1718 }
1719
1720 final int flags = target.info.flags;
1721
1722 final boolean finishOnTaskLaunch =
1723 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1724 final boolean allowTaskReparenting =
1725 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1726
1727 if (target.task == task) {
1728 // We are inside of the task being reset... we'll either
1729 // finish this activity, push it out for another task,
1730 // or leave it as-is. We only do this
1731 // for activities that are not the root of the task (since
1732 // if we finish the root, we may no longer have the task!).
1733 if (taskTopI < 0) {
1734 taskTopI = targetI;
1735 }
1736 if (below != null && below.task == task) {
1737 final boolean clearWhenTaskReset =
1738 (target.intent.getFlags()
1739 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1740 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1741 // If this activity is sending a reply to a previous
1742 // activity, we can't do anything with it now until
1743 // we reach the start of the reply chain.
1744 // XXX note that we are assuming the result is always
1745 // to the previous activity, which is almost always
1746 // the case but we really shouldn't count on.
1747 if (replyChainEnd < 0) {
1748 replyChainEnd = targetI;
1749 }
1750 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1751 && target.taskAffinity != null
1752 && !target.taskAffinity.equals(task.affinity)) {
1753 // If this activity has an affinity for another
1754 // task, then we need to move it out of here. We will
1755 // move it as far out of the way as possible, to the
1756 // bottom of the activity stack. This also keeps it
1757 // correctly ordered with any activities we previously
1758 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001759 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001760 if (target.taskAffinity != null
1761 && target.taskAffinity.equals(p.task.affinity)) {
1762 // If the activity currently at the bottom has the
1763 // same task affinity as the one we are moving,
1764 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001765 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001766 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1767 + " out to bottom task " + p.task);
1768 } else {
1769 mService.mCurTask++;
1770 if (mService.mCurTask <= 0) {
1771 mService.mCurTask = 1;
1772 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001773 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
1774 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001775 target.task.affinityIntent = target.intent;
1776 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
1777 + " out to new task " + target.task);
1778 }
1779 mService.mWindowManager.setAppGroupId(target, task.taskId);
1780 if (replyChainEnd < 0) {
1781 replyChainEnd = targetI;
1782 }
1783 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001784 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001786 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 if (p.finishing) {
1788 continue;
1789 }
1790 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
1791 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001792 p.setTask(target.task, curThumbHolder, false);
1793 curThumbHolder = p.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001794 mHistory.remove(srcPos);
1795 mHistory.add(dstPos, p);
1796 mService.mWindowManager.moveAppToken(dstPos, p);
1797 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1798 dstPos++;
1799 if (VALIDATE_TOKENS) {
1800 mService.mWindowManager.validateAppTokens(mHistory);
1801 }
1802 i++;
1803 }
1804 if (taskTop == p) {
1805 taskTop = below;
1806 }
1807 if (taskTopI == replyChainEnd) {
1808 taskTopI = -1;
1809 }
1810 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811 } else if (forceReset || finishOnTaskLaunch
1812 || clearWhenTaskReset) {
1813 // If the activity should just be removed -- either
1814 // because it asks for it, or the task should be
1815 // cleared -- then finish it and anything that is
1816 // part of its reply chain.
1817 if (clearWhenTaskReset) {
1818 // In this case, we want to finish this activity
1819 // and everything above it, so be sneaky and pretend
1820 // like these are all in the reply chain.
1821 replyChainEnd = targetI+1;
1822 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001823 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001824 replyChainEnd)).task == task) {
1825 replyChainEnd++;
1826 }
1827 replyChainEnd--;
1828 } else if (replyChainEnd < 0) {
1829 replyChainEnd = targetI;
1830 }
1831 ActivityRecord p = null;
1832 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001833 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001834 if (p.finishing) {
1835 continue;
1836 }
1837 if (finishActivityLocked(p, srcPos,
1838 Activity.RESULT_CANCELED, null, "reset")) {
1839 replyChainEnd--;
1840 srcPos--;
1841 }
1842 }
1843 if (taskTop == p) {
1844 taskTop = below;
1845 }
1846 if (taskTopI == replyChainEnd) {
1847 taskTopI = -1;
1848 }
1849 replyChainEnd = -1;
1850 } else {
1851 // If we were in the middle of a chain, well the
1852 // activity that started it all doesn't want anything
1853 // special, so leave it all as-is.
1854 replyChainEnd = -1;
1855 }
1856 } else {
1857 // Reached the bottom of the task -- any reply chain
1858 // should be left as-is.
1859 replyChainEnd = -1;
1860 }
1861
1862 } else if (target.resultTo != null) {
1863 // If this activity is sending a reply to a previous
1864 // activity, we can't do anything with it now until
1865 // we reach the start of the reply chain.
1866 // XXX note that we are assuming the result is always
1867 // to the previous activity, which is almost always
1868 // the case but we really shouldn't count on.
1869 if (replyChainEnd < 0) {
1870 replyChainEnd = targetI;
1871 }
1872
1873 } else if (taskTopI >= 0 && allowTaskReparenting
1874 && task.affinity != null
1875 && task.affinity.equals(target.taskAffinity)) {
1876 // We are inside of another task... if this activity has
1877 // an affinity for our task, then either remove it if we are
1878 // clearing or move it over to our task. Note that
1879 // we currently punt on the case where we are resetting a
1880 // task that is not at the top but who has activities above
1881 // with an affinity to it... this is really not a normal
1882 // case, and we will need to later pull that task to the front
1883 // and usually at that point we will do the reset and pick
1884 // up those remaining activities. (This only happens if
1885 // someone starts an activity in a new task from an activity
1886 // in a task that is not currently on top.)
1887 if (forceReset || finishOnTaskLaunch) {
1888 if (replyChainEnd < 0) {
1889 replyChainEnd = targetI;
1890 }
1891 ActivityRecord p = null;
1892 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001893 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 if (p.finishing) {
1895 continue;
1896 }
1897 if (finishActivityLocked(p, srcPos,
1898 Activity.RESULT_CANCELED, null, "reset")) {
1899 taskTopI--;
1900 lastReparentPos--;
1901 replyChainEnd--;
1902 srcPos--;
1903 }
1904 }
1905 replyChainEnd = -1;
1906 } else {
1907 if (replyChainEnd < 0) {
1908 replyChainEnd = targetI;
1909 }
1910 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001911 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001912 if (p.finishing) {
1913 continue;
1914 }
1915 if (lastReparentPos < 0) {
1916 lastReparentPos = taskTopI;
1917 taskTop = p;
1918 } else {
1919 lastReparentPos--;
1920 }
1921 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001922 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 mHistory.add(lastReparentPos, p);
1924 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
1925 + " in to resetting task " + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001926 mService.mWindowManager.moveAppToken(lastReparentPos, p);
1927 mService.mWindowManager.setAppGroupId(p, p.task.taskId);
1928 if (VALIDATE_TOKENS) {
1929 mService.mWindowManager.validateAppTokens(mHistory);
1930 }
1931 }
1932 replyChainEnd = -1;
1933
1934 // Now we've moved it in to place... but what if this is
1935 // a singleTop activity and we have put it on top of another
1936 // instance of the same activity? Then we drop the instance
1937 // below so it remains singleTop.
1938 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
1939 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001940 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001941 if (p.finishing) {
1942 continue;
1943 }
1944 if (p.intent.getComponent().equals(target.intent.getComponent())) {
1945 if (finishActivityLocked(p, j,
1946 Activity.RESULT_CANCELED, null, "replace")) {
1947 taskTopI--;
1948 lastReparentPos--;
1949 }
1950 }
1951 }
1952 }
1953 }
1954 }
1955
1956 target = below;
1957 targetI = i;
1958 }
1959
1960 return taskTop;
1961 }
1962
1963 /**
1964 * Perform clear operation as requested by
1965 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
1966 * stack to the given task, then look for
1967 * an instance of that activity in the stack and, if found, finish all
1968 * activities on top of it and return the instance.
1969 *
1970 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001971 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001972 * or null if none was found.
1973 */
1974 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001975 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001976 int i = mHistory.size();
1977
1978 // First find the requested task.
1979 while (i > 0) {
1980 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001981 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001982 if (r.task.taskId == taskId) {
1983 i++;
1984 break;
1985 }
1986 }
1987
1988 // Now clear it.
1989 while (i > 0) {
1990 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001991 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001992 if (r.finishing) {
1993 continue;
1994 }
1995 if (r.task.taskId != taskId) {
1996 return null;
1997 }
1998 if (r.realActivity.equals(newR.realActivity)) {
1999 // Here it is! Now finish everything in front...
2000 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002001 while (i < (mHistory.size()-1)) {
2002 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002003 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002004 if (r.task.taskId != taskId) {
2005 break;
2006 }
2007 if (r.finishing) {
2008 continue;
2009 }
2010 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2011 null, "clear")) {
2012 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002013 }
2014 }
2015
2016 // Finally, if this is a normal launch mode (that is, not
2017 // expecting onNewIntent()), then we will finish the current
2018 // instance of the activity so a new fresh one can be started.
2019 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2020 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2021 if (!ret.finishing) {
2022 int index = indexOfTokenLocked(ret);
2023 if (index >= 0) {
2024 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
2025 null, "clear");
2026 }
2027 return null;
2028 }
2029 }
2030
2031 return ret;
2032 }
2033 }
2034
2035 return null;
2036 }
2037
2038 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002039 * Completely remove all activities associated with an existing
2040 * task starting at a specified index.
2041 */
2042 private final void performClearTaskAtIndexLocked(int taskId, int i) {
2043 while (i < (mHistory.size()-1)) {
2044 ActivityRecord r = mHistory.get(i);
2045 if (r.task.taskId != taskId) {
2046 // Whoops hit the end.
2047 return;
2048 }
2049 if (r.finishing) {
2050 i++;
2051 continue;
2052 }
2053 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
2054 null, "clear")) {
2055 i++;
2056 }
2057 }
2058 }
2059
2060 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002061 * Completely remove all activities associated with an existing task.
2062 */
2063 private final void performClearTaskLocked(int taskId) {
2064 int i = mHistory.size();
2065
2066 // First find the requested task.
2067 while (i > 0) {
2068 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002069 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002070 if (r.task.taskId == taskId) {
2071 i++;
2072 break;
2073 }
2074 }
2075
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002076 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002077 while (i > 0) {
2078 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002079 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002080 if (r.finishing) {
2081 continue;
2082 }
2083 if (r.task.taskId != taskId) {
2084 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002085 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002086 return;
2087 }
2088 }
2089 }
2090
2091 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002092 * Find the activity in the history stack within the given task. Returns
2093 * the index within the history at which it's found, or < 0 if not found.
2094 */
2095 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2096 int i = mHistory.size();
2097 while (i > 0) {
2098 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002099 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002100 if (candidate.task.taskId != task) {
2101 break;
2102 }
2103 if (candidate.realActivity.equals(r.realActivity)) {
2104 return i;
2105 }
2106 }
2107
2108 return -1;
2109 }
2110
2111 /**
2112 * Reorder the history stack so that the activity at the given index is
2113 * brought to the front.
2114 */
2115 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002116 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002118 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002119 mHistory.add(top, newTop);
2120 oldTop.frontOfTask = false;
2121 newTop.frontOfTask = true;
2122 return newTop;
2123 }
2124
2125 final int startActivityLocked(IApplicationThread caller,
2126 Intent intent, String resolvedType,
2127 Uri[] grantedUriPermissions,
2128 int grantedMode, ActivityInfo aInfo, IBinder resultTo,
2129 String resultWho, int requestCode,
2130 int callingPid, int callingUid, boolean onlyIfNeeded,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002131 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002132
2133 int err = START_SUCCESS;
2134
2135 ProcessRecord callerApp = null;
2136 if (caller != null) {
2137 callerApp = mService.getRecordForAppLocked(caller);
2138 if (callerApp != null) {
2139 callingPid = callerApp.pid;
2140 callingUid = callerApp.info.uid;
2141 } else {
2142 Slog.w(TAG, "Unable to find app for caller " + caller
2143 + " (pid=" + callingPid + ") when starting: "
2144 + intent.toString());
2145 err = START_PERMISSION_DENIED;
2146 }
2147 }
2148
2149 if (err == START_SUCCESS) {
2150 Slog.i(TAG, "Starting: " + intent + " from pid "
2151 + (callerApp != null ? callerApp.pid : callingPid));
2152 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002153
2154 ActivityRecord sourceRecord = null;
2155 ActivityRecord resultRecord = null;
2156 if (resultTo != null) {
2157 int index = indexOfTokenLocked(resultTo);
2158 if (DEBUG_RESULTS) Slog.v(
2159 TAG, "Sending result to " + resultTo + " (index " + index + ")");
2160 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002161 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002162 if (requestCode >= 0 && !sourceRecord.finishing) {
2163 resultRecord = sourceRecord;
2164 }
2165 }
2166 }
2167
2168 int launchFlags = intent.getFlags();
2169
2170 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2171 && sourceRecord != null) {
2172 // Transfer the result target from the source activity to the new
2173 // one being started, including any failures.
2174 if (requestCode >= 0) {
2175 return START_FORWARD_AND_REQUEST_CONFLICT;
2176 }
2177 resultRecord = sourceRecord.resultTo;
2178 resultWho = sourceRecord.resultWho;
2179 requestCode = sourceRecord.requestCode;
2180 sourceRecord.resultTo = null;
2181 if (resultRecord != null) {
2182 resultRecord.removeResultsLocked(
2183 sourceRecord, resultWho, requestCode);
2184 }
2185 }
2186
Dianne Hackbornefb58102010-10-14 16:47:34 -07002187 if (err == START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002188 // We couldn't find a class that can handle the given Intent.
2189 // That's the end of that!
2190 err = START_INTENT_NOT_RESOLVED;
2191 }
2192
2193 if (err == START_SUCCESS && aInfo == null) {
2194 // We couldn't find the specific class specified in the Intent.
2195 // Also the end of the line.
2196 err = START_CLASS_NOT_FOUND;
2197 }
2198
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002199 if (err != START_SUCCESS) {
2200 if (resultRecord != null) {
2201 sendActivityResultLocked(-1,
2202 resultRecord, resultWho, requestCode,
2203 Activity.RESULT_CANCELED, null);
2204 }
2205 return err;
2206 }
2207
2208 final int perm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002209 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002210 if (perm != PackageManager.PERMISSION_GRANTED) {
2211 if (resultRecord != null) {
2212 sendActivityResultLocked(-1,
2213 resultRecord, resultWho, requestCode,
2214 Activity.RESULT_CANCELED, null);
2215 }
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002216 String msg;
2217 if (!aInfo.exported) {
2218 msg = "Permission Denial: starting " + intent.toString()
2219 + " from " + callerApp + " (pid=" + callingPid
2220 + ", uid=" + callingUid + ")"
2221 + " not exported from uid " + aInfo.applicationInfo.uid;
2222 } else {
2223 msg = "Permission Denial: starting " + intent.toString()
2224 + " from " + callerApp + " (pid=" + callingPid
2225 + ", uid=" + callingUid + ")"
2226 + " requires " + aInfo.permission;
2227 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002228 Slog.w(TAG, msg);
2229 throw new SecurityException(msg);
2230 }
2231
2232 if (mMainStack) {
2233 if (mService.mController != null) {
2234 boolean abort = false;
2235 try {
2236 // The Intent we give to the watcher has the extra data
2237 // stripped off, since it can contain private information.
2238 Intent watchIntent = intent.cloneFilter();
2239 abort = !mService.mController.activityStarting(watchIntent,
2240 aInfo.applicationInfo.packageName);
2241 } catch (RemoteException e) {
2242 mService.mController = null;
2243 }
2244
2245 if (abort) {
2246 if (resultRecord != null) {
2247 sendActivityResultLocked(-1,
2248 resultRecord, resultWho, requestCode,
2249 Activity.RESULT_CANCELED, null);
2250 }
2251 // We pretend to the caller that it was really started, but
2252 // they will just get a cancel result.
2253 return START_SUCCESS;
2254 }
2255 }
2256 }
2257
2258 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2259 intent, resolvedType, aInfo, mService.mConfiguration,
2260 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002261 if (outActivity != null) {
2262 outActivity[0] = r;
2263 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002264
2265 if (mMainStack) {
2266 if (mResumedActivity == null
2267 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2268 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2269 PendingActivityLaunch pal = new PendingActivityLaunch();
2270 pal.r = r;
2271 pal.sourceRecord = sourceRecord;
2272 pal.grantedUriPermissions = grantedUriPermissions;
2273 pal.grantedMode = grantedMode;
2274 pal.onlyIfNeeded = onlyIfNeeded;
2275 mService.mPendingActivityLaunches.add(pal);
2276 return START_SWITCHES_CANCELED;
2277 }
2278 }
2279
2280 if (mService.mDidAppSwitch) {
2281 // This is the second allowed switch since we stopped switches,
2282 // so now just generally allow switches. Use case: user presses
2283 // home (switches disabled, switch to home, mDidAppSwitch now true);
2284 // user taps a home icon (coming from home so allowed, we hit here
2285 // and now allow anyone to switch again).
2286 mService.mAppSwitchesAllowedTime = 0;
2287 } else {
2288 mService.mDidAppSwitch = true;
2289 }
2290
2291 mService.doPendingActivityLaunchesLocked(false);
2292 }
2293
2294 return startActivityUncheckedLocked(r, sourceRecord,
2295 grantedUriPermissions, grantedMode, onlyIfNeeded, true);
2296 }
2297
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002298 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2299 if ((launchFlags &
2300 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2301 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2302 // Caller wants to appear on home activity, so before starting
2303 // their own activity we will bring home to the front.
2304 moveHomeToFrontLocked();
2305 }
2306 }
2307
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002308 final int startActivityUncheckedLocked(ActivityRecord r,
2309 ActivityRecord sourceRecord, Uri[] grantedUriPermissions,
2310 int grantedMode, boolean onlyIfNeeded, boolean doResume) {
2311 final Intent intent = r.intent;
2312 final int callingUid = r.launchedFromUid;
2313
2314 int launchFlags = intent.getFlags();
2315
2316 // We'll invoke onUserLeaving before onPause only if the launching
2317 // activity did not explicitly state that this is an automated launch.
2318 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2319 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2320 "startActivity() => mUserLeaving=" + mUserLeaving);
2321
2322 // If the caller has asked not to resume at this point, we make note
2323 // of this in the record so that we can skip it when trying to find
2324 // the top running activity.
2325 if (!doResume) {
2326 r.delayedResume = true;
2327 }
2328
2329 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2330 != 0 ? r : null;
2331
2332 // If the onlyIfNeeded flag is set, then we can do this if the activity
2333 // being launched is the same as the one making the call... or, as
2334 // a special case, if we do not know the caller then we count the
2335 // current top activity as the caller.
2336 if (onlyIfNeeded) {
2337 ActivityRecord checkedCaller = sourceRecord;
2338 if (checkedCaller == null) {
2339 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2340 }
2341 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2342 // Caller is not the same as launcher, so always needed.
2343 onlyIfNeeded = false;
2344 }
2345 }
2346
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002347 if (sourceRecord == null) {
2348 // This activity is not being started from another... in this
2349 // case we -always- start a new task.
2350 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2351 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2352 + intent);
2353 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2354 }
2355 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2356 // The original activity who is starting us is running as a single
2357 // instance... this new activity it is starting must go on its
2358 // own task.
2359 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2360 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2361 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2362 // The activity being started is a single instance... it always
2363 // gets launched into its own task.
2364 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2365 }
2366
2367 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2368 // For whatever reason this activity is being launched into a new
2369 // task... yet the caller has requested a result back. Well, that
2370 // is pretty messed up, so instead immediately send back a cancel
2371 // and let the new task continue launched as normal without a
2372 // dependency on its originator.
2373 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2374 sendActivityResultLocked(-1,
2375 r.resultTo, r.resultWho, r.requestCode,
2376 Activity.RESULT_CANCELED, null);
2377 r.resultTo = null;
2378 }
2379
2380 boolean addingToTask = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002381 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002382 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2383 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2384 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2385 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2386 // If bring to front is requested, and no result is requested, and
2387 // we can find a task that was started with this same
2388 // component, then instead of launching bring that one to the front.
2389 if (r.resultTo == null) {
2390 // See if there is a task to bring to the front. If this is
2391 // a SINGLE_INSTANCE activity, there can be one and only one
2392 // instance of it in the history, and it is always in its own
2393 // unique task, so we do a special search.
2394 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2395 ? findTaskLocked(intent, r.info)
2396 : findActivityLocked(intent, r.info);
2397 if (taskTop != null) {
2398 if (taskTop.task.intent == null) {
2399 // This task was started because of movement of
2400 // the activity based on affinity... now that we
2401 // are actually launching it, we can assign the
2402 // base intent.
2403 taskTop.task.setIntent(intent, r.info);
2404 }
2405 // If the target task is not in the front, then we need
2406 // to bring it to the front... except... well, with
2407 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2408 // to have the same behavior as if a new instance was
2409 // being started, which means not bringing it to the front
2410 // if the caller is not itself in the front.
2411 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002412 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002413 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2414 boolean callerAtFront = sourceRecord == null
2415 || curTop.task == sourceRecord.task;
2416 if (callerAtFront) {
2417 // We really do want to push this one into the
2418 // user's face, right now.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002419 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002420 moveTaskToFrontLocked(taskTop.task, r);
2421 }
2422 }
2423 // If the caller has requested that the target task be
2424 // reset, then do so.
2425 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2426 taskTop = resetTaskIfNeededLocked(taskTop, r);
2427 }
2428 if (onlyIfNeeded) {
2429 // We don't need to start a new activity, and
2430 // the client said not to do anything if that
2431 // is the case, so this is it! And for paranoia, make
2432 // sure we have correctly resumed the top activity.
2433 if (doResume) {
2434 resumeTopActivityLocked(null);
2435 }
2436 return START_RETURN_INTENT_TO_CALLER;
2437 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002438 if ((launchFlags &
2439 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2440 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2441 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002442 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002443 // not be too hard...
2444 reuseTask = taskTop.task;
2445 performClearTaskLocked(taskTop.task.taskId);
2446 reuseTask.setIntent(r.intent, r.info);
2447 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002448 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2449 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2450 // In this situation we want to remove all activities
2451 // from the task up to the one being started. In most
2452 // cases this means we are resetting the task to its
2453 // initial state.
2454 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002455 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002456 if (top != null) {
2457 if (top.frontOfTask) {
2458 // Activity aliases may mean we use different
2459 // intents for the top activity, so make sure
2460 // the task now has the identity of the new
2461 // intent.
2462 top.task.setIntent(r.intent, r.info);
2463 }
2464 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002465 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002466 } else {
2467 // A special case: we need to
2468 // start the activity because it is not currently
2469 // running, and the caller has asked to clear the
2470 // current task to have this activity at the top.
2471 addingToTask = true;
2472 // Now pretend like this activity is being started
2473 // by the top of its task, so it is put in the
2474 // right place.
2475 sourceRecord = taskTop;
2476 }
2477 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2478 // In this case the top activity on the task is the
2479 // same as the one being launched, so we take that
2480 // as a request to bring the task to the foreground.
2481 // If the top activity in the task is the root
2482 // activity, deliver this new intent to it if it
2483 // desires.
2484 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2485 && taskTop.realActivity.equals(r.realActivity)) {
2486 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2487 if (taskTop.frontOfTask) {
2488 taskTop.task.setIntent(r.intent, r.info);
2489 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002490 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002491 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2492 // In this case we are launching the root activity
2493 // of the task, but with a different intent. We
2494 // should start a new instance on top.
2495 addingToTask = true;
2496 sourceRecord = taskTop;
2497 }
2498 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2499 // In this case an activity is being launched in to an
2500 // existing task, without resetting that task. This
2501 // is typically the situation of launching an activity
2502 // from a notification or shortcut. We want to place
2503 // the new activity on top of the current task.
2504 addingToTask = true;
2505 sourceRecord = taskTop;
2506 } else if (!taskTop.task.rootWasReset) {
2507 // In this case we are launching in to an existing task
2508 // that has not yet been started from its front door.
2509 // The current task has been brought to the front.
2510 // Ideally, we'd probably like to place this new task
2511 // at the bottom of its stack, but that's a little hard
2512 // to do with the current organization of the code so
2513 // for now we'll just drop it.
2514 taskTop.task.setIntent(r.intent, r.info);
2515 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002516 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002517 // We didn't do anything... but it was needed (a.k.a., client
2518 // don't use that intent!) And for paranoia, make
2519 // sure we have correctly resumed the top activity.
2520 if (doResume) {
2521 resumeTopActivityLocked(null);
2522 }
2523 return START_TASK_TO_FRONT;
2524 }
2525 }
2526 }
2527 }
2528
2529 //String uri = r.intent.toURI();
2530 //Intent intent2 = new Intent(uri);
2531 //Slog.i(TAG, "Given intent: " + r.intent);
2532 //Slog.i(TAG, "URI is: " + uri);
2533 //Slog.i(TAG, "To intent: " + intent2);
2534
2535 if (r.packageName != null) {
2536 // If the activity being launched is the same as the one currently
2537 // at the top, then we need to check if it should only be launched
2538 // once.
2539 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2540 if (top != null && r.resultTo == null) {
2541 if (top.realActivity.equals(r.realActivity)) {
2542 if (top.app != null && top.app.thread != null) {
2543 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2544 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2545 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2546 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2547 // For paranoia, make sure we have correctly
2548 // resumed the top activity.
2549 if (doResume) {
2550 resumeTopActivityLocked(null);
2551 }
2552 if (onlyIfNeeded) {
2553 // We don't need to start a new activity, and
2554 // the client said not to do anything if that
2555 // is the case, so this is it!
2556 return START_RETURN_INTENT_TO_CALLER;
2557 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002558 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002559 return START_DELIVERED_TO_TOP;
2560 }
2561 }
2562 }
2563 }
2564
2565 } else {
2566 if (r.resultTo != null) {
2567 sendActivityResultLocked(-1,
2568 r.resultTo, r.resultWho, r.requestCode,
2569 Activity.RESULT_CANCELED, null);
2570 }
2571 return START_CLASS_NOT_FOUND;
2572 }
2573
2574 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002575 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002576
2577 // Should this be considered a new task?
2578 if (r.resultTo == null && !addingToTask
2579 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002580 if (reuseTask == null) {
2581 // todo: should do better management of integers.
2582 mService.mCurTask++;
2583 if (mService.mCurTask <= 0) {
2584 mService.mCurTask = 1;
2585 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002586 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002587 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2588 + " in new task " + r.task);
2589 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002590 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002591 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002592 newTask = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002593 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002594
2595 } else if (sourceRecord != null) {
2596 if (!addingToTask &&
2597 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2598 // In this case, we are adding the activity to an existing
2599 // task, but the caller has asked to clear that task if the
2600 // activity is already running.
2601 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002602 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002603 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002604 if (top != null) {
2605 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002606 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002607 // For paranoia, make sure we have correctly
2608 // resumed the top activity.
2609 if (doResume) {
2610 resumeTopActivityLocked(null);
2611 }
2612 return START_DELIVERED_TO_TOP;
2613 }
2614 } else if (!addingToTask &&
2615 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2616 // In this case, we are launching an activity in our own task
2617 // that may already be running somewhere in the history, and
2618 // we want to shuffle it to the front of the stack if so.
2619 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2620 if (where >= 0) {
2621 ActivityRecord top = moveActivityToFrontLocked(where);
2622 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002623 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002624 if (doResume) {
2625 resumeTopActivityLocked(null);
2626 }
2627 return START_DELIVERED_TO_TOP;
2628 }
2629 }
2630 // An existing activity is starting this new activity, so we want
2631 // to keep the new one in the same task as the one that is starting
2632 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002633 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002634 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2635 + " in existing task " + r.task);
2636
2637 } else {
2638 // This not being started from an existing activity, and not part
2639 // of a new task... just put it in the top task, though these days
2640 // this case should never happen.
2641 final int N = mHistory.size();
2642 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002643 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002644 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002645 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002646 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002647 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2648 + " in new guessed " + r.task);
2649 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002650
2651 if (grantedUriPermissions != null && callingUid > 0) {
2652 for (int i=0; i<grantedUriPermissions.length; i++) {
2653 mService.grantUriPermissionLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002654 grantedUriPermissions[i], grantedMode, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002655 }
2656 }
2657
2658 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002659 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002660
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 if (newTask) {
2662 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2663 }
2664 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002665 startActivityLocked(r, newTask, doResume, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002666 return START_SUCCESS;
2667 }
2668
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002669 ActivityInfo resolveActivity(Intent intent, String resolvedType, boolean debug) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002670 // Collect information about the target of the Intent.
2671 ActivityInfo aInfo;
2672 try {
2673 ResolveInfo rInfo =
2674 AppGlobals.getPackageManager().resolveIntent(
2675 intent, resolvedType,
2676 PackageManager.MATCH_DEFAULT_ONLY
2677 | ActivityManagerService.STOCK_PM_FLAGS);
2678 aInfo = rInfo != null ? rInfo.activityInfo : null;
2679 } catch (RemoteException e) {
2680 aInfo = null;
2681 }
2682
2683 if (aInfo != null) {
2684 // Store the found target back into the intent, because now that
2685 // we have it we never want to do this again. For example, if the
2686 // user navigates back to this point in the history, we should
2687 // always restart the exact same activity.
2688 intent.setComponent(new ComponentName(
2689 aInfo.applicationInfo.packageName, aInfo.name));
2690
2691 // Don't debug things in the system process
2692 if (debug) {
2693 if (!aInfo.processName.equals("system")) {
2694 mService.setDebugApp(aInfo.processName, true, false);
2695 }
2696 }
2697 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002698 return aInfo;
2699 }
2700
2701 final int startActivityMayWait(IApplicationThread caller, int callingUid,
2702 Intent intent, String resolvedType, Uri[] grantedUriPermissions,
2703 int grantedMode, IBinder resultTo,
2704 String resultWho, int requestCode, boolean onlyIfNeeded,
2705 boolean debug, WaitResult outResult, Configuration config) {
2706 // Refuse possible leaked file descriptors
2707 if (intent != null && intent.hasFileDescriptors()) {
2708 throw new IllegalArgumentException("File descriptors passed in Intent");
2709 }
2710
2711 boolean componentSpecified = intent.getComponent() != null;
2712
2713 // Don't modify the client's object!
2714 intent = new Intent(intent);
2715
2716 // Collect information about the target of the Intent.
2717 ActivityInfo aInfo = resolveActivity(intent, resolvedType, debug);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002718
2719 synchronized (mService) {
2720 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002721 if (callingUid >= 0) {
2722 callingPid = -1;
2723 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002724 callingPid = Binder.getCallingPid();
2725 callingUid = Binder.getCallingUid();
2726 } else {
2727 callingPid = callingUid = -1;
2728 }
2729
2730 mConfigWillChange = config != null
2731 && mService.mConfiguration.diff(config) != 0;
2732 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2733 "Starting activity when config will change = " + mConfigWillChange);
2734
2735 final long origId = Binder.clearCallingIdentity();
2736
2737 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07002738 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002739 // This may be a heavy-weight process! Check to see if we already
2740 // have another, different heavy-weight process running.
2741 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
2742 if (mService.mHeavyWeightProcess != null &&
2743 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
2744 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
2745 int realCallingPid = callingPid;
2746 int realCallingUid = callingUid;
2747 if (caller != null) {
2748 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
2749 if (callerApp != null) {
2750 realCallingPid = callerApp.pid;
2751 realCallingUid = callerApp.info.uid;
2752 } else {
2753 Slog.w(TAG, "Unable to find app for caller " + caller
2754 + " (pid=" + realCallingPid + ") when starting: "
2755 + intent.toString());
2756 return START_PERMISSION_DENIED;
2757 }
2758 }
2759
2760 IIntentSender target = mService.getIntentSenderLocked(
2761 IActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002762 realCallingUid, null, null, 0, new Intent[] { intent },
2763 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 | PendingIntent.FLAG_ONE_SHOT);
2765
2766 Intent newIntent = new Intent();
2767 if (requestCode >= 0) {
2768 // Caller is requesting a result.
2769 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
2770 }
2771 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
2772 new IntentSender(target));
2773 if (mService.mHeavyWeightProcess.activities.size() > 0) {
2774 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
2775 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
2776 hist.packageName);
2777 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
2778 hist.task.taskId);
2779 }
2780 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
2781 aInfo.packageName);
2782 newIntent.setFlags(intent.getFlags());
2783 newIntent.setClassName("android",
2784 HeavyWeightSwitcherActivity.class.getName());
2785 intent = newIntent;
2786 resolvedType = null;
2787 caller = null;
2788 callingUid = Binder.getCallingUid();
2789 callingPid = Binder.getCallingPid();
2790 componentSpecified = true;
2791 try {
2792 ResolveInfo rInfo =
2793 AppGlobals.getPackageManager().resolveIntent(
2794 intent, null,
2795 PackageManager.MATCH_DEFAULT_ONLY
2796 | ActivityManagerService.STOCK_PM_FLAGS);
2797 aInfo = rInfo != null ? rInfo.activityInfo : null;
2798 } catch (RemoteException e) {
2799 aInfo = null;
2800 }
2801 }
2802 }
2803 }
2804
2805 int res = startActivityLocked(caller, intent, resolvedType,
2806 grantedUriPermissions, grantedMode, aInfo,
2807 resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002808 onlyIfNeeded, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002809
2810 if (mConfigWillChange && mMainStack) {
2811 // If the caller also wants to switch to a new configuration,
2812 // do so now. This allows a clean switch, as we are waiting
2813 // for the current activity to pause (so we will not destroy
2814 // it), and have not yet started the next activity.
2815 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
2816 "updateConfiguration()");
2817 mConfigWillChange = false;
2818 if (DEBUG_CONFIGURATION) Slog.v(TAG,
2819 "Updating to new configuration after starting activity.");
2820 mService.updateConfigurationLocked(config, null);
2821 }
2822
2823 Binder.restoreCallingIdentity(origId);
2824
2825 if (outResult != null) {
2826 outResult.result = res;
2827 if (res == IActivityManager.START_SUCCESS) {
2828 mWaitingActivityLaunched.add(outResult);
2829 do {
2830 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002831 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 } catch (InterruptedException e) {
2833 }
2834 } while (!outResult.timeout && outResult.who == null);
2835 } else if (res == IActivityManager.START_TASK_TO_FRONT) {
2836 ActivityRecord r = this.topRunningActivityLocked(null);
2837 if (r.nowVisible) {
2838 outResult.timeout = false;
2839 outResult.who = new ComponentName(r.info.packageName, r.info.name);
2840 outResult.totalTime = 0;
2841 outResult.thisTime = 0;
2842 } else {
2843 outResult.thisTime = SystemClock.uptimeMillis();
2844 mWaitingActivityVisible.add(outResult);
2845 do {
2846 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07002847 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002848 } catch (InterruptedException e) {
2849 }
2850 } while (!outResult.timeout && outResult.who == null);
2851 }
2852 }
2853 }
2854
2855 return res;
2856 }
2857 }
2858
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002859 final int startActivities(IApplicationThread caller, int callingUid,
2860 Intent[] intents, String[] resolvedTypes, IBinder resultTo) {
2861 if (intents == null) {
2862 throw new NullPointerException("intents is null");
2863 }
2864 if (resolvedTypes == null) {
2865 throw new NullPointerException("resolvedTypes is null");
2866 }
2867 if (intents.length != resolvedTypes.length) {
2868 throw new IllegalArgumentException("intents are length different than resolvedTypes");
2869 }
2870
2871 ActivityRecord[] outActivity = new ActivityRecord[1];
2872
2873 int callingPid;
2874 if (callingUid >= 0) {
2875 callingPid = -1;
2876 } else if (caller == null) {
2877 callingPid = Binder.getCallingPid();
2878 callingUid = Binder.getCallingUid();
2879 } else {
2880 callingPid = callingUid = -1;
2881 }
2882 final long origId = Binder.clearCallingIdentity();
2883 try {
2884 synchronized (mService) {
2885
2886 for (int i=0; i<intents.length; i++) {
2887 Intent intent = intents[i];
2888 if (intent == null) {
2889 continue;
2890 }
2891
2892 // Refuse possible leaked file descriptors
2893 if (intent != null && intent.hasFileDescriptors()) {
2894 throw new IllegalArgumentException("File descriptors passed in Intent");
2895 }
2896
2897 boolean componentSpecified = intent.getComponent() != null;
2898
2899 // Don't modify the client's object!
2900 intent = new Intent(intent);
2901
2902 // Collect information about the target of the Intent.
2903 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i], false);
2904
2905 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
2906 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
2907 throw new IllegalArgumentException(
2908 "FLAG_CANT_SAVE_STATE not supported here");
2909 }
2910
2911 int res = startActivityLocked(caller, intent, resolvedTypes[i],
2912 null, 0, aInfo, resultTo, null, -1, callingPid, callingUid,
2913 false, componentSpecified, outActivity);
2914 if (res < 0) {
2915 return res;
2916 }
2917
2918 resultTo = outActivity[0];
2919 }
2920 }
2921 } finally {
2922 Binder.restoreCallingIdentity(origId);
2923 }
2924
2925 return IActivityManager.START_SUCCESS;
2926 }
2927
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002928 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
2929 long thisTime, long totalTime) {
2930 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
2931 WaitResult w = mWaitingActivityLaunched.get(i);
2932 w.timeout = timeout;
2933 if (r != null) {
2934 w.who = new ComponentName(r.info.packageName, r.info.name);
2935 }
2936 w.thisTime = thisTime;
2937 w.totalTime = totalTime;
2938 }
2939 mService.notifyAll();
2940 }
2941
2942 void reportActivityVisibleLocked(ActivityRecord r) {
2943 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
2944 WaitResult w = mWaitingActivityVisible.get(i);
2945 w.timeout = false;
2946 if (r != null) {
2947 w.who = new ComponentName(r.info.packageName, r.info.name);
2948 }
2949 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
2950 w.thisTime = w.totalTime;
2951 }
2952 mService.notifyAll();
2953 }
2954
2955 void sendActivityResultLocked(int callingUid, ActivityRecord r,
2956 String resultWho, int requestCode, int resultCode, Intent data) {
2957
2958 if (callingUid > 0) {
2959 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002960 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002961 }
2962
2963 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
2964 + " : who=" + resultWho + " req=" + requestCode
2965 + " res=" + resultCode + " data=" + data);
2966 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
2967 try {
2968 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
2969 list.add(new ResultInfo(resultWho, requestCode,
2970 resultCode, data));
2971 r.app.thread.scheduleSendResult(r, list);
2972 return;
2973 } catch (Exception e) {
2974 Slog.w(TAG, "Exception thrown sending result to " + r, e);
2975 }
2976 }
2977
2978 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
2979 }
2980
2981 private final void stopActivityLocked(ActivityRecord r) {
2982 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
2983 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
2984 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
2985 if (!r.finishing) {
2986 requestFinishActivityLocked(r, Activity.RESULT_CANCELED, null,
2987 "no-history");
2988 }
2989 } else if (r.app != null && r.app.thread != null) {
2990 if (mMainStack) {
2991 if (mService.mFocusedActivity == r) {
2992 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
2993 }
2994 }
2995 r.resumeKeyDispatchingLocked();
2996 try {
2997 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07002998 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
2999 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003000 r.state = ActivityState.STOPPING;
3001 if (DEBUG_VISBILITY) Slog.v(
3002 TAG, "Stopping visible=" + r.visible + " for " + r);
3003 if (!r.visible) {
3004 mService.mWindowManager.setAppVisibility(r, false);
3005 }
3006 r.app.thread.scheduleStopActivity(r, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003007 if (mService.isSleeping()) {
3008 r.setSleeping(true);
3009 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003010 } catch (Exception e) {
3011 // Maybe just ignore exceptions here... if the process
3012 // has crashed, our death notification will clean things
3013 // up.
3014 Slog.w(TAG, "Exception thrown during pause", e);
3015 // Just in case, assume it to be stopped.
3016 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003017 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003018 r.state = ActivityState.STOPPED;
3019 if (r.configDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003020 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003021 }
3022 }
3023 }
3024 }
3025
3026 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3027 boolean remove) {
3028 int N = mStoppingActivities.size();
3029 if (N <= 0) return null;
3030
3031 ArrayList<ActivityRecord> stops = null;
3032
3033 final boolean nowVisible = mResumedActivity != null
3034 && mResumedActivity.nowVisible
3035 && !mResumedActivity.waitingVisible;
3036 for (int i=0; i<N; i++) {
3037 ActivityRecord s = mStoppingActivities.get(i);
3038 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3039 + nowVisible + " waitingVisible=" + s.waitingVisible
3040 + " finishing=" + s.finishing);
3041 if (s.waitingVisible && nowVisible) {
3042 mWaitingVisibleActivities.remove(s);
3043 s.waitingVisible = false;
3044 if (s.finishing) {
3045 // If this activity is finishing, it is sitting on top of
3046 // everyone else but we now know it is no longer needed...
3047 // so get rid of it. Otherwise, we need to go through the
3048 // normal flow and hide it once we determine that it is
3049 // hidden by the activities in front of it.
3050 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
3051 mService.mWindowManager.setAppVisibility(s, false);
3052 }
3053 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003054 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003055 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3056 if (stops == null) {
3057 stops = new ArrayList<ActivityRecord>();
3058 }
3059 stops.add(s);
3060 mStoppingActivities.remove(i);
3061 N--;
3062 i--;
3063 }
3064 }
3065
3066 return stops;
3067 }
3068
3069 final void activityIdleInternal(IBinder token, boolean fromTimeout,
3070 Configuration config) {
3071 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3072
3073 ArrayList<ActivityRecord> stops = null;
3074 ArrayList<ActivityRecord> finishes = null;
3075 ArrayList<ActivityRecord> thumbnails = null;
3076 int NS = 0;
3077 int NF = 0;
3078 int NT = 0;
3079 IApplicationThread sendThumbnail = null;
3080 boolean booting = false;
3081 boolean enableScreen = false;
3082
3083 synchronized (mService) {
3084 if (token != null) {
3085 mHandler.removeMessages(IDLE_TIMEOUT_MSG, token);
3086 }
3087
3088 // Get the activity record.
3089 int index = indexOfTokenLocked(token);
3090 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003091 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003092
3093 if (fromTimeout) {
3094 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3095 }
3096
3097 // This is a hack to semi-deal with a race condition
3098 // in the client where it can be constructed with a
3099 // newer configuration from when we asked it to launch.
3100 // We'll update with whatever configuration it now says
3101 // it used to launch.
3102 if (config != null) {
3103 r.configuration = config;
3104 }
3105
3106 // No longer need to keep the device awake.
3107 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3108 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3109 mLaunchingActivity.release();
3110 }
3111
3112 // We are now idle. If someone is waiting for a thumbnail from
3113 // us, we can now deliver.
3114 r.idle = true;
3115 mService.scheduleAppGcsLocked();
3116 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3117 sendThumbnail = r.app.thread;
3118 r.thumbnailNeeded = false;
3119 }
3120
3121 // If this activity is fullscreen, set up to hide those under it.
3122
3123 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3124 ensureActivitiesVisibleLocked(null, 0);
3125
3126 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3127 if (mMainStack) {
3128 if (!mService.mBooted && !fromTimeout) {
3129 mService.mBooted = true;
3130 enableScreen = true;
3131 }
3132 }
3133
3134 } else if (fromTimeout) {
3135 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3136 }
3137
3138 // Atomically retrieve all of the other things to do.
3139 stops = processStoppingActivitiesLocked(true);
3140 NS = stops != null ? stops.size() : 0;
3141 if ((NF=mFinishingActivities.size()) > 0) {
3142 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3143 mFinishingActivities.clear();
3144 }
3145 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3146 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3147 mService.mCancelledThumbnails.clear();
3148 }
3149
3150 if (mMainStack) {
3151 booting = mService.mBooting;
3152 mService.mBooting = false;
3153 }
3154 }
3155
3156 int i;
3157
3158 // Send thumbnail if requested.
3159 if (sendThumbnail != null) {
3160 try {
3161 sendThumbnail.requestThumbnail(token);
3162 } catch (Exception e) {
3163 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3164 mService.sendPendingThumbnail(null, token, null, null, true);
3165 }
3166 }
3167
3168 // Stop any activities that are scheduled to do so but have been
3169 // waiting for the next one to start.
3170 for (i=0; i<NS; i++) {
3171 ActivityRecord r = (ActivityRecord)stops.get(i);
3172 synchronized (mService) {
3173 if (r.finishing) {
3174 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY);
3175 } else {
3176 stopActivityLocked(r);
3177 }
3178 }
3179 }
3180
3181 // Finish any activities that are scheduled to do so but have been
3182 // waiting for the next one to start.
3183 for (i=0; i<NF; i++) {
3184 ActivityRecord r = (ActivityRecord)finishes.get(i);
3185 synchronized (mService) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003186 destroyActivityLocked(r, true, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003187 }
3188 }
3189
3190 // Report back to any thumbnail receivers.
3191 for (i=0; i<NT; i++) {
3192 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3193 mService.sendPendingThumbnail(r, null, null, null, true);
3194 }
3195
3196 if (booting) {
3197 mService.finishBooting();
3198 }
3199
3200 mService.trimApplications();
3201 //dump();
3202 //mWindowManager.dump();
3203
3204 if (enableScreen) {
3205 mService.enableScreenAfterBoot();
3206 }
3207 }
3208
3209 /**
3210 * @return Returns true if the activity is being finished, false if for
3211 * some reason it is being left as-is.
3212 */
3213 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
3214 Intent resultData, String reason) {
3215 if (DEBUG_RESULTS) Slog.v(
3216 TAG, "Finishing activity: token=" + token
3217 + ", result=" + resultCode + ", data=" + resultData);
3218
3219 int index = indexOfTokenLocked(token);
3220 if (index < 0) {
3221 return false;
3222 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003223 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003224
3225 // Is this the last activity left?
3226 boolean lastActivity = true;
3227 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003228 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229 if (!p.finishing && p != r) {
3230 lastActivity = false;
3231 break;
3232 }
3233 }
3234
3235 // If this is the last activity, but it is the home activity, then
3236 // just don't finish it.
3237 if (lastActivity) {
3238 if (r.intent.hasCategory(Intent.CATEGORY_HOME)) {
3239 return false;
3240 }
3241 }
3242
3243 finishActivityLocked(r, index, resultCode, resultData, reason);
3244 return true;
3245 }
3246
3247 /**
3248 * @return Returns true if this activity has been removed from the history
3249 * list, or false if it is still in the list and will be removed later.
3250 */
3251 final boolean finishActivityLocked(ActivityRecord r, int index,
3252 int resultCode, Intent resultData, String reason) {
3253 if (r.finishing) {
3254 Slog.w(TAG, "Duplicate finish request for " + r);
3255 return false;
3256 }
3257
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003258 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003259 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3260 System.identityHashCode(r),
3261 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003262 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003263 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003264 if (next.task == r.task) {
3265 if (r.frontOfTask) {
3266 // The next activity is now the front of the task.
3267 next.frontOfTask = true;
3268 }
3269 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3270 // If the caller asked that this activity (and all above it)
3271 // be cleared when the task is reset, don't lose that information,
3272 // but propagate it up to the next activity.
3273 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3274 }
3275 }
3276 }
3277
3278 r.pauseKeyDispatchingLocked();
3279 if (mMainStack) {
3280 if (mService.mFocusedActivity == r) {
3281 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3282 }
3283 }
3284
3285 // send the result
3286 ActivityRecord resultTo = r.resultTo;
3287 if (resultTo != null) {
3288 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3289 + " who=" + r.resultWho + " req=" + r.requestCode
3290 + " res=" + resultCode + " data=" + resultData);
3291 if (r.info.applicationInfo.uid > 0) {
3292 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
Dianne Hackborna1c69e02010-09-01 22:55:02 -07003293 resultTo.packageName, resultData,
3294 resultTo.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003295 }
3296 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3297 resultData);
3298 r.resultTo = null;
3299 }
3300 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3301
3302 // Make sure this HistoryRecord is not holding on to other resources,
3303 // because clients have remote IPC references to this object so we
3304 // can't assume that will go away and want to avoid circular IPC refs.
3305 r.results = null;
3306 r.pendingResults = null;
3307 r.newIntents = null;
3308 r.icicle = null;
3309
3310 if (mService.mPendingThumbnails.size() > 0) {
3311 // There are clients waiting to receive thumbnails so, in case
3312 // this is an activity that someone is waiting for, add it
3313 // to the pending list so we can correctly update the clients.
3314 mService.mCancelledThumbnails.add(r);
3315 }
3316
3317 if (mResumedActivity == r) {
3318 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003319 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003320 if (DEBUG_TRANSITION) Slog.v(TAG,
3321 "Prepare close transition: finishing " + r);
3322 mService.mWindowManager.prepareAppTransition(endTask
3323 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003324 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003325
3326 // Tell window manager to prepare for this one to be removed.
3327 mService.mWindowManager.setAppVisibility(r, false);
3328
3329 if (mPausingActivity == null) {
3330 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3331 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3332 startPausingLocked(false, false);
3333 }
3334
3335 } else if (r.state != ActivityState.PAUSING) {
3336 // If the activity is PAUSING, we will complete the finish once
3337 // it is done pausing; else we can just directly finish it here.
3338 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3339 return finishCurrentActivityLocked(r, index,
3340 FINISH_AFTER_PAUSE) == null;
3341 } else {
3342 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3343 }
3344
3345 return false;
3346 }
3347
3348 private static final int FINISH_IMMEDIATELY = 0;
3349 private static final int FINISH_AFTER_PAUSE = 1;
3350 private static final int FINISH_AFTER_VISIBLE = 2;
3351
3352 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3353 int mode) {
3354 final int index = indexOfTokenLocked(r);
3355 if (index < 0) {
3356 return null;
3357 }
3358
3359 return finishCurrentActivityLocked(r, index, mode);
3360 }
3361
3362 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
3363 int index, int mode) {
3364 // First things first: if this activity is currently visible,
3365 // and the resumed activity is not yet visible, then hold off on
3366 // finishing until the resumed one becomes visible.
3367 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3368 if (!mStoppingActivities.contains(r)) {
3369 mStoppingActivities.add(r);
3370 if (mStoppingActivities.size() > 3) {
3371 // If we already have a few activities waiting to stop,
3372 // then give up on things going idle and start clearing
3373 // them out.
3374 Message msg = Message.obtain();
3375 msg.what = IDLE_NOW_MSG;
3376 mHandler.sendMessage(msg);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003377 } else {
3378 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003379 }
3380 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003381 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3382 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003383 r.state = ActivityState.STOPPING;
3384 mService.updateOomAdjLocked();
3385 return r;
3386 }
3387
3388 // make sure the record is cleaned out of other places.
3389 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003390 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003391 mWaitingVisibleActivities.remove(r);
3392 if (mResumedActivity == r) {
3393 mResumedActivity = null;
3394 }
3395 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003396 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003397 r.state = ActivityState.FINISHING;
3398
3399 if (mode == FINISH_IMMEDIATELY
3400 || prevState == ActivityState.STOPPED
3401 || prevState == ActivityState.INITIALIZING) {
3402 // If this activity is already stopped, we can just finish
3403 // it right now.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003404 return destroyActivityLocked(r, true, true) ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003405 } else {
3406 // Need to go through the full pause cycle to get this
3407 // activity into the stopped state and then finish it.
3408 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3409 mFinishingActivities.add(r);
3410 resumeTopActivityLocked(null);
3411 }
3412 return r;
3413 }
3414
3415 /**
3416 * Perform the common clean-up of an activity record. This is called both
3417 * as part of destroyActivityLocked() (when destroying the client-side
3418 * representation) and cleaning things up as a result of its hosting
3419 * processing going away, in which case there is no remaining client-side
3420 * state to destroy so only the cleanup here is needed.
3421 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003422 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3423 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003424 if (mResumedActivity == r) {
3425 mResumedActivity = null;
3426 }
3427 if (mService.mFocusedActivity == r) {
3428 mService.mFocusedActivity = null;
3429 }
3430
3431 r.configDestroy = false;
3432 r.frozenBeforeDestroy = false;
3433
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003434 if (setState) {
3435 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3436 r.state = ActivityState.DESTROYED;
3437 }
3438
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003439 // Make sure this record is no longer in the pending finishes list.
3440 // This could happen, for example, if we are trimming activities
3441 // down to the max limit while they are still waiting to finish.
3442 mFinishingActivities.remove(r);
3443 mWaitingVisibleActivities.remove(r);
3444
3445 // Remove any pending results.
3446 if (r.finishing && r.pendingResults != null) {
3447 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3448 PendingIntentRecord rec = apr.get();
3449 if (rec != null) {
3450 mService.cancelIntentSenderLocked(rec, false);
3451 }
3452 }
3453 r.pendingResults = null;
3454 }
3455
3456 if (cleanServices) {
3457 cleanUpActivityServicesLocked(r);
3458 }
3459
3460 if (mService.mPendingThumbnails.size() > 0) {
3461 // There are clients waiting to receive thumbnails so, in case
3462 // this is an activity that someone is waiting for, add it
3463 // to the pending list so we can correctly update the clients.
3464 mService.mCancelledThumbnails.add(r);
3465 }
3466
3467 // Get rid of any pending idle timeouts.
3468 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
3469 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003470 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003471 }
3472
3473 private final void removeActivityFromHistoryLocked(ActivityRecord r) {
3474 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003475 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003476 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003477 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003478 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3479 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003480 r.state = ActivityState.DESTROYED;
3481 mService.mWindowManager.removeAppToken(r);
3482 if (VALIDATE_TOKENS) {
3483 mService.mWindowManager.validateAppTokens(mHistory);
3484 }
3485 cleanUpActivityServicesLocked(r);
3486 r.removeUriPermissionsLocked();
3487 }
3488 }
3489
3490 /**
3491 * Perform clean-up of service connections in an activity record.
3492 */
3493 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3494 // Throw away any services that have been bound by this activity.
3495 if (r.connections != null) {
3496 Iterator<ConnectionRecord> it = r.connections.iterator();
3497 while (it.hasNext()) {
3498 ConnectionRecord c = it.next();
3499 mService.removeConnectionLocked(c, null, r);
3500 }
3501 r.connections = null;
3502 }
3503 }
3504
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003505 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj) {
3506 for (int i=mHistory.size()-1; i>=0; i--) {
3507 ActivityRecord r = mHistory.get(i);
3508 if (owner != null && r.app != owner) {
3509 continue;
3510 }
3511 // We can destroy this one if we have its icicle saved and
3512 // it is not in the process of pausing/stopping/finishing.
3513 if (r.app != null && r.haveState && !r.visible && r.stopped && !r.finishing
3514 && r.state != ActivityState.DESTROYING
3515 && r.state != ActivityState.DESTROYED) {
3516 destroyActivityLocked(r, true, oomAdj);
3517 }
3518 }
3519 }
3520
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003521 /**
3522 * Destroy the current CLIENT SIDE instance of an activity. This may be
3523 * called both when actually finishing an activity, or when performing
3524 * a configuration switch where we destroy the current client-side object
3525 * but then create a new client-side object for this same HistoryRecord.
3526 */
3527 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003528 boolean removeFromApp, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003529 if (DEBUG_SWITCH) Slog.v(
3530 TAG, "Removing activity: token=" + r
3531 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3532 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3533 System.identityHashCode(r),
3534 r.task.taskId, r.shortComponentName);
3535
3536 boolean removedFromHistory = false;
3537
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003538 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003539
3540 final boolean hadApp = r.app != null;
3541
3542 if (hadApp) {
3543 if (removeFromApp) {
3544 int idx = r.app.activities.indexOf(r);
3545 if (idx >= 0) {
3546 r.app.activities.remove(idx);
3547 }
3548 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
3549 mService.mHeavyWeightProcess = null;
3550 mService.mHandler.sendEmptyMessage(
3551 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
3552 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003553 if (r.app.activities.size() == 0) {
3554 // No longer have activities, so update location in
3555 // LRU list.
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003556 mService.updateLruProcessLocked(r.app, oomAdj, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003557 }
3558 }
3559
3560 boolean skipDestroy = false;
3561
3562 try {
3563 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
3564 r.app.thread.scheduleDestroyActivity(r, r.finishing,
3565 r.configChangeFlags);
3566 } catch (Exception e) {
3567 // We can just ignore exceptions here... if the process
3568 // has crashed, our death notification will clean things
3569 // up.
3570 //Slog.w(TAG, "Exception thrown during finish", e);
3571 if (r.finishing) {
3572 removeActivityFromHistoryLocked(r);
3573 removedFromHistory = true;
3574 skipDestroy = true;
3575 }
3576 }
3577
3578 r.app = null;
3579 r.nowVisible = false;
3580
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003581 // If the activity is finishing, we need to wait on removing it
3582 // from the list to give it a chance to do its cleanup. During
3583 // that time it may make calls back with its token so we need to
3584 // be able to find it on the list and so we don't want to remove
3585 // it from the list yet. Otherwise, we can just immediately put
3586 // it in the destroyed state since we are not removing it from the
3587 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003588 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003589 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
3590 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003591 r.state = ActivityState.DESTROYING;
3592 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
3593 msg.obj = r;
3594 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
3595 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003596 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3597 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 r.state = ActivityState.DESTROYED;
3599 }
3600 } else {
3601 // remove this record from the history.
3602 if (r.finishing) {
3603 removeActivityFromHistoryLocked(r);
3604 removedFromHistory = true;
3605 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003606 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3607 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003608 r.state = ActivityState.DESTROYED;
3609 }
3610 }
3611
3612 r.configChangeFlags = 0;
3613
3614 if (!mLRUActivities.remove(r) && hadApp) {
3615 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
3616 }
3617
3618 return removedFromHistory;
3619 }
3620
3621 final void activityDestroyed(IBinder token) {
3622 synchronized (mService) {
3623 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, token);
3624
3625 int index = indexOfTokenLocked(token);
3626 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003627 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003628 if (r.state == ActivityState.DESTROYING) {
3629 final long origId = Binder.clearCallingIdentity();
3630 removeActivityFromHistoryLocked(r);
3631 Binder.restoreCallingIdentity(origId);
3632 }
3633 }
3634 }
3635 }
3636
3637 private static void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
3638 int i = list.size();
3639 if (localLOGV) Slog.v(
3640 TAG, "Removing app " + app + " from list " + list
3641 + " with " + i + " entries");
3642 while (i > 0) {
3643 i--;
3644 ActivityRecord r = (ActivityRecord)list.get(i);
3645 if (localLOGV) Slog.v(
3646 TAG, "Record #" + i + " " + r + ": app=" + r.app);
3647 if (r.app == app) {
3648 if (localLOGV) Slog.v(TAG, "Removing this entry!");
3649 list.remove(i);
3650 }
3651 }
3652 }
3653
3654 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
3655 removeHistoryRecordsForAppLocked(mLRUActivities, app);
3656 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003657 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003658 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
3659 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
3660 }
3661
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003662 /**
3663 * Move the current home activity's task (if one exists) to the front
3664 * of the stack.
3665 */
3666 final void moveHomeToFrontLocked() {
3667 TaskRecord homeTask = null;
3668 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003669 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003670 if (hr.isHomeActivity) {
3671 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003672 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003673 }
3674 }
3675 if (homeTask != null) {
3676 moveTaskToFrontLocked(homeTask, null);
3677 }
3678 }
3679
3680
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003681 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason) {
3682 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
3683
3684 final int task = tr.taskId;
3685 int top = mHistory.size()-1;
3686
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003687 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003688 // nothing to do!
3689 return;
3690 }
3691
3692 ArrayList moved = new ArrayList();
3693
3694 // Applying the affinities may have removed entries from the history,
3695 // so get the size again.
3696 top = mHistory.size()-1;
3697 int pos = top;
3698
3699 // Shift all activities with this task up to the top
3700 // of the stack, keeping them in the same internal order.
3701 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003702 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003703 if (localLOGV) Slog.v(
3704 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003705 if (r.task.taskId == task) {
3706 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
3707 mHistory.remove(pos);
3708 mHistory.add(top, r);
3709 moved.add(0, r);
3710 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 }
3712 pos--;
3713 }
3714
3715 if (DEBUG_TRANSITION) Slog.v(TAG,
3716 "Prepare to front transition: task=" + tr);
3717 if (reason != null &&
3718 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003719 mService.mWindowManager.prepareAppTransition(
3720 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003721 ActivityRecord r = topRunningActivityLocked(null);
3722 if (r != null) {
3723 mNoAnimActivities.add(r);
3724 }
3725 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003726 mService.mWindowManager.prepareAppTransition(
3727 WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003728 }
3729
3730 mService.mWindowManager.moveAppTokensToTop(moved);
3731 if (VALIDATE_TOKENS) {
3732 mService.mWindowManager.validateAppTokens(mHistory);
3733 }
3734
3735 finishTaskMoveLocked(task);
3736 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
3737 }
3738
3739 private final void finishTaskMoveLocked(int task) {
3740 resumeTopActivityLocked(null);
3741 }
3742
3743 /**
3744 * Worker method for rearranging history stack. Implements the function of moving all
3745 * activities for a specific task (gathering them if disjoint) into a single group at the
3746 * bottom of the stack.
3747 *
3748 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
3749 * to premeptively cancel the move.
3750 *
3751 * @param task The taskId to collect and move to the bottom.
3752 * @return Returns true if the move completed, false if not.
3753 */
3754 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
3755 Slog.i(TAG, "moveTaskToBack: " + task);
3756
3757 // If we have a watcher, preflight the move before committing to it. First check
3758 // for *other* available tasks, but if none are available, then try again allowing the
3759 // current task to be selected.
3760 if (mMainStack && mService.mController != null) {
3761 ActivityRecord next = topRunningActivityLocked(null, task);
3762 if (next == null) {
3763 next = topRunningActivityLocked(null, 0);
3764 }
3765 if (next != null) {
3766 // ask watcher if this is allowed
3767 boolean moveOK = true;
3768 try {
3769 moveOK = mService.mController.activityResuming(next.packageName);
3770 } catch (RemoteException e) {
3771 mService.mController = null;
3772 }
3773 if (!moveOK) {
3774 return false;
3775 }
3776 }
3777 }
3778
3779 ArrayList moved = new ArrayList();
3780
3781 if (DEBUG_TRANSITION) Slog.v(TAG,
3782 "Prepare to back transition: task=" + task);
3783
3784 final int N = mHistory.size();
3785 int bottom = 0;
3786 int pos = 0;
3787
3788 // Shift all activities with this task down to the bottom
3789 // of the stack, keeping them in the same internal order.
3790 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003791 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792 if (localLOGV) Slog.v(
3793 TAG, "At " + pos + " ckp " + r.task + ": " + r);
3794 if (r.task.taskId == task) {
3795 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
3796 mHistory.remove(pos);
3797 mHistory.add(bottom, r);
3798 moved.add(r);
3799 bottom++;
3800 }
3801 pos++;
3802 }
3803
3804 if (reason != null &&
3805 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003806 mService.mWindowManager.prepareAppTransition(
3807 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003808 ActivityRecord r = topRunningActivityLocked(null);
3809 if (r != null) {
3810 mNoAnimActivities.add(r);
3811 }
3812 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003813 mService.mWindowManager.prepareAppTransition(
3814 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003815 }
3816 mService.mWindowManager.moveAppTokensToBottom(moved);
3817 if (VALIDATE_TOKENS) {
3818 mService.mWindowManager.validateAppTokens(mHistory);
3819 }
3820
3821 finishTaskMoveLocked(task);
3822 return true;
3823 }
3824
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003825 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
3826 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
3827 ActivityRecord resumed = mResumedActivity;
3828 if (resumed != null && resumed.thumbHolder == tr) {
3829 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
3830 } else {
3831 info.mainThumbnail = tr.lastThumbnail;
3832 }
3833 return info;
3834 }
3835
3836 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex) {
3837 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
3838 if (info.root == null) {
3839 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
3840 return null;
3841 }
3842
3843 if (subTaskIndex < 0) {
3844 // Just remove the entire task.
3845 performClearTaskAtIndexLocked(taskId, info.rootIndex);
3846 return info.root;
3847 }
3848
3849 if (subTaskIndex >= info.subtasks.size()) {
3850 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
3851 return null;
3852 }
3853
3854 // Remove all of this task's activies starting at the sub task.
3855 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
3856 performClearTaskAtIndexLocked(taskId, subtask.index);
3857 return subtask.activity;
3858 }
3859
3860 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
3861 ActivityRecord resumed = mResumedActivity;
3862 final TaskAccessInfo thumbs = new TaskAccessInfo();
3863 // How many different sub-thumbnails?
3864 final int NA = mHistory.size();
3865 int j = 0;
3866 ThumbnailHolder holder = null;
3867 while (j < NA) {
3868 ActivityRecord ar = mHistory.get(j);
3869 if (!ar.finishing && ar.task.taskId == taskId) {
3870 holder = ar.thumbHolder;
3871 break;
3872 }
3873 j++;
3874 }
3875
3876 if (j >= NA) {
3877 return thumbs;
3878 }
3879
3880 thumbs.root = mHistory.get(j);
3881 thumbs.rootIndex = j;
3882
3883 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
3884 thumbs.subtasks = subtasks;
3885 ActivityRecord lastActivity = null;
3886 while (j < NA) {
3887 ActivityRecord ar = mHistory.get(j);
3888 j++;
3889 if (ar.finishing) {
3890 continue;
3891 }
3892 if (ar.task.taskId != taskId) {
3893 break;
3894 }
3895 lastActivity = ar;
3896 if (ar.thumbHolder != holder && holder != null) {
3897 thumbs.numSubThumbbails++;
3898 holder = ar.thumbHolder;
3899 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
3900 sub.thumbnail = holder.lastThumbnail;
3901 sub.activity = ar;
3902 sub.index = j-1;
3903 subtasks.add(sub);
3904 }
3905 }
3906 if (lastActivity != null && subtasks.size() > 0) {
3907 if (resumed == lastActivity) {
3908 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
3909 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
3910 }
3911 }
3912 if (thumbs.numSubThumbbails > 0) {
3913 thumbs.retriever = new IThumbnailRetriever.Stub() {
3914 public Bitmap getThumbnail(int index) {
3915 if (index < 0 || index >= thumbs.subtasks.size()) {
3916 return null;
3917 }
3918 return thumbs.subtasks.get(index).thumbnail;
3919 }
3920 };
3921 }
3922 return thumbs;
3923 }
3924
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003925 private final void logStartActivity(int tag, ActivityRecord r,
3926 TaskRecord task) {
3927 EventLog.writeEvent(tag,
3928 System.identityHashCode(r), task.taskId,
3929 r.shortComponentName, r.intent.getAction(),
3930 r.intent.getType(), r.intent.getDataString(),
3931 r.intent.getFlags());
3932 }
3933
3934 /**
3935 * Make sure the given activity matches the current configuration. Returns
3936 * false if the activity had to be destroyed. Returns true if the
3937 * configuration is the same, or the activity will remain running as-is
3938 * for whatever reason. Ensures the HistoryRecord is updated with the
3939 * correct configuration and all other bookkeeping is handled.
3940 */
3941 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
3942 int globalChanges) {
3943 if (mConfigWillChange) {
3944 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3945 "Skipping config check (will change): " + r);
3946 return true;
3947 }
3948
3949 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3950 "Ensuring correct configuration: " + r);
3951
3952 // Short circuit: if the two configurations are the exact same
3953 // object (the common case), then there is nothing to do.
3954 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003955 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003956 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3957 "Configuration unchanged in " + r);
3958 return true;
3959 }
3960
3961 // We don't worry about activities that are finishing.
3962 if (r.finishing) {
3963 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3964 "Configuration doesn't matter in finishing " + r);
3965 r.stopFreezingScreenLocked(false);
3966 return true;
3967 }
3968
3969 // Okay we now are going to make this activity have the new config.
3970 // But then we need to figure out how it needs to deal with that.
3971 Configuration oldConfig = r.configuration;
3972 r.configuration = newConfig;
3973
3974 // If the activity isn't currently running, just leave the new
3975 // configuration and it will pick that up next time it starts.
3976 if (r.app == null || r.app.thread == null) {
3977 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3978 "Configuration doesn't matter not running " + r);
3979 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003980 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003981 return true;
3982 }
3983
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003984 // Figure out what has changed between the two configurations.
3985 int changes = oldConfig.diff(newConfig);
3986 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
3987 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
3988 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07003989 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003990 + ", newConfig=" + newConfig);
3991 }
Dianne Hackborne6676352011-06-01 16:51:20 -07003992 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003993 // Aha, the activity isn't handling the change, so DIE DIE DIE.
3994 r.configChangeFlags |= changes;
3995 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04003996 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07003997 if (r.app == null || r.app.thread == null) {
3998 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
3999 "Switch is destroying non-running " + r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004000 destroyActivityLocked(r, true, false);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004001 } else if (r.state == ActivityState.PAUSING) {
4002 // A little annoying: we are waiting for this activity to
4003 // finish pausing. Let's not do anything now, but just
4004 // flag that it needs to be restarted when done pausing.
4005 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4006 "Switch is skipping already pausing " + r);
4007 r.configDestroy = true;
4008 return true;
4009 } else if (r.state == ActivityState.RESUMED) {
4010 // Try to optimize this case: the configuration is changing
4011 // and we need to restart the top, resumed activity.
4012 // Instead of doing the normal handshaking, just say
4013 // "restart!".
4014 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4015 "Switch is restarting resumed " + r);
4016 relaunchActivityLocked(r, r.configChangeFlags, true);
4017 r.configChangeFlags = 0;
4018 } else {
4019 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4020 "Switch is restarting non-resumed " + r);
4021 relaunchActivityLocked(r, r.configChangeFlags, false);
4022 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004023 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004024
4025 // All done... tell the caller we weren't able to keep this
4026 // activity around.
4027 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004028 }
4029
4030 // Default case: the activity can handle this new configuration, so
4031 // hand it over. Note that we don't need to give it the new
4032 // configuration, since we always send configuration changes to all
4033 // process when they happen so it can just use whatever configuration
4034 // it last got.
4035 if (r.app != null && r.app.thread != null) {
4036 try {
4037 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
4038 r.app.thread.scheduleActivityConfigurationChanged(r);
4039 } catch (RemoteException e) {
4040 // If process died, whatever.
4041 }
4042 }
4043 r.stopFreezingScreenLocked(false);
4044
4045 return true;
4046 }
4047
4048 private final boolean relaunchActivityLocked(ActivityRecord r,
4049 int changes, boolean andResume) {
4050 List<ResultInfo> results = null;
4051 List<Intent> newIntents = null;
4052 if (andResume) {
4053 results = r.results;
4054 newIntents = r.newIntents;
4055 }
4056 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4057 + " with results=" + results + " newIntents=" + newIntents
4058 + " andResume=" + andResume);
4059 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4060 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4061 r.task.taskId, r.shortComponentName);
4062
4063 r.startFreezingScreenLocked(r.app, 0);
4064
4065 try {
4066 if (DEBUG_SWITCH) Slog.i(TAG, "Switch is restarting resumed " + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004067 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004068 r.app.thread.scheduleRelaunchActivity(r, results, newIntents,
4069 changes, !andResume, mService.mConfiguration);
4070 // Note: don't need to call pauseIfSleepingLocked() here, because
4071 // the caller will only pass in 'andResume' if this activity is
4072 // currently resumed, which implies we aren't sleeping.
4073 } catch (RemoteException e) {
4074 return false;
4075 }
4076
4077 if (andResume) {
4078 r.results = null;
4079 r.newIntents = null;
4080 if (mMainStack) {
4081 mService.reportResumedActivityLocked(r);
4082 }
4083 }
4084
4085 return true;
4086 }
4087}