blob: 29ee0bcfe5a9adf7554f12b8d1e5a3fe4c510d09 [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
Jeff Sharkey35be7562012-04-18 19:16:15 -070019import static android.Manifest.permission.START_ANY_ACTIVITY;
20import static android.content.pm.PackageManager.PERMISSION_GRANTED;
21
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070022import com.android.internal.app.HeavyWeightSwitcherActivity;
23import com.android.internal.os.BatteryStatsImpl;
24import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
25
26import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070028import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import android.app.AppGlobals;
30import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070031import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070032import android.app.IApplicationThread;
33import android.app.PendingIntent;
34import android.app.ResultInfo;
35import android.app.IActivityManager.WaitResult;
36import android.content.ComponentName;
37import android.content.Context;
38import android.content.IIntentSender;
39import android.content.Intent;
40import android.content.IntentSender;
41import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
45import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080046import android.content.res.Resources;
47import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070048import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070049import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070050import android.os.Handler;
51import android.os.IBinder;
52import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070053import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070054import android.os.PowerManager;
55import android.os.RemoteException;
56import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070057import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070058import android.util.EventLog;
59import android.util.Log;
60import android.util.Slog;
Craig Mautner59c00972012-07-30 12:10:24 -070061import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070062import android.view.WindowManagerPolicy;
63
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070064import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070065import java.lang.ref.WeakReference;
66import java.util.ArrayList;
67import java.util.Iterator;
68import java.util.List;
69
70/**
71 * State and management of a single stack of activities.
72 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070073final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070074 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070075 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
77 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
78 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
79 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
80 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
81 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
82 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
83 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
84
Dianne Hackbornce86ba82011-07-13 19:33:41 -070085 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070086 static final boolean DEBUG_ADD_REMOVE = false;
87 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070088
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;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070094
95 // Ticks during which we check progress while waiting for an app to launch.
96 static final int LAUNCH_TICK = 500;
97
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070098 // How long we wait until giving up on the last activity to pause. This
99 // is short because it directly impacts the responsiveness of starting the
100 // next activity.
101 static final int PAUSE_TIMEOUT = 500;
102
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700103 // How long we wait for the activity to tell us it has stopped before
104 // giving up. This is a good amount of time because we really need this
105 // from the application in order to get its saved state.
106 static final int STOP_TIMEOUT = 10*1000;
107
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800108 // How long we can hold the sleep wake lock before giving up.
109 static final int SLEEP_TIMEOUT = 5*1000;
110
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700111 // How long we can hold the launch wake lock before giving up.
112 static final int LAUNCH_TIMEOUT = 10*1000;
113
114 // How long we wait until giving up on an activity telling us it has
115 // finished destroying itself.
116 static final int DESTROY_TIMEOUT = 10*1000;
117
118 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800119 // disabled.
120 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700121
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700122 // How long between activity launches that we consider safe to not warn
123 // the user about an unexpected activity being launched on top.
124 static final long START_WARN_TIME = 5*1000;
125
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700126 // Set to false to disable the preview that is shown while a new activity
127 // is being started.
128 static final boolean SHOW_APP_STARTING_PREVIEW = true;
129
130 enum ActivityState {
131 INITIALIZING,
132 RESUMED,
133 PAUSING,
134 PAUSED,
135 STOPPING,
136 STOPPED,
137 FINISHING,
138 DESTROYING,
139 DESTROYED
140 }
141
142 final ActivityManagerService mService;
143 final boolean mMainStack;
144
145 final Context mContext;
146
147 /**
148 * The back history of all previous (and possibly still
149 * running) activities. It contains HistoryRecord objects.
150 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700151 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800152
153 /**
154 * Used for validating app tokens with window manager.
155 */
156 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
157
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700158 /**
159 * List of running activities, sorted by recent usage.
160 * The first entry in the list is the least recently used.
161 * It contains HistoryRecord objects.
162 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700163 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700164
165 /**
166 * List of activities that are waiting for a new activity
167 * to become visible before completing whatever operation they are
168 * supposed to do.
169 */
170 final ArrayList<ActivityRecord> mWaitingVisibleActivities
171 = new ArrayList<ActivityRecord>();
172
173 /**
174 * List of activities that are ready to be stopped, but waiting
175 * for the next activity to settle down before doing so. It contains
176 * HistoryRecord objects.
177 */
178 final ArrayList<ActivityRecord> mStoppingActivities
179 = new ArrayList<ActivityRecord>();
180
181 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800182 * List of activities that are in the process of going to sleep.
183 */
184 final ArrayList<ActivityRecord> mGoingToSleepActivities
185 = new ArrayList<ActivityRecord>();
186
187 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700188 * Animations that for the current transition have requested not to
189 * be considered for the transition animation.
190 */
191 final ArrayList<ActivityRecord> mNoAnimActivities
192 = new ArrayList<ActivityRecord>();
193
194 /**
195 * List of activities that are ready to be finished, but waiting
196 * for the previous activity to settle down before doing so. It contains
197 * HistoryRecord objects.
198 */
199 final ArrayList<ActivityRecord> mFinishingActivities
200 = new ArrayList<ActivityRecord>();
201
202 /**
203 * List of people waiting to find out about the next launched activity.
204 */
205 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
206 = new ArrayList<IActivityManager.WaitResult>();
207
208 /**
209 * List of people waiting to find out about the next visible activity.
210 */
211 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
212 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700213
214 final ArrayList<UserStartedState> mStartingUsers
215 = new ArrayList<UserStartedState>();
216
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700217 /**
218 * Set when the system is going to sleep, until we have
219 * successfully paused the current activity and released our wake lock.
220 * At that point the system is allowed to actually sleep.
221 */
222 final PowerManager.WakeLock mGoingToSleep;
223
224 /**
225 * We don't want to allow the device to go to sleep while in the process
226 * of launching an activity. This is primarily to allow alarm intent
227 * receivers to launch an activity and get that to run before the device
228 * goes back to sleep.
229 */
230 final PowerManager.WakeLock mLaunchingActivity;
231
232 /**
233 * When we are in the process of pausing an activity, before starting the
234 * next one, this variable holds the activity that is currently being paused.
235 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800236 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700237
238 /**
239 * This is the last activity that we put into the paused state. This is
240 * used to determine if we need to do an activity transition while sleeping,
241 * when we normally hold the top activity paused.
242 */
243 ActivityRecord mLastPausedActivity = null;
244
245 /**
246 * Current activity that is resumed, or null if there is none.
247 */
248 ActivityRecord mResumedActivity = null;
249
250 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700251 * This is the last activity that has been started. It is only used to
252 * identify when multiple activities are started at once so that the user
253 * can be warned they may not be in the activity they think they are.
254 */
255 ActivityRecord mLastStartedActivity = null;
256
257 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700258 * Set when we know we are going to be calling updateConfiguration()
259 * soon, so want to skip intermediate config checks.
260 */
261 boolean mConfigWillChange;
262
263 /**
264 * Set to indicate whether to issue an onUserLeaving callback when a
265 * newly launched activity is being brought in front of us.
266 */
267 boolean mUserLeaving = false;
268
269 long mInitialStartTime = 0;
270
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800271 /**
272 * Set when we have taken too long waiting to go to sleep.
273 */
274 boolean mSleepTimeout = false;
275
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700276 /**
277 * Dismiss the keyguard after the next activity is displayed?
278 */
279 boolean mDismissKeyguardOnNextActivity = false;
280
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800281 int mThumbnailWidth = -1;
282 int mThumbnailHeight = -1;
283
Amith Yamasani742a6712011-05-04 14:49:28 -0700284 private int mCurrentUser;
285
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800286 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
287 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
288 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
289 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
290 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
291 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
292 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700293 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700294 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700295 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
296
297 static class ScheduleDestroyArgs {
298 final ProcessRecord mOwner;
299 final boolean mOomAdj;
300 final String mReason;
301 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
302 mOwner = owner;
303 mOomAdj = oomAdj;
304 mReason = reason;
305 }
306 }
307
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700308 final Handler mHandler = new Handler() {
309 //public Handler() {
310 // if (localLOGV) Slog.v(TAG, "Handler started!");
311 //}
312
313 public void handleMessage(Message msg) {
314 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800315 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700316 synchronized (mService) {
317 if (mService.isSleeping()) {
318 Slog.w(TAG, "Sleep timeout! Sleeping now.");
319 mSleepTimeout = true;
320 checkReadyForSleepLocked();
321 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800322 }
323 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700324 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800325 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700326 // We don't at this point know if the activity is fullscreen,
327 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800328 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700329 synchronized (mService) {
330 if (r.app != null) {
331 mService.logAppTooSlow(r.app, r.pauseTime,
332 "pausing " + r);
333 }
334 }
335
Dianne Hackbornbe707852011-11-11 14:32:10 -0800336 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700337 } break;
338 case IDLE_TIMEOUT_MSG: {
339 if (mService.mDidDexOpt) {
340 mService.mDidDexOpt = false;
341 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
342 nmsg.obj = msg.obj;
343 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
344 return;
345 }
346 // We don't at this point know if the activity is fullscreen,
347 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800348 ActivityRecord r = (ActivityRecord)msg.obj;
349 Slog.w(TAG, "Activity idle timeout for " + r);
350 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700351 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700352 case LAUNCH_TICK_MSG: {
353 ActivityRecord r = (ActivityRecord)msg.obj;
354 synchronized (mService) {
355 if (r.continueLaunchTickingLocked()) {
356 mService.logAppTooSlow(r.app, r.launchTickTime,
357 "launching " + r);
358 }
359 }
360 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700361 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800362 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700363 // We don't at this point know if the activity is fullscreen,
364 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800365 Slog.w(TAG, "Activity destroy timeout for " + r);
366 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 } break;
368 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800369 ActivityRecord r = (ActivityRecord)msg.obj;
370 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700371 } break;
372 case LAUNCH_TIMEOUT_MSG: {
373 if (mService.mDidDexOpt) {
374 mService.mDidDexOpt = false;
375 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
376 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
377 return;
378 }
379 synchronized (mService) {
380 if (mLaunchingActivity.isHeld()) {
381 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
382 mLaunchingActivity.release();
383 }
384 }
385 } break;
386 case RESUME_TOP_ACTIVITY_MSG: {
387 synchronized (mService) {
388 resumeTopActivityLocked(null);
389 }
390 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700391 case STOP_TIMEOUT_MSG: {
392 ActivityRecord r = (ActivityRecord)msg.obj;
393 // We don't at this point know if the activity is fullscreen,
394 // so we need to be conservative and assume it isn't.
395 Slog.w(TAG, "Activity stop timeout for " + r);
396 synchronized (mService) {
397 if (r.isInHistory()) {
398 activityStoppedLocked(r, null, null, null);
399 }
400 }
401 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700402 case DESTROY_ACTIVITIES_MSG: {
403 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
404 synchronized (mService) {
405 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
406 }
407 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700408 }
409 }
410 };
411
412 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
413 mService = service;
414 mContext = context;
415 mMainStack = mainStack;
416 PowerManager pm =
417 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
418 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
419 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
420 mLaunchingActivity.setReferenceCounted(false);
421 }
422
423 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
424 int i = mHistory.size()-1;
425 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700426 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700427 if (!r.finishing && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700428 return r;
429 }
430 i--;
431 }
432 return null;
433 }
434
435 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
436 int i = mHistory.size()-1;
437 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700438 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700439 if (!r.finishing && !r.delayedResume && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700440 return r;
441 }
442 i--;
443 }
444 return null;
445 }
446
447 /**
448 * This is a simplified version of topRunningActivityLocked that provides a number of
449 * optional skip-over modes. It is intended for use with the ActivityController hook only.
450 *
451 * @param token If non-null, any history records matching this token will be skipped.
452 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
453 *
454 * @return Returns the HistoryRecord of the next activity on the stack.
455 */
456 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
457 int i = mHistory.size()-1;
458 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700459 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700460 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700461 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
462 && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700463 return r;
464 }
465 i--;
466 }
467 return null;
468 }
469
470 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800471 return mHistory.indexOf(ActivityRecord.forToken(token));
472 }
473
474 final int indexOfActivityLocked(ActivityRecord r) {
475 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700476 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700477
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700478 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800479 ActivityRecord r = ActivityRecord.forToken(token);
480 if (mHistory.contains(r)) {
481 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700482 }
483 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700484 }
485
486 private final boolean updateLRUListLocked(ActivityRecord r) {
487 final boolean hadit = mLRUActivities.remove(r);
488 mLRUActivities.add(r);
489 return hadit;
490 }
491
492 /**
493 * Returns the top activity in any existing task matching the given
494 * Intent. Returns null if no such task is found.
495 */
496 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
497 ComponentName cls = intent.getComponent();
498 if (info.targetActivity != null) {
499 cls = new ComponentName(info.packageName, info.targetActivity);
500 }
501
502 TaskRecord cp = null;
503
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700504 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700505 final int N = mHistory.size();
506 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700507 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700508 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700509 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
510 cp = r.task;
511 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
512 // + "/aff=" + r.task.affinity + " to new cls="
513 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
514 if (r.task.affinity != null) {
515 if (r.task.affinity.equals(info.taskAffinity)) {
516 //Slog.i(TAG, "Found matching affinity!");
517 return r;
518 }
519 } else if (r.task.intent != null
520 && r.task.intent.getComponent().equals(cls)) {
521 //Slog.i(TAG, "Found matching class!");
522 //dump();
523 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
524 return r;
525 } else if (r.task.affinityIntent != null
526 && r.task.affinityIntent.getComponent().equals(cls)) {
527 //Slog.i(TAG, "Found matching class!");
528 //dump();
529 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
530 return r;
531 }
532 }
533 }
534
535 return null;
536 }
537
538 /**
539 * Returns the first activity (starting from the top of the stack) that
540 * is the same as the given activity. Returns null if no such activity
541 * is found.
542 */
543 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
544 ComponentName cls = intent.getComponent();
545 if (info.targetActivity != null) {
546 cls = new ComponentName(info.packageName, info.targetActivity);
547 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700548 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700549
550 final int N = mHistory.size();
551 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700552 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700553 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700554 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700555 //Slog.i(TAG, "Found matching class!");
556 //dump();
557 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
558 return r;
559 }
560 }
561 }
562
563 return null;
564 }
565
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700566 final void showAskCompatModeDialogLocked(ActivityRecord r) {
567 Message msg = Message.obtain();
568 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
569 msg.obj = r.task.askedCompatMode ? null : r;
570 mService.mHandler.sendMessage(msg);
571 }
572
Amith Yamasani742a6712011-05-04 14:49:28 -0700573 /*
574 * Move the activities around in the stack to bring a user to the foreground.
575 * @return whether there are any activities for the specified user.
576 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700577 final boolean switchUserLocked(int userId, UserStartedState uss) {
578 mCurrentUser = userId;
579 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700580
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700581 // Only one activity? Nothing to do...
582 if (mHistory.size() < 2)
583 return false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700584
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700585 boolean haveActivities = false;
586 // Check if the top activity is from the new user.
587 ActivityRecord top = mHistory.get(mHistory.size() - 1);
588 if (top.userId == userId) return true;
589 // Otherwise, move the user's activities to the top.
590 int N = mHistory.size();
591 int i = 0;
592 while (i < N) {
593 ActivityRecord r = mHistory.get(i);
594 if (r.userId == userId) {
595 ActivityRecord moveToTop = mHistory.remove(i);
596 mHistory.add(moveToTop);
597 // No need to check the top one now
598 N--;
599 haveActivities = true;
600 } else {
601 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700602 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700603 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700604 // Transition from the old top to the new top
605 resumeTopActivityLocked(top);
606 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700607 }
608
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700609 final boolean realStartActivityLocked(ActivityRecord r,
610 ProcessRecord app, boolean andResume, boolean checkConfig)
611 throws RemoteException {
612
613 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800614 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700615
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700616 // schedule launch ticks to collect information about slow apps.
617 r.startLaunchTickingLocked();
618
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700619 // Have the window manager re-evaluate the orientation of
620 // the screen based on the new activity order. Note that
621 // as a result of this, it can call back into the activity
622 // manager with a new orientation. We don't care about that,
623 // because the activity is not currently running so we are
624 // just restarting it anyway.
625 if (checkConfig) {
626 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
627 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800628 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800629 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700630 }
631
632 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700633 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700634
635 if (localLOGV) Slog.v(TAG, "Launching: " + r);
636
637 int idx = app.activities.indexOf(r);
638 if (idx < 0) {
639 app.activities.add(r);
640 }
641 mService.updateLruProcessLocked(app, true, true);
642
643 try {
644 if (app.thread == null) {
645 throw new RemoteException();
646 }
647 List<ResultInfo> results = null;
648 List<Intent> newIntents = null;
649 if (andResume) {
650 results = r.results;
651 newIntents = r.newIntents;
652 }
653 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
654 + " icicle=" + r.icicle
655 + " with results=" + results + " newIntents=" + newIntents
656 + " andResume=" + andResume);
657 if (andResume) {
658 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
659 System.identityHashCode(r),
660 r.task.taskId, r.shortComponentName);
661 }
662 if (r.isHomeActivity) {
663 mService.mHomeProcess = app;
664 }
665 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800666 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400667 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700668 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700669 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700670 String profileFile = null;
671 ParcelFileDescriptor profileFd = null;
672 boolean profileAutoStop = false;
673 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
674 if (mService.mProfileProc == null || mService.mProfileProc == app) {
675 mService.mProfileProc = app;
676 profileFile = mService.mProfileFile;
677 profileFd = mService.mProfileFd;
678 profileAutoStop = mService.mAutoStopProfiler;
679 }
680 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700681 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700682 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700683 if (profileFd != null) {
684 try {
685 profileFd = profileFd.dup();
686 } catch (IOException e) {
687 profileFd = null;
688 }
689 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800690 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800691 System.identityHashCode(r), r.info,
692 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700693 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700694 mService.isNextTransitionForward(), profileFile, profileFd,
695 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700696
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700697 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700698 // This may be a heavy-weight process! Note that the package
699 // manager will ensure that only activity can run in the main
700 // process of the .apk, which is the only thing that will be
701 // considered heavy-weight.
702 if (app.processName.equals(app.info.packageName)) {
703 if (mService.mHeavyWeightProcess != null
704 && mService.mHeavyWeightProcess != app) {
705 Log.w(TAG, "Starting new heavy weight process " + app
706 + " when already running "
707 + mService.mHeavyWeightProcess);
708 }
709 mService.mHeavyWeightProcess = app;
710 Message msg = mService.mHandler.obtainMessage(
711 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
712 msg.obj = r;
713 mService.mHandler.sendMessage(msg);
714 }
715 }
716
717 } catch (RemoteException e) {
718 if (r.launchFailed) {
719 // This is the second time we failed -- finish activity
720 // and give up.
721 Slog.e(TAG, "Second failure launching "
722 + r.intent.getComponent().flattenToShortString()
723 + ", giving up", e);
724 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800725 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700726 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700727 return false;
728 }
729
730 // This is the first time we failed -- restart process and
731 // retry.
732 app.activities.remove(r);
733 throw e;
734 }
735
736 r.launchFailed = false;
737 if (updateLRUListLocked(r)) {
738 Slog.w(TAG, "Activity " + r
739 + " being launched, but already in LRU list");
740 }
741
742 if (andResume) {
743 // As part of the process of launching, ActivityThread also performs
744 // a resume.
745 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700746 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
747 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700748 r.stopped = false;
749 mResumedActivity = r;
750 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800751 if (mMainStack) {
752 mService.addRecentTaskLocked(r.task);
753 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700754 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800755 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700756 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700757 } else {
758 // This activity is not starting in the resumed state... which
759 // should look like we asked it to pause+stop (but remain visible),
760 // and it has done so and reported back the current icicle and
761 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700762 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
763 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700764 r.state = ActivityState.STOPPED;
765 r.stopped = true;
766 }
767
768 // Launch the new version setup screen if needed. We do this -after-
769 // launching the initial activity (that is, home), so that it can have
770 // a chance to initialize itself while in the background, making the
771 // switch back to it faster and look better.
772 if (mMainStack) {
773 mService.startSetupActivityLocked();
774 }
775
776 return true;
777 }
778
779 private final void startSpecificActivityLocked(ActivityRecord r,
780 boolean andResume, boolean checkConfig) {
781 // Is this activity's application already running?
782 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
783 r.info.applicationInfo.uid);
784
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700785 if (r.launchTime == 0) {
786 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700787 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700788 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700789 }
790 } else if (mInitialStartTime == 0) {
791 mInitialStartTime = SystemClock.uptimeMillis();
792 }
793
794 if (app != null && app.thread != null) {
795 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700796 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700797 realStartActivityLocked(r, app, andResume, checkConfig);
798 return;
799 } catch (RemoteException e) {
800 Slog.w(TAG, "Exception when starting activity "
801 + r.intent.getComponent().flattenToShortString(), e);
802 }
803
804 // If a dead object exception was thrown -- fall through to
805 // restart the application.
806 }
807
808 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800809 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700810 }
811
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800812 void stopIfSleepingLocked() {
813 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700814 if (!mGoingToSleep.isHeld()) {
815 mGoingToSleep.acquire();
816 if (mLaunchingActivity.isHeld()) {
817 mLaunchingActivity.release();
818 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
819 }
820 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800821 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
822 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
823 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
824 checkReadyForSleepLocked();
825 }
826 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700827
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800828 void awakeFromSleepingLocked() {
829 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
830 mSleepTimeout = false;
831 if (mGoingToSleep.isHeld()) {
832 mGoingToSleep.release();
833 }
834 // Ensure activities are no longer sleeping.
835 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700836 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800837 r.setSleeping(false);
838 }
839 mGoingToSleepActivities.clear();
840 }
841
842 void activitySleptLocked(ActivityRecord r) {
843 mGoingToSleepActivities.remove(r);
844 checkReadyForSleepLocked();
845 }
846
847 void checkReadyForSleepLocked() {
848 if (!mService.isSleeping()) {
849 // Do not care.
850 return;
851 }
852
853 if (!mSleepTimeout) {
854 if (mResumedActivity != null) {
855 // Still have something resumed; can't sleep until it is paused.
856 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700857 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
858 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800859 return;
860 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800861 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800862 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800863 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800864 return;
865 }
866
867 if (mStoppingActivities.size() > 0) {
868 // Still need to tell some activities to stop; can't sleep yet.
869 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
870 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700871 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800872 return;
873 }
874
875 ensureActivitiesVisibleLocked(null, 0);
876
877 // Make sure any stopped but visible activities are now sleeping.
878 // This ensures that the activity's onStop() is called.
879 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700880 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800881 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
882 r.setSleeping(true);
883 }
884 }
885
886 if (mGoingToSleepActivities.size() > 0) {
887 // Still need to tell some activities to sleep; can't sleep yet.
888 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
889 + mGoingToSleepActivities.size() + " activities");
890 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700891 }
892 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800893
894 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
895
896 if (mGoingToSleep.isHeld()) {
897 mGoingToSleep.release();
898 }
899 if (mService.mShuttingDown) {
900 mService.notifyAll();
901 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700902 }
Craig Mautner59c00972012-07-30 12:10:24 -0700903
Dianne Hackbornd2835932010-12-13 16:28:46 -0800904 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800905 if (who.noDisplay) {
906 return null;
907 }
908
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800909 Resources res = mService.mContext.getResources();
910 int w = mThumbnailWidth;
911 int h = mThumbnailHeight;
912 if (w < 0) {
913 mThumbnailWidth = w =
914 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
915 mThumbnailHeight = h =
916 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
917 }
918
919 if (w > 0) {
Craig Mautner59c00972012-07-30 12:10:24 -0700920 return mService.mWindowManager.screenshotApplications(who.appToken,
921 Display.DEFAULT_DISPLAY, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800922 }
923 return null;
924 }
925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700926 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800927 if (mPausingActivity != null) {
928 RuntimeException e = new RuntimeException();
929 Slog.e(TAG, "Trying to pause when pause is already pending for "
930 + mPausingActivity, e);
931 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700932 ActivityRecord prev = mResumedActivity;
933 if (prev == null) {
934 RuntimeException e = new RuntimeException();
935 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
936 resumeTopActivityLocked(null);
937 return;
938 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700939 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
940 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700941 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800942 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700943 mLastPausedActivity = prev;
944 prev.state = ActivityState.PAUSING;
945 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700946 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700947
948 mService.updateCpuStats();
949
950 if (prev.app != null && prev.app.thread != null) {
951 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
952 try {
953 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
954 System.identityHashCode(prev),
955 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800956 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
957 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700958 if (mMainStack) {
959 mService.updateUsageStats(prev, false);
960 }
961 } catch (Exception e) {
962 // Ignore exception, if process died other code will cleanup.
963 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800964 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700965 mLastPausedActivity = null;
966 }
967 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800968 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700969 mLastPausedActivity = null;
970 }
971
972 // If we are not going to sleep, we want to ensure the device is
973 // awake until the next activity is started.
974 if (!mService.mSleeping && !mService.mShuttingDown) {
975 mLaunchingActivity.acquire();
976 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
977 // To be safe, don't allow the wake lock to be held for too long.
978 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
979 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
980 }
981 }
982
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800983
984 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700985 // Have the window manager pause its key dispatching until the new
986 // activity has started. If we're pausing the activity just because
987 // the screen is being turned off and the UI is sleeping, don't interrupt
988 // key dispatch; the same activity will pick it up again on wakeup.
989 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800990 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700991 } else {
992 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
993 }
994
995 // Schedule a pause timeout in case the app doesn't respond.
996 // We don't give it much time because this directly impacts the
997 // responsiveness seen by the user.
998 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
999 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001000 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001001 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1002 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1003 } else {
1004 // This activity failed to schedule the
1005 // pause, so just treat it as being paused now.
1006 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001007 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001008 }
1009 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001010
1011 final void activityResumed(IBinder token) {
1012 ActivityRecord r = null;
1013
1014 synchronized (mService) {
1015 int index = indexOfTokenLocked(token);
1016 if (index >= 0) {
1017 r = mHistory.get(index);
1018 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1019 r.icicle = null;
1020 r.haveState = false;
1021 }
1022 }
1023 }
1024
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001025 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001026 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001027 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001028
1029 ActivityRecord r = null;
1030
1031 synchronized (mService) {
1032 int index = indexOfTokenLocked(token);
1033 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001034 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001035 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001036 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001037 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1038 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001039 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001040 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001041 } else {
1042 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1043 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001044 mPausingActivity != null
1045 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001046 }
1047 }
1048 }
1049 }
1050
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001051 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1052 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001053 if (r.state != ActivityState.STOPPING) {
1054 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1055 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1056 return;
1057 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001058 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001059 if (icicle != null) {
1060 // If icicle is null, this is happening due to a timeout, so we
1061 // haven't really saved the state.
1062 r.icicle = icicle;
1063 r.haveState = true;
1064 r.updateThumbnail(thumbnail, description);
1065 }
1066 if (!r.stopped) {
1067 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1068 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1069 r.stopped = true;
1070 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001071 if (r.finishing) {
1072 r.clearOptionsLocked();
1073 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001074 if (r.configDestroy) {
1075 destroyActivityLocked(r, true, false, "stop-config");
1076 resumeTopActivityLocked(null);
1077 } else {
1078 // Now that this process has stopped, we may want to consider
1079 // it to be the previous app to try to keep around in case
1080 // the user wants to return to it.
1081 ProcessRecord fgApp = null;
1082 if (mResumedActivity != null) {
1083 fgApp = mResumedActivity.app;
1084 } else if (mPausingActivity != null) {
1085 fgApp = mPausingActivity.app;
1086 }
1087 if (r.app != null && fgApp != null && r.app != fgApp
1088 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1089 && r.app != mService.mHomeProcess) {
1090 mService.mPreviousProcess = r.app;
1091 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1092 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001093 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001094 }
1095 }
1096 }
1097
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001098 private final void completePauseLocked() {
1099 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001100 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1101
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001102 if (prev != null) {
1103 if (prev.finishing) {
1104 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001105 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001106 } else if (prev.app != null) {
1107 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1108 if (prev.waitingVisible) {
1109 prev.waitingVisible = false;
1110 mWaitingVisibleActivities.remove(prev);
1111 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1112 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001113 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001114 if (prev.configDestroy) {
1115 // The previous is being paused because the configuration
1116 // is changing, which means it is actually stopping...
1117 // To juggle the fact that we are also starting a new
1118 // instance right now, we need to first completely stop
1119 // the current instance before starting the new one.
1120 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1121 destroyActivityLocked(prev, true, false, "pause-config");
1122 } else {
1123 mStoppingActivities.add(prev);
1124 if (mStoppingActivities.size() > 3) {
1125 // If we already have a few activities waiting to stop,
1126 // then give up on things going idle and start clearing
1127 // them out.
1128 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1129 scheduleIdleLocked();
1130 } else {
1131 checkReadyForSleepLocked();
1132 }
1133 }
1134 } else {
1135 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1136 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001137 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001138 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001139 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001140
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001141 if (!mService.isSleeping()) {
1142 resumeTopActivityLocked(prev);
1143 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001144 checkReadyForSleepLocked();
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001145 if (topRunningActivityLocked(null) == null) {
1146 // If there are no more activities available to run, then
1147 // do resume anyway to start something.
1148 resumeTopActivityLocked(null);
1149 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001150 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001151
1152 if (prev != null) {
1153 prev.resumeKeyDispatchingLocked();
1154 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001155
1156 if (prev.app != null && prev.cpuTimeAtResume > 0
1157 && mService.mBatteryStatsService.isOnBattery()) {
1158 long diff = 0;
1159 synchronized (mService.mProcessStatsThread) {
1160 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1161 - prev.cpuTimeAtResume;
1162 }
1163 if (diff > 0) {
1164 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1165 synchronized (bsi) {
1166 BatteryStatsImpl.Uid.Proc ps =
1167 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1168 prev.info.packageName);
1169 if (ps != null) {
1170 ps.addForegroundTimeLocked(diff);
1171 }
1172 }
1173 }
1174 }
1175 prev.cpuTimeAtResume = 0; // reset it
1176 }
1177
1178 /**
1179 * Once we know that we have asked an application to put an activity in
1180 * the resumed state (either by launching it or explicitly telling it),
1181 * this function updates the rest of our state to match that fact.
1182 */
1183 private final void completeResumeLocked(ActivityRecord next) {
1184 next.idle = false;
1185 next.results = null;
1186 next.newIntents = null;
1187
1188 // schedule an idle timeout in case the app doesn't do it for us.
1189 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1190 msg.obj = next;
1191 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1192
1193 if (false) {
1194 // The activity was never told to pause, so just keep
1195 // things going as-is. To maintain our own state,
1196 // we need to emulate it coming back and saying it is
1197 // idle.
1198 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1199 msg.obj = next;
1200 mHandler.sendMessage(msg);
1201 }
1202
1203 if (mMainStack) {
1204 mService.reportResumedActivityLocked(next);
1205 }
1206
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001207 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001208 if (mMainStack) {
1209 mService.setFocusedActivityLocked(next);
1210 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001211 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001212 ensureActivitiesVisibleLocked(null, 0);
1213 mService.mWindowManager.executeAppTransition();
1214 mNoAnimActivities.clear();
1215
1216 // Mark the point when the activity is resuming
1217 // TODO: To be more accurate, the mark should be before the onCreate,
1218 // not after the onResume. But for subsequent starts, onResume is fine.
1219 if (next.app != null) {
1220 synchronized (mService.mProcessStatsThread) {
1221 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1222 }
1223 } else {
1224 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1225 }
1226 }
1227
1228 /**
1229 * Make sure that all activities that need to be visible (that is, they
1230 * currently can be seen by the user) actually are.
1231 */
1232 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1233 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1234 if (DEBUG_VISBILITY) Slog.v(
1235 TAG, "ensureActivitiesVisible behind " + top
1236 + " configChanges=0x" + Integer.toHexString(configChanges));
1237
1238 // If the top activity is not fullscreen, then we need to
1239 // make sure any activities under it are now visible.
1240 final int count = mHistory.size();
1241 int i = count-1;
1242 while (mHistory.get(i) != top) {
1243 i--;
1244 }
1245 ActivityRecord r;
1246 boolean behindFullscreen = false;
1247 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001248 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001249 if (DEBUG_VISBILITY) Slog.v(
1250 TAG, "Make visible? " + r + " finishing=" + r.finishing
1251 + " state=" + r.state);
1252 if (r.finishing) {
1253 continue;
1254 }
1255
1256 final boolean doThisProcess = onlyThisProcess == null
1257 || onlyThisProcess.equals(r.processName);
1258
1259 // First: if this is not the current activity being started, make
1260 // sure it matches the current configuration.
1261 if (r != starting && doThisProcess) {
1262 ensureActivityConfigurationLocked(r, 0);
1263 }
1264
1265 if (r.app == null || r.app.thread == null) {
1266 if (onlyThisProcess == null
1267 || onlyThisProcess.equals(r.processName)) {
1268 // This activity needs to be visible, but isn't even
1269 // running... get it started, but don't resume it
1270 // at this point.
1271 if (DEBUG_VISBILITY) Slog.v(
1272 TAG, "Start and freeze screen for " + r);
1273 if (r != starting) {
1274 r.startFreezingScreenLocked(r.app, configChanges);
1275 }
1276 if (!r.visible) {
1277 if (DEBUG_VISBILITY) Slog.v(
1278 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001279 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001280 }
1281 if (r != starting) {
1282 startSpecificActivityLocked(r, false, false);
1283 }
1284 }
1285
1286 } else if (r.visible) {
1287 // If this activity is already visible, then there is nothing
1288 // else to do here.
1289 if (DEBUG_VISBILITY) Slog.v(
1290 TAG, "Skipping: already visible at " + r);
1291 r.stopFreezingScreenLocked(false);
1292
1293 } else if (onlyThisProcess == null) {
1294 // This activity is not currently visible, but is running.
1295 // Tell it to become visible.
1296 r.visible = true;
1297 if (r.state != ActivityState.RESUMED && r != starting) {
1298 // If this activity is paused, tell it
1299 // to now show its window.
1300 if (DEBUG_VISBILITY) Slog.v(
1301 TAG, "Making visible and scheduling visibility: " + r);
1302 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001303 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001304 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001305 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001306 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001307 r.stopFreezingScreenLocked(false);
1308 } catch (Exception e) {
1309 // Just skip on any failure; we'll make it
1310 // visible when it next restarts.
1311 Slog.w(TAG, "Exception thrown making visibile: "
1312 + r.intent.getComponent(), e);
1313 }
1314 }
1315 }
1316
1317 // Aggregate current change flags.
1318 configChanges |= r.configChangeFlags;
1319
1320 if (r.fullscreen) {
1321 // At this point, nothing else needs to be shown
1322 if (DEBUG_VISBILITY) Slog.v(
1323 TAG, "Stopping: fullscreen at " + r);
1324 behindFullscreen = true;
1325 i--;
1326 break;
1327 }
1328 }
1329
1330 // Now for any activities that aren't visible to the user, make
1331 // sure they no longer are keeping the screen frozen.
1332 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001333 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001334 if (DEBUG_VISBILITY) Slog.v(
1335 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1336 + " state=" + r.state
1337 + " behindFullscreen=" + behindFullscreen);
1338 if (!r.finishing) {
1339 if (behindFullscreen) {
1340 if (r.visible) {
1341 if (DEBUG_VISBILITY) Slog.v(
1342 TAG, "Making invisible: " + r);
1343 r.visible = false;
1344 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001345 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001346 if ((r.state == ActivityState.STOPPING
1347 || r.state == ActivityState.STOPPED)
1348 && r.app != null && r.app.thread != null) {
1349 if (DEBUG_VISBILITY) Slog.v(
1350 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001351 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001352 }
1353 } catch (Exception e) {
1354 // Just skip on any failure; we'll make it
1355 // visible when it next restarts.
1356 Slog.w(TAG, "Exception thrown making hidden: "
1357 + r.intent.getComponent(), e);
1358 }
1359 } else {
1360 if (DEBUG_VISBILITY) Slog.v(
1361 TAG, "Already invisible: " + r);
1362 }
1363 } else if (r.fullscreen) {
1364 if (DEBUG_VISBILITY) Slog.v(
1365 TAG, "Now behindFullscreen: " + r);
1366 behindFullscreen = true;
1367 }
1368 }
1369 i--;
1370 }
1371 }
1372
1373 /**
1374 * Version of ensureActivitiesVisible that can easily be called anywhere.
1375 */
1376 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1377 int configChanges) {
1378 ActivityRecord r = topRunningActivityLocked(null);
1379 if (r != null) {
1380 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1381 }
1382 }
1383
1384 /**
1385 * Ensure that the top activity in the stack is resumed.
1386 *
1387 * @param prev The previously resumed activity, for when in the process
1388 * of pausing; can be null to call from elsewhere.
1389 *
1390 * @return Returns true if something is being resumed, or false if
1391 * nothing happened.
1392 */
1393 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001394 return resumeTopActivityLocked(prev, null);
1395 }
1396
1397 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001398 // Find the first activity that is not finishing.
1399 ActivityRecord next = topRunningActivityLocked(null);
1400
1401 // Remember how we'll process this pause/resume situation, and ensure
1402 // that the state is reset however we wind up proceeding.
1403 final boolean userLeaving = mUserLeaving;
1404 mUserLeaving = false;
1405
1406 if (next == null) {
1407 // There are no more activities! Let's just start up the
1408 // Launcher...
1409 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001410 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001411 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001412 }
1413 }
1414
1415 next.delayedResume = false;
1416
1417 // If the top activity is the resumed one, nothing to do.
1418 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1419 // Make sure we have executed any pending transitions, since there
1420 // should be nothing left to do at this point.
1421 mService.mWindowManager.executeAppTransition();
1422 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001423 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001424 return false;
1425 }
1426
1427 // If we are sleeping, and there is no resumed activity, and the top
1428 // activity is paused, well that is the state we want.
1429 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001430 && mLastPausedActivity == next
1431 && (next.state == ActivityState.PAUSED
1432 || next.state == ActivityState.STOPPED
1433 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001434 // Make sure we have executed any pending transitions, since there
1435 // should be nothing left to do at this point.
1436 mService.mWindowManager.executeAppTransition();
1437 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001438 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001439 return false;
1440 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001441
1442 // Make sure that the user who owns this activity is started. If not,
1443 // we will just leave it as is because someone should be bringing
1444 // another user's activities to the top of the stack.
1445 if (mService.mStartedUsers.get(next.userId) == null) {
1446 Slog.w(TAG, "Skipping resume of top activity " + next
1447 + ": user " + next.userId + " is stopped");
1448 return false;
1449 }
1450
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001451 // The activity may be waiting for stop, but that is no longer
1452 // appropriate for it.
1453 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001454 mGoingToSleepActivities.remove(next);
1455 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001456 mWaitingVisibleActivities.remove(next);
1457
Dianne Hackborn84375872012-06-01 19:03:50 -07001458 next.updateOptionsLocked(options);
1459
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001460 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1461
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001462 // If we are currently pausing an activity, then don't do anything
1463 // until that is done.
1464 if (mPausingActivity != null) {
1465 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1466 return false;
1467 }
1468
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001469 // Okay we are now going to start a switch, to 'next'. We may first
1470 // have to pause the current activity, but this is an important point
1471 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001472 // XXX "App Redirected" dialog is getting too many false positives
1473 // at this point, so turn off for now.
1474 if (false) {
1475 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1476 long now = SystemClock.uptimeMillis();
1477 final boolean inTime = mLastStartedActivity.startTime != 0
1478 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1479 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1480 final int nextUid = next.info.applicationInfo.uid;
1481 if (inTime && lastUid != nextUid
1482 && lastUid != next.launchedFromUid
1483 && mService.checkPermission(
1484 android.Manifest.permission.STOP_APP_SWITCHES,
1485 -1, next.launchedFromUid)
1486 != PackageManager.PERMISSION_GRANTED) {
1487 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1488 } else {
1489 next.startTime = now;
1490 mLastStartedActivity = next;
1491 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001492 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001493 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001494 mLastStartedActivity = next;
1495 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001496 }
1497
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001498 // We need to start pausing the current activity so the top one
1499 // can be resumed...
1500 if (mResumedActivity != null) {
1501 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001502 // At this point we want to put the upcoming activity's process
1503 // at the top of the LRU list, since we know we will be needing it
1504 // very soon and it would be a waste to let it get killed if it
1505 // happens to be sitting towards the end.
1506 if (next.app != null && next.app.thread != null) {
1507 // No reason to do full oom adj update here; we'll let that
1508 // happen whenever it needs to later.
1509 mService.updateLruProcessLocked(next.app, false, true);
1510 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001511 startPausingLocked(userLeaving, false);
1512 return true;
1513 }
1514
Christopher Tated3f175c2012-06-14 14:16:54 -07001515 // If the most recent activity was noHistory but was only stopped rather
1516 // than stopped+finished because the device went to sleep, we need to make
1517 // sure to finish it as we're making a new activity topmost.
1518 final ActivityRecord last = mLastPausedActivity;
1519 if (mService.mSleeping && last != null && !last.finishing) {
1520 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1521 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1522 if (DEBUG_STATES) {
1523 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1524 }
1525 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001526 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001527 }
1528 }
1529
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001530 if (prev != null && prev != next) {
1531 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1532 prev.waitingVisible = true;
1533 mWaitingVisibleActivities.add(prev);
1534 if (DEBUG_SWITCH) Slog.v(
1535 TAG, "Resuming top, waiting visible to hide: " + prev);
1536 } else {
1537 // The next activity is already visible, so hide the previous
1538 // activity's windows right now so we can show the new one ASAP.
1539 // We only do this if the previous is finishing, which should mean
1540 // it is on top of the one being resumed so hiding it quickly
1541 // is good. Otherwise, we want to do the normal route of allowing
1542 // the resumed activity to be shown so we can decide if the
1543 // previous should actually be hidden depending on whether the
1544 // new one is found to be full-screen or not.
1545 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001546 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001547 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1548 + prev + ", waitingVisible="
1549 + (prev != null ? prev.waitingVisible : null)
1550 + ", nowVisible=" + next.nowVisible);
1551 } else {
1552 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1553 + prev + ", waitingVisible="
1554 + (prev != null ? prev.waitingVisible : null)
1555 + ", nowVisible=" + next.nowVisible);
1556 }
1557 }
1558 }
1559
Dianne Hackborne7f97212011-02-24 14:40:20 -08001560 // Launching this app's activity, make sure the app is no longer
1561 // considered stopped.
1562 try {
1563 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001564 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001565 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001566 } catch (IllegalArgumentException e) {
1567 Slog.w(TAG, "Failed trying to unstop package "
1568 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001569 }
1570
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001571 // We are starting up the next activity, so tell the window manager
1572 // that the previous one will be hidden soon. This way it can know
1573 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001574 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001575 if (prev != null) {
1576 if (prev.finishing) {
1577 if (DEBUG_TRANSITION) Slog.v(TAG,
1578 "Prepare close transition: prev=" + prev);
1579 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001580 mService.mWindowManager.prepareAppTransition(
1581 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001582 } else {
1583 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1584 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001585 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001586 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001587 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1588 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001589 } else {
1590 if (DEBUG_TRANSITION) Slog.v(TAG,
1591 "Prepare open transition: prev=" + prev);
1592 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001593 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001594 mService.mWindowManager.prepareAppTransition(
1595 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001596 } else {
1597 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1598 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001599 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001600 }
1601 }
1602 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001603 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1604 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001605 }
1606 } else if (mHistory.size() > 1) {
1607 if (DEBUG_TRANSITION) Slog.v(TAG,
1608 "Prepare open transition: no previous");
1609 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001610 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001611 mService.mWindowManager.prepareAppTransition(
1612 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001613 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001614 mService.mWindowManager.prepareAppTransition(
1615 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001616 }
1617 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001618 if (!noAnim) {
1619 next.applyOptionsLocked();
1620 } else {
1621 next.clearOptionsLocked();
1622 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001623
1624 if (next.app != null && next.app.thread != null) {
1625 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1626
1627 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001628 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001629
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001630 // schedule launch ticks to collect information about slow apps.
1631 next.startLaunchTickingLocked();
1632
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001633 ActivityRecord lastResumedActivity = mResumedActivity;
1634 ActivityState lastState = next.state;
1635
1636 mService.updateCpuStats();
1637
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001638 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001639 next.state = ActivityState.RESUMED;
1640 mResumedActivity = next;
1641 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001642 if (mMainStack) {
1643 mService.addRecentTaskLocked(next.task);
1644 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001645 mService.updateLruProcessLocked(next.app, true, true);
1646 updateLRUListLocked(next);
1647
1648 // Have the window manager re-evaluate the orientation of
1649 // the screen based on the new activity order.
1650 boolean updated = false;
1651 if (mMainStack) {
1652 synchronized (mService) {
1653 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1654 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001655 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001656 if (config != null) {
1657 next.frozenBeforeDestroy = true;
1658 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001659 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001660 }
1661 }
1662 if (!updated) {
1663 // The configuration update wasn't able to keep the existing
1664 // instance of the activity, and instead started a new one.
1665 // We should be all done, but let's just make sure our activity
1666 // is still at the top and schedule another run if something
1667 // weird happened.
1668 ActivityRecord nextNext = topRunningActivityLocked(null);
1669 if (DEBUG_SWITCH) Slog.i(TAG,
1670 "Activity config changed during resume: " + next
1671 + ", new next: " + nextNext);
1672 if (nextNext != next) {
1673 // Do over!
1674 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1675 }
1676 if (mMainStack) {
1677 mService.setFocusedActivityLocked(next);
1678 }
1679 ensureActivitiesVisibleLocked(null, 0);
1680 mService.mWindowManager.executeAppTransition();
1681 mNoAnimActivities.clear();
1682 return true;
1683 }
1684
1685 try {
1686 // Deliver all pending results.
1687 ArrayList a = next.results;
1688 if (a != null) {
1689 final int N = a.size();
1690 if (!next.finishing && N > 0) {
1691 if (DEBUG_RESULTS) Slog.v(
1692 TAG, "Delivering results to " + next
1693 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001694 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001695 }
1696 }
1697
1698 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001699 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001700 }
1701
1702 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1703 System.identityHashCode(next),
1704 next.task.taskId, next.shortComponentName);
1705
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001706 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001707 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001708 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001709 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 mService.isNextTransitionForward());
1711
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001712 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001713
1714 } catch (Exception e) {
1715 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001716 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1717 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001718 next.state = lastState;
1719 mResumedActivity = lastResumedActivity;
1720 Slog.i(TAG, "Restarting because process died: " + next);
1721 if (!next.hasBeenLaunched) {
1722 next.hasBeenLaunched = true;
1723 } else {
1724 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1725 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001726 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001727 mService.compatibilityInfoForPackageLocked(
1728 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001730 next.labelRes, next.icon, next.windowFlags,
1731 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001732 }
1733 }
1734 startSpecificActivityLocked(next, true, false);
1735 return true;
1736 }
1737
1738 // From this point on, if something goes wrong there is no way
1739 // to recover the activity.
1740 try {
1741 next.visible = true;
1742 completeResumeLocked(next);
1743 } catch (Exception e) {
1744 // If any exception gets thrown, toss away this
1745 // activity and try the next one.
1746 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001747 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001748 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001749 return true;
1750 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001751 next.stopped = false;
1752
1753 } else {
1754 // Whoops, need to restart this activity!
1755 if (!next.hasBeenLaunched) {
1756 next.hasBeenLaunched = true;
1757 } else {
1758 if (SHOW_APP_STARTING_PREVIEW) {
1759 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001760 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001761 mService.compatibilityInfoForPackageLocked(
1762 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001764 next.labelRes, next.icon, next.windowFlags,
1765 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001766 }
1767 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1768 }
1769 startSpecificActivityLocked(next, true, true);
1770 }
1771
1772 return true;
1773 }
1774
1775 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001776 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001777 final int NH = mHistory.size();
1778
1779 int addPos = -1;
1780
1781 if (!newTask) {
1782 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 boolean startIt = true;
1784 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001785 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 if (p.finishing) {
1787 continue;
1788 }
1789 if (p.task == r.task) {
1790 // Here it is! Now, if this is not yet visible to the
1791 // user, then just add it without starting; it will
1792 // get started when the user navigates back to it.
1793 addPos = i+1;
1794 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001795 if (DEBUG_ADD_REMOVE) {
1796 RuntimeException here = new RuntimeException("here");
1797 here.fillInStackTrace();
1798 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1799 here);
1800 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001801 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001802 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001803 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001804 r.info.screenOrientation, r.fullscreen);
1805 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001806 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001807 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001808 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 return;
1810 }
1811 break;
1812 }
1813 if (p.fullscreen) {
1814 startIt = false;
1815 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001816 }
1817 }
1818
1819 // Place a new activity at top of stack, so it is next to interact
1820 // with the user.
1821 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001822 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001823 }
1824
1825 // If we are not placing the new activity frontmost, we do not want
1826 // to deliver the onUserLeaving callback to the actual frontmost
1827 // activity
1828 if (addPos < NH) {
1829 mUserLeaving = false;
1830 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1831 }
1832
1833 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001834 if (DEBUG_ADD_REMOVE) {
1835 RuntimeException here = new RuntimeException("here");
1836 here.fillInStackTrace();
1837 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1838 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001839 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001840 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001841 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001842 if (NH > 0) {
1843 // We want to show the starting preview window if we are
1844 // switching to a new task, or the next activity's process is
1845 // not currently running.
1846 boolean showStartingIcon = newTask;
1847 ProcessRecord proc = r.app;
1848 if (proc == null) {
1849 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1850 }
1851 if (proc == null || proc.thread == null) {
1852 showStartingIcon = true;
1853 }
1854 if (DEBUG_TRANSITION) Slog.v(TAG,
1855 "Prepare open transition: starting " + r);
1856 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001857 mService.mWindowManager.prepareAppTransition(
1858 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001859 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001860 } else {
1861 mService.mWindowManager.prepareAppTransition(newTask
1862 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001863 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001864 mNoAnimActivities.remove(r);
1865 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001866 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001867 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001868 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 boolean doShow = true;
1870 if (newTask) {
1871 // Even though this activity is starting fresh, we still need
1872 // to reset it to make sure we apply affinities to move any
1873 // existing activities from other tasks in to it.
1874 // If the caller has requested that the target task be
1875 // reset, then do so.
1876 if ((r.intent.getFlags()
1877 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1878 resetTaskIfNeededLocked(r, r);
1879 doShow = topRunningNonDelayedActivityLocked(null) == r;
1880 }
1881 }
1882 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1883 // Figure out if we are transitioning from another activity that is
1884 // "has the same starting icon" as the next one. This allows the
1885 // window manager to keep the previous window it had previously
1886 // created, if it still had one.
1887 ActivityRecord prev = mResumedActivity;
1888 if (prev != null) {
1889 // We don't want to reuse the previous starting preview if:
1890 // (1) The current activity is in a different task.
1891 if (prev.task != r.task) prev = null;
1892 // (2) The current activity is already displayed.
1893 else if (prev.nowVisible) prev = null;
1894 }
1895 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001896 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001897 mService.compatibilityInfoForPackageLocked(
1898 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001899 r.labelRes, r.icon, r.windowFlags,
1900 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001901 }
1902 } else {
1903 // If this is the first activity, don't do any fancy animations,
1904 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001905 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001906 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001907 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001908 }
1909 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001910 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 }
1912
1913 if (doResume) {
1914 resumeTopActivityLocked(null);
1915 }
1916 }
1917
Dianne Hackbornbe707852011-11-11 14:32:10 -08001918 final void validateAppTokensLocked() {
1919 mValidateAppTokens.clear();
1920 mValidateAppTokens.ensureCapacity(mHistory.size());
1921 for (int i=0; i<mHistory.size(); i++) {
1922 mValidateAppTokens.add(mHistory.get(i).appToken);
1923 }
1924 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1925 }
1926
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001927 /**
1928 * Perform a reset of the given task, if needed as part of launching it.
1929 * Returns the new HistoryRecord at the top of the task.
1930 */
1931 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1932 ActivityRecord newActivity) {
1933 boolean forceReset = (newActivity.info.flags
1934 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001935 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1936 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001937 if ((newActivity.info.flags
1938 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1939 forceReset = true;
1940 }
1941 }
1942
1943 final TaskRecord task = taskTop.task;
1944
1945 // We are going to move through the history list so that we can look
1946 // at each activity 'target' with 'below' either the interesting
1947 // activity immediately below it in the stack or null.
1948 ActivityRecord target = null;
1949 int targetI = 0;
1950 int taskTopI = -1;
1951 int replyChainEnd = -1;
1952 int lastReparentPos = -1;
1953 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001954 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001955
1956 if (below != null && below.finishing) {
1957 continue;
1958 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001959 // Don't check any lower in the stack if we're crossing a user boundary.
1960 if (below != null && below.userId != taskTop.userId) {
1961 break;
1962 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001963 if (target == null) {
1964 target = below;
1965 targetI = i;
1966 // If we were in the middle of a reply chain before this
1967 // task, it doesn't appear like the root of the chain wants
1968 // anything interesting, so drop it.
1969 replyChainEnd = -1;
1970 continue;
1971 }
1972
1973 final int flags = target.info.flags;
1974
1975 final boolean finishOnTaskLaunch =
1976 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1977 final boolean allowTaskReparenting =
1978 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1979
1980 if (target.task == task) {
1981 // We are inside of the task being reset... we'll either
1982 // finish this activity, push it out for another task,
1983 // or leave it as-is. We only do this
1984 // for activities that are not the root of the task (since
1985 // if we finish the root, we may no longer have the task!).
1986 if (taskTopI < 0) {
1987 taskTopI = targetI;
1988 }
1989 if (below != null && below.task == task) {
1990 final boolean clearWhenTaskReset =
1991 (target.intent.getFlags()
1992 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1993 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1994 // If this activity is sending a reply to a previous
1995 // activity, we can't do anything with it now until
1996 // we reach the start of the reply chain.
1997 // XXX note that we are assuming the result is always
1998 // to the previous activity, which is almost always
1999 // the case but we really shouldn't count on.
2000 if (replyChainEnd < 0) {
2001 replyChainEnd = targetI;
2002 }
2003 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2004 && target.taskAffinity != null
2005 && !target.taskAffinity.equals(task.affinity)) {
2006 // If this activity has an affinity for another
2007 // task, then we need to move it out of here. We will
2008 // move it as far out of the way as possible, to the
2009 // bottom of the activity stack. This also keeps it
2010 // correctly ordered with any activities we previously
2011 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002012 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002013 if (target.taskAffinity != null
2014 && target.taskAffinity.equals(p.task.affinity)) {
2015 // If the activity currently at the bottom has the
2016 // same task affinity as the one we are moving,
2017 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002018 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2020 + " out to bottom task " + p.task);
2021 } else {
2022 mService.mCurTask++;
2023 if (mService.mCurTask <= 0) {
2024 mService.mCurTask = 1;
2025 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002026 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2027 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002028 target.task.affinityIntent = target.intent;
2029 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2030 + " out to new task " + target.task);
2031 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002032 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002033 if (replyChainEnd < 0) {
2034 replyChainEnd = targetI;
2035 }
2036 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002037 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002038 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002039 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002040 if (p.finishing) {
2041 continue;
2042 }
2043 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2044 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002045 p.setTask(target.task, curThumbHolder, false);
2046 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002047 if (DEBUG_ADD_REMOVE) {
2048 RuntimeException here = new RuntimeException("here");
2049 here.fillInStackTrace();
2050 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2051 + dstPos, here);
2052 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002053 mHistory.remove(srcPos);
2054 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002055 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2056 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002057 dstPos++;
2058 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002059 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002060 }
2061 i++;
2062 }
2063 if (taskTop == p) {
2064 taskTop = below;
2065 }
2066 if (taskTopI == replyChainEnd) {
2067 taskTopI = -1;
2068 }
2069 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002070 } else if (forceReset || finishOnTaskLaunch
2071 || clearWhenTaskReset) {
2072 // If the activity should just be removed -- either
2073 // because it asks for it, or the task should be
2074 // cleared -- then finish it and anything that is
2075 // part of its reply chain.
2076 if (clearWhenTaskReset) {
2077 // In this case, we want to finish this activity
2078 // and everything above it, so be sneaky and pretend
2079 // like these are all in the reply chain.
2080 replyChainEnd = targetI+1;
2081 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002082 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083 replyChainEnd)).task == task) {
2084 replyChainEnd++;
2085 }
2086 replyChainEnd--;
2087 } else if (replyChainEnd < 0) {
2088 replyChainEnd = targetI;
2089 }
2090 ActivityRecord p = null;
2091 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002092 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002093 if (p.finishing) {
2094 continue;
2095 }
2096 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002097 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002098 replyChainEnd--;
2099 srcPos--;
2100 }
2101 }
2102 if (taskTop == p) {
2103 taskTop = below;
2104 }
2105 if (taskTopI == replyChainEnd) {
2106 taskTopI = -1;
2107 }
2108 replyChainEnd = -1;
2109 } else {
2110 // If we were in the middle of a chain, well the
2111 // activity that started it all doesn't want anything
2112 // special, so leave it all as-is.
2113 replyChainEnd = -1;
2114 }
2115 } else {
2116 // Reached the bottom of the task -- any reply chain
2117 // should be left as-is.
2118 replyChainEnd = -1;
2119 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002120
2121 } else if (target.resultTo != null && (below == null
2122 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002123 // If this activity is sending a reply to a previous
2124 // activity, we can't do anything with it now until
2125 // we reach the start of the reply chain.
2126 // XXX note that we are assuming the result is always
2127 // to the previous activity, which is almost always
2128 // the case but we really shouldn't count on.
2129 if (replyChainEnd < 0) {
2130 replyChainEnd = targetI;
2131 }
2132
2133 } else if (taskTopI >= 0 && allowTaskReparenting
2134 && task.affinity != null
2135 && task.affinity.equals(target.taskAffinity)) {
2136 // We are inside of another task... if this activity has
2137 // an affinity for our task, then either remove it if we are
2138 // clearing or move it over to our task. Note that
2139 // we currently punt on the case where we are resetting a
2140 // task that is not at the top but who has activities above
2141 // with an affinity to it... this is really not a normal
2142 // case, and we will need to later pull that task to the front
2143 // and usually at that point we will do the reset and pick
2144 // up those remaining activities. (This only happens if
2145 // someone starts an activity in a new task from an activity
2146 // in a task that is not currently on top.)
2147 if (forceReset || finishOnTaskLaunch) {
2148 if (replyChainEnd < 0) {
2149 replyChainEnd = targetI;
2150 }
2151 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002152 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2153 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002154 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002155 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002156 if (p.finishing) {
2157 continue;
2158 }
2159 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002160 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002161 taskTopI--;
2162 lastReparentPos--;
2163 replyChainEnd--;
2164 srcPos--;
2165 }
2166 }
2167 replyChainEnd = -1;
2168 } else {
2169 if (replyChainEnd < 0) {
2170 replyChainEnd = targetI;
2171 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002172 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2173 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002174 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002175 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002176 if (p.finishing) {
2177 continue;
2178 }
2179 if (lastReparentPos < 0) {
2180 lastReparentPos = taskTopI;
2181 taskTop = p;
2182 } else {
2183 lastReparentPos--;
2184 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002185 if (DEBUG_ADD_REMOVE) {
2186 RuntimeException here = new RuntimeException("here");
2187 here.fillInStackTrace();
2188 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2189 + lastReparentPos, here);
2190 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002191 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002192 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002193 mHistory.add(lastReparentPos, p);
2194 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002195 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002196 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002197 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2198 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002199 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002200 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002201 }
2202 }
2203 replyChainEnd = -1;
2204
2205 // Now we've moved it in to place... but what if this is
2206 // a singleTop activity and we have put it on top of another
2207 // instance of the same activity? Then we drop the instance
2208 // below so it remains singleTop.
2209 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2210 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002211 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002212 if (p.finishing) {
2213 continue;
2214 }
2215 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2216 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002217 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002218 taskTopI--;
2219 lastReparentPos--;
2220 }
2221 }
2222 }
2223 }
2224 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002225
2226 } else if (below != null && below.task != target.task) {
2227 // We hit the botton of a task; the reply chain can't
2228 // pass through it.
2229 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002230 }
2231
2232 target = below;
2233 targetI = i;
2234 }
2235
2236 return taskTop;
2237 }
2238
2239 /**
2240 * Perform clear operation as requested by
2241 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2242 * stack to the given task, then look for
2243 * an instance of that activity in the stack and, if found, finish all
2244 * activities on top of it and return the instance.
2245 *
2246 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002247 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002248 * or null if none was found.
2249 */
2250 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002251 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002252 int i = mHistory.size();
2253
2254 // First find the requested task.
2255 while (i > 0) {
2256 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002257 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002258 if (r.task.taskId == taskId) {
2259 i++;
2260 break;
2261 }
2262 }
2263
2264 // Now clear it.
2265 while (i > 0) {
2266 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002267 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002268 if (r.finishing) {
2269 continue;
2270 }
2271 if (r.task.taskId != taskId) {
2272 return null;
2273 }
2274 if (r.realActivity.equals(newR.realActivity)) {
2275 // Here it is! Now finish everything in front...
2276 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002277 while (i < (mHistory.size()-1)) {
2278 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002279 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002280 if (r.task.taskId != taskId) {
2281 break;
2282 }
2283 if (r.finishing) {
2284 continue;
2285 }
2286 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002287 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002288 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002289 }
2290 }
2291
2292 // Finally, if this is a normal launch mode (that is, not
2293 // expecting onNewIntent()), then we will finish the current
2294 // instance of the activity so a new fresh one can be started.
2295 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2296 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2297 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002298 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002299 if (index >= 0) {
2300 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002301 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002302 }
2303 return null;
2304 }
2305 }
2306
2307 return ret;
2308 }
2309 }
2310
2311 return null;
2312 }
2313
2314 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002315 * Completely remove all activities associated with an existing
2316 * task starting at a specified index.
2317 */
2318 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002319 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002320 ActivityRecord r = mHistory.get(i);
2321 if (r.task.taskId != taskId) {
2322 // Whoops hit the end.
2323 return;
2324 }
2325 if (r.finishing) {
2326 i++;
2327 continue;
2328 }
2329 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002330 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002331 i++;
2332 }
2333 }
2334 }
2335
2336 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002337 * Completely remove all activities associated with an existing task.
2338 */
2339 private final void performClearTaskLocked(int taskId) {
2340 int i = mHistory.size();
2341
2342 // First find the requested task.
2343 while (i > 0) {
2344 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002345 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002346 if (r.task.taskId == taskId) {
2347 i++;
2348 break;
2349 }
2350 }
2351
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002352 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002353 while (i > 0) {
2354 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002355 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002356 if (r.finishing) {
2357 continue;
2358 }
2359 if (r.task.taskId != taskId) {
2360 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002361 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002362 return;
2363 }
2364 }
2365 }
2366
2367 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002368 * Find the activity in the history stack within the given task. Returns
2369 * the index within the history at which it's found, or < 0 if not found.
2370 */
2371 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2372 int i = mHistory.size();
2373 while (i > 0) {
2374 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002375 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002376 if (candidate.finishing) {
2377 continue;
2378 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002379 if (candidate.task.taskId != task) {
2380 break;
2381 }
2382 if (candidate.realActivity.equals(r.realActivity)) {
2383 return i;
2384 }
2385 }
2386
2387 return -1;
2388 }
2389
2390 /**
2391 * Reorder the history stack so that the activity at the given index is
2392 * brought to the front.
2393 */
2394 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002395 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002396 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002397 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002398 if (DEBUG_ADD_REMOVE) {
2399 RuntimeException here = new RuntimeException("here");
2400 here.fillInStackTrace();
2401 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2402 + top, here);
2403 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002404 mHistory.add(top, newTop);
2405 oldTop.frontOfTask = false;
2406 newTop.frontOfTask = true;
2407 return newTop;
2408 }
2409
2410 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002411 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002412 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002413 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002414 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002415
Dianne Hackborna4972e92012-03-14 10:38:05 -07002416 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002417
2418 ProcessRecord callerApp = null;
2419 if (caller != null) {
2420 callerApp = mService.getRecordForAppLocked(caller);
2421 if (callerApp != null) {
2422 callingPid = callerApp.pid;
2423 callingUid = callerApp.info.uid;
2424 } else {
2425 Slog.w(TAG, "Unable to find app for caller " + caller
2426 + " (pid=" + callingPid + ") when starting: "
2427 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002428 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002429 }
2430 }
2431
Dianne Hackborna4972e92012-03-14 10:38:05 -07002432 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002433 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002434 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002435 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002436 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002437
2438 ActivityRecord sourceRecord = null;
2439 ActivityRecord resultRecord = null;
2440 if (resultTo != null) {
2441 int index = indexOfTokenLocked(resultTo);
2442 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002443 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002444 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002445 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002446 if (requestCode >= 0 && !sourceRecord.finishing) {
2447 resultRecord = sourceRecord;
2448 }
2449 }
2450 }
2451
2452 int launchFlags = intent.getFlags();
2453
2454 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2455 && sourceRecord != null) {
2456 // Transfer the result target from the source activity to the new
2457 // one being started, including any failures.
2458 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002459 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002460 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002461 }
2462 resultRecord = sourceRecord.resultTo;
2463 resultWho = sourceRecord.resultWho;
2464 requestCode = sourceRecord.requestCode;
2465 sourceRecord.resultTo = null;
2466 if (resultRecord != null) {
2467 resultRecord.removeResultsLocked(
2468 sourceRecord, resultWho, requestCode);
2469 }
2470 }
2471
Dianne Hackborna4972e92012-03-14 10:38:05 -07002472 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002473 // We couldn't find a class that can handle the given Intent.
2474 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002475 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002476 }
2477
Dianne Hackborna4972e92012-03-14 10:38:05 -07002478 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002479 // We couldn't find the specific class specified in the Intent.
2480 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002481 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002482 }
2483
Dianne Hackborna4972e92012-03-14 10:38:05 -07002484 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 if (resultRecord != null) {
2486 sendActivityResultLocked(-1,
2487 resultRecord, resultWho, requestCode,
2488 Activity.RESULT_CANCELED, null);
2489 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002490 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002491 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 return err;
2493 }
2494
Jeff Sharkey35be7562012-04-18 19:16:15 -07002495 final int startAnyPerm = mService.checkPermission(
2496 START_ANY_ACTIVITY, callingPid, callingUid);
2497 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002498 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002499 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 if (resultRecord != null) {
2501 sendActivityResultLocked(-1,
2502 resultRecord, resultWho, requestCode,
2503 Activity.RESULT_CANCELED, null);
2504 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002505 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002506 String msg;
2507 if (!aInfo.exported) {
2508 msg = "Permission Denial: starting " + intent.toString()
2509 + " from " + callerApp + " (pid=" + callingPid
2510 + ", uid=" + callingUid + ")"
2511 + " not exported from uid " + aInfo.applicationInfo.uid;
2512 } else {
2513 msg = "Permission Denial: starting " + intent.toString()
2514 + " from " + callerApp + " (pid=" + callingPid
2515 + ", uid=" + callingUid + ")"
2516 + " requires " + aInfo.permission;
2517 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002518 Slog.w(TAG, msg);
2519 throw new SecurityException(msg);
2520 }
2521
2522 if (mMainStack) {
2523 if (mService.mController != null) {
2524 boolean abort = false;
2525 try {
2526 // The Intent we give to the watcher has the extra data
2527 // stripped off, since it can contain private information.
2528 Intent watchIntent = intent.cloneFilter();
2529 abort = !mService.mController.activityStarting(watchIntent,
2530 aInfo.applicationInfo.packageName);
2531 } catch (RemoteException e) {
2532 mService.mController = null;
2533 }
2534
2535 if (abort) {
2536 if (resultRecord != null) {
2537 sendActivityResultLocked(-1,
2538 resultRecord, resultWho, requestCode,
2539 Activity.RESULT_CANCELED, null);
2540 }
2541 // We pretend to the caller that it was really started, but
2542 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002543 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002544 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002545 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002546 }
2547 }
2548 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002549
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002550 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2551 intent, resolvedType, aInfo, mService.mConfiguration,
2552 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002553 if (outActivity != null) {
2554 outActivity[0] = r;
2555 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002556
2557 if (mMainStack) {
2558 if (mResumedActivity == null
2559 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2560 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2561 PendingActivityLaunch pal = new PendingActivityLaunch();
2562 pal.r = r;
2563 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002564 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002566 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002567 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002568 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002569 }
2570 }
2571
2572 if (mService.mDidAppSwitch) {
2573 // This is the second allowed switch since we stopped switches,
2574 // so now just generally allow switches. Use case: user presses
2575 // home (switches disabled, switch to home, mDidAppSwitch now true);
2576 // user taps a home icon (coming from home so allowed, we hit here
2577 // and now allow anyone to switch again).
2578 mService.mAppSwitchesAllowedTime = 0;
2579 } else {
2580 mService.mDidAppSwitch = true;
2581 }
2582
2583 mService.doPendingActivityLaunchesLocked(false);
2584 }
2585
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002586 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002587 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002588 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002589 // Someone asked to have the keyguard dismissed on the next
2590 // activity start, but we are not actually doing an activity
2591 // switch... just dismiss the keyguard now, because we
2592 // probably want to see whatever is behind it.
2593 mDismissKeyguardOnNextActivity = false;
2594 mService.mWindowManager.dismissKeyguard();
2595 }
2596 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002597 }
2598
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002599 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2600 if ((launchFlags &
2601 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2602 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2603 // Caller wants to appear on home activity, so before starting
2604 // their own activity we will bring home to the front.
2605 moveHomeToFrontLocked();
2606 }
2607 }
2608
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002609 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002610 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2611 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002612 final Intent intent = r.intent;
2613 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002614 final int userId = r.userId;
2615
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002616 int launchFlags = intent.getFlags();
2617
2618 // We'll invoke onUserLeaving before onPause only if the launching
2619 // activity did not explicitly state that this is an automated launch.
2620 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2621 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2622 "startActivity() => mUserLeaving=" + mUserLeaving);
2623
2624 // If the caller has asked not to resume at this point, we make note
2625 // of this in the record so that we can skip it when trying to find
2626 // the top running activity.
2627 if (!doResume) {
2628 r.delayedResume = true;
2629 }
2630
2631 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2632 != 0 ? r : null;
2633
2634 // If the onlyIfNeeded flag is set, then we can do this if the activity
2635 // being launched is the same as the one making the call... or, as
2636 // a special case, if we do not know the caller then we count the
2637 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002638 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002639 ActivityRecord checkedCaller = sourceRecord;
2640 if (checkedCaller == null) {
2641 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2642 }
2643 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2644 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002645 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002646 }
2647 }
2648
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002649 if (sourceRecord == null) {
2650 // This activity is not being started from another... in this
2651 // case we -always- start a new task.
2652 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2653 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2654 + intent);
2655 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2656 }
2657 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2658 // The original activity who is starting us is running as a single
2659 // instance... this new activity it is starting must go on its
2660 // own task.
2661 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2662 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2663 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2664 // The activity being started is a single instance... it always
2665 // gets launched into its own task.
2666 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2667 }
2668
2669 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2670 // For whatever reason this activity is being launched into a new
2671 // task... yet the caller has requested a result back. Well, that
2672 // is pretty messed up, so instead immediately send back a cancel
2673 // and let the new task continue launched as normal without a
2674 // dependency on its originator.
2675 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2676 sendActivityResultLocked(-1,
2677 r.resultTo, r.resultWho, r.requestCode,
2678 Activity.RESULT_CANCELED, null);
2679 r.resultTo = null;
2680 }
2681
2682 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002683 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002684 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002685 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2686 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2687 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2688 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2689 // If bring to front is requested, and no result is requested, and
2690 // we can find a task that was started with this same
2691 // component, then instead of launching bring that one to the front.
2692 if (r.resultTo == null) {
2693 // See if there is a task to bring to the front. If this is
2694 // a SINGLE_INSTANCE activity, there can be one and only one
2695 // instance of it in the history, and it is always in its own
2696 // unique task, so we do a special search.
2697 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2698 ? findTaskLocked(intent, r.info)
2699 : findActivityLocked(intent, r.info);
2700 if (taskTop != null) {
2701 if (taskTop.task.intent == null) {
2702 // This task was started because of movement of
2703 // the activity based on affinity... now that we
2704 // are actually launching it, we can assign the
2705 // base intent.
2706 taskTop.task.setIntent(intent, r.info);
2707 }
2708 // If the target task is not in the front, then we need
2709 // to bring it to the front... except... well, with
2710 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2711 // to have the same behavior as if a new instance was
2712 // being started, which means not bringing it to the front
2713 // if the caller is not itself in the front.
2714 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002715 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002716 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2717 boolean callerAtFront = sourceRecord == null
2718 || curTop.task == sourceRecord.task;
2719 if (callerAtFront) {
2720 // We really do want to push this one into the
2721 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002722 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002723 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002724 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002725 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002726 }
2727 }
2728 // If the caller has requested that the target task be
2729 // reset, then do so.
2730 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2731 taskTop = resetTaskIfNeededLocked(taskTop, r);
2732 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002733 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002734 // We don't need to start a new activity, and
2735 // the client said not to do anything if that
2736 // is the case, so this is it! And for paranoia, make
2737 // sure we have correctly resumed the top activity.
2738 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002739 resumeTopActivityLocked(null, options);
2740 } else {
2741 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002742 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002743 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002744 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002745 if ((launchFlags &
2746 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2747 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2748 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002749 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002750 // not be too hard...
2751 reuseTask = taskTop.task;
2752 performClearTaskLocked(taskTop.task.taskId);
2753 reuseTask.setIntent(r.intent, r.info);
2754 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002755 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2756 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2757 // In this situation we want to remove all activities
2758 // from the task up to the one being started. In most
2759 // cases this means we are resetting the task to its
2760 // initial state.
2761 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002762 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002763 if (top != null) {
2764 if (top.frontOfTask) {
2765 // Activity aliases may mean we use different
2766 // intents for the top activity, so make sure
2767 // the task now has the identity of the new
2768 // intent.
2769 top.task.setIntent(r.intent, r.info);
2770 }
2771 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002772 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002773 } else {
2774 // A special case: we need to
2775 // start the activity because it is not currently
2776 // running, and the caller has asked to clear the
2777 // current task to have this activity at the top.
2778 addingToTask = true;
2779 // Now pretend like this activity is being started
2780 // by the top of its task, so it is put in the
2781 // right place.
2782 sourceRecord = taskTop;
2783 }
2784 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2785 // In this case the top activity on the task is the
2786 // same as the one being launched, so we take that
2787 // as a request to bring the task to the foreground.
2788 // If the top activity in the task is the root
2789 // activity, deliver this new intent to it if it
2790 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002791 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2792 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002793 && taskTop.realActivity.equals(r.realActivity)) {
2794 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2795 if (taskTop.frontOfTask) {
2796 taskTop.task.setIntent(r.intent, r.info);
2797 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002798 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002799 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2800 // In this case we are launching the root activity
2801 // of the task, but with a different intent. We
2802 // should start a new instance on top.
2803 addingToTask = true;
2804 sourceRecord = taskTop;
2805 }
2806 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2807 // In this case an activity is being launched in to an
2808 // existing task, without resetting that task. This
2809 // is typically the situation of launching an activity
2810 // from a notification or shortcut. We want to place
2811 // the new activity on top of the current task.
2812 addingToTask = true;
2813 sourceRecord = taskTop;
2814 } else if (!taskTop.task.rootWasReset) {
2815 // In this case we are launching in to an existing task
2816 // that has not yet been started from its front door.
2817 // The current task has been brought to the front.
2818 // Ideally, we'd probably like to place this new task
2819 // at the bottom of its stack, but that's a little hard
2820 // to do with the current organization of the code so
2821 // for now we'll just drop it.
2822 taskTop.task.setIntent(r.intent, r.info);
2823 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002824 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002825 // We didn't do anything... but it was needed (a.k.a., client
2826 // don't use that intent!) And for paranoia, make
2827 // sure we have correctly resumed the top activity.
2828 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002829 resumeTopActivityLocked(null, options);
2830 } else {
2831 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002832 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002833 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 }
2835 }
2836 }
2837 }
2838
2839 //String uri = r.intent.toURI();
2840 //Intent intent2 = new Intent(uri);
2841 //Slog.i(TAG, "Given intent: " + r.intent);
2842 //Slog.i(TAG, "URI is: " + uri);
2843 //Slog.i(TAG, "To intent: " + intent2);
2844
2845 if (r.packageName != null) {
2846 // If the activity being launched is the same as the one currently
2847 // at the top, then we need to check if it should only be launched
2848 // once.
2849 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2850 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002851 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 if (top.app != null && top.app.thread != null) {
2853 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2854 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2855 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2856 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2857 // For paranoia, make sure we have correctly
2858 // resumed the top activity.
2859 if (doResume) {
2860 resumeTopActivityLocked(null);
2861 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002862 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002863 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002864 // We don't need to start a new activity, and
2865 // the client said not to do anything if that
2866 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002867 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002869 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002870 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002871 }
2872 }
2873 }
2874 }
2875
2876 } else {
2877 if (r.resultTo != null) {
2878 sendActivityResultLocked(-1,
2879 r.resultTo, r.resultWho, r.requestCode,
2880 Activity.RESULT_CANCELED, null);
2881 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002882 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002883 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002884 }
2885
2886 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002887 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002888
2889 // Should this be considered a new task?
2890 if (r.resultTo == null && !addingToTask
2891 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002892 if (reuseTask == null) {
2893 // todo: should do better management of integers.
2894 mService.mCurTask++;
2895 if (mService.mCurTask <= 0) {
2896 mService.mCurTask = 1;
2897 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002898 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002899 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2900 + " in new task " + r.task);
2901 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002902 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002903 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002904 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002905 if (!movedHome) {
2906 moveHomeToFrontFromLaunchLocked(launchFlags);
2907 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908
2909 } else if (sourceRecord != null) {
2910 if (!addingToTask &&
2911 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2912 // In this case, we are adding the activity to an existing
2913 // task, but the caller has asked to clear that task if the
2914 // activity is already running.
2915 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002916 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002917 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002918 if (top != null) {
2919 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002920 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002921 // For paranoia, make sure we have correctly
2922 // resumed the top activity.
2923 if (doResume) {
2924 resumeTopActivityLocked(null);
2925 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002926 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002927 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002928 }
2929 } else if (!addingToTask &&
2930 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2931 // In this case, we are launching an activity in our own task
2932 // that may already be running somewhere in the history, and
2933 // we want to shuffle it to the front of the stack if so.
2934 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2935 if (where >= 0) {
2936 ActivityRecord top = moveActivityToFrontLocked(where);
2937 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002938 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002939 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002940 if (doResume) {
2941 resumeTopActivityLocked(null);
2942 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002943 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002944 }
2945 }
2946 // An existing activity is starting this new activity, so we want
2947 // to keep the new one in the same task as the one that is starting
2948 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002949 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002950 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2951 + " in existing task " + r.task);
2952
2953 } else {
2954 // This not being started from an existing activity, and not part
2955 // of a new task... just put it in the top task, though these days
2956 // this case should never happen.
2957 final int N = mHistory.size();
2958 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002959 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002960 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002961 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002962 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002963 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2964 + " in new guessed " + r.task);
2965 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002966
Dianne Hackborn39792d22010-08-19 18:01:52 -07002967 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002968 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002969
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002970 if (newTask) {
2971 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2972 }
2973 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002974 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002975 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002976 }
2977
Dianne Hackborna4972e92012-03-14 10:38:05 -07002978 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002979 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002980 // Collect information about the target of the Intent.
2981 ActivityInfo aInfo;
2982 try {
2983 ResolveInfo rInfo =
2984 AppGlobals.getPackageManager().resolveIntent(
2985 intent, resolvedType,
2986 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002987 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002988 aInfo = rInfo != null ? rInfo.activityInfo : null;
2989 } catch (RemoteException e) {
2990 aInfo = null;
2991 }
2992
2993 if (aInfo != null) {
2994 // Store the found target back into the intent, because now that
2995 // we have it we never want to do this again. For example, if the
2996 // user navigates back to this point in the history, we should
2997 // always restart the exact same activity.
2998 intent.setComponent(new ComponentName(
2999 aInfo.applicationInfo.packageName, aInfo.name));
3000
3001 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003002 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003003 if (!aInfo.processName.equals("system")) {
3004 mService.setDebugApp(aInfo.processName, true, false);
3005 }
3006 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003007
Dianne Hackborna4972e92012-03-14 10:38:05 -07003008 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003009 if (!aInfo.processName.equals("system")) {
3010 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3011 }
3012 }
3013
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003014 if (profileFile != null) {
3015 if (!aInfo.processName.equals("system")) {
3016 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003017 profileFile, profileFd,
3018 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003019 }
3020 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003021 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003022 return aInfo;
3023 }
3024
3025 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003026 Intent intent, String resolvedType, IBinder resultTo,
3027 String resultWho, int requestCode, int startFlags, String profileFile,
3028 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3029 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003030 // Refuse possible leaked file descriptors
3031 if (intent != null && intent.hasFileDescriptors()) {
3032 throw new IllegalArgumentException("File descriptors passed in Intent");
3033 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003034 boolean componentSpecified = intent.getComponent() != null;
3035
3036 // Don't modify the client's object!
3037 intent = new Intent(intent);
3038
3039 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003040 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003041 profileFile, profileFd, userId);
Amith Yamasania10d1aa2012-08-21 09:49:53 -07003042 if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_MULTIPROCESS) == 0
3043 && mService.isSingleton(aInfo.processName, aInfo.applicationInfo, null, 0)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07003044 userId = 0;
3045 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003046 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003047
3048 synchronized (mService) {
3049 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003050 if (callingUid >= 0) {
3051 callingPid = -1;
3052 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003053 callingPid = Binder.getCallingPid();
3054 callingUid = Binder.getCallingUid();
3055 } else {
3056 callingPid = callingUid = -1;
3057 }
3058
3059 mConfigWillChange = config != null
3060 && mService.mConfiguration.diff(config) != 0;
3061 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3062 "Starting activity when config will change = " + mConfigWillChange);
3063
3064 final long origId = Binder.clearCallingIdentity();
3065
3066 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003067 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003068 // This may be a heavy-weight process! Check to see if we already
3069 // have another, different heavy-weight process running.
3070 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3071 if (mService.mHeavyWeightProcess != null &&
3072 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3073 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3074 int realCallingPid = callingPid;
3075 int realCallingUid = callingUid;
3076 if (caller != null) {
3077 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3078 if (callerApp != null) {
3079 realCallingPid = callerApp.pid;
3080 realCallingUid = callerApp.info.uid;
3081 } else {
3082 Slog.w(TAG, "Unable to find app for caller " + caller
3083 + " (pid=" + realCallingPid + ") when starting: "
3084 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003085 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003086 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003087 }
3088 }
3089
3090 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003091 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003092 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003093 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003094 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003095
3096 Intent newIntent = new Intent();
3097 if (requestCode >= 0) {
3098 // Caller is requesting a result.
3099 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3100 }
3101 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3102 new IntentSender(target));
3103 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3104 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3105 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3106 hist.packageName);
3107 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3108 hist.task.taskId);
3109 }
3110 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3111 aInfo.packageName);
3112 newIntent.setFlags(intent.getFlags());
3113 newIntent.setClassName("android",
3114 HeavyWeightSwitcherActivity.class.getName());
3115 intent = newIntent;
3116 resolvedType = null;
3117 caller = null;
3118 callingUid = Binder.getCallingUid();
3119 callingPid = Binder.getCallingPid();
3120 componentSpecified = true;
3121 try {
3122 ResolveInfo rInfo =
3123 AppGlobals.getPackageManager().resolveIntent(
3124 intent, null,
3125 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003126 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003127 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003128 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003129 } catch (RemoteException e) {
3130 aInfo = null;
3131 }
3132 }
3133 }
3134 }
3135
3136 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003137 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3138 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003139
3140 if (mConfigWillChange && mMainStack) {
3141 // If the caller also wants to switch to a new configuration,
3142 // do so now. This allows a clean switch, as we are waiting
3143 // for the current activity to pause (so we will not destroy
3144 // it), and have not yet started the next activity.
3145 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3146 "updateConfiguration()");
3147 mConfigWillChange = false;
3148 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3149 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003150 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003151 }
3152
3153 Binder.restoreCallingIdentity(origId);
3154
3155 if (outResult != null) {
3156 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003157 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158 mWaitingActivityLaunched.add(outResult);
3159 do {
3160 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003161 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003162 } catch (InterruptedException e) {
3163 }
3164 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003165 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003166 ActivityRecord r = this.topRunningActivityLocked(null);
3167 if (r.nowVisible) {
3168 outResult.timeout = false;
3169 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3170 outResult.totalTime = 0;
3171 outResult.thisTime = 0;
3172 } else {
3173 outResult.thisTime = SystemClock.uptimeMillis();
3174 mWaitingActivityVisible.add(outResult);
3175 do {
3176 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003177 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 } catch (InterruptedException e) {
3179 }
3180 } while (!outResult.timeout && outResult.who == null);
3181 }
3182 }
3183 }
3184
3185 return res;
3186 }
3187 }
3188
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003189 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003190 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3191 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003192 if (intents == null) {
3193 throw new NullPointerException("intents is null");
3194 }
3195 if (resolvedTypes == null) {
3196 throw new NullPointerException("resolvedTypes is null");
3197 }
3198 if (intents.length != resolvedTypes.length) {
3199 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3200 }
3201
3202 ActivityRecord[] outActivity = new ActivityRecord[1];
3203
3204 int callingPid;
3205 if (callingUid >= 0) {
3206 callingPid = -1;
3207 } else if (caller == null) {
3208 callingPid = Binder.getCallingPid();
3209 callingUid = Binder.getCallingUid();
3210 } else {
3211 callingPid = callingUid = -1;
3212 }
3213 final long origId = Binder.clearCallingIdentity();
3214 try {
3215 synchronized (mService) {
3216
3217 for (int i=0; i<intents.length; i++) {
3218 Intent intent = intents[i];
3219 if (intent == null) {
3220 continue;
3221 }
3222
3223 // Refuse possible leaked file descriptors
3224 if (intent != null && intent.hasFileDescriptors()) {
3225 throw new IllegalArgumentException("File descriptors passed in Intent");
3226 }
3227
3228 boolean componentSpecified = intent.getComponent() != null;
3229
3230 // Don't modify the client's object!
3231 intent = new Intent(intent);
3232
3233 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003234 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003235 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003236 // TODO: New, check if this is correct
3237 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003238
3239 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3240 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3241 throw new IllegalArgumentException(
3242 "FLAG_CANT_SAVE_STATE not supported here");
3243 }
3244
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003245 Bundle theseOptions;
3246 if (options != null && i == intents.length-1) {
3247 theseOptions = options;
3248 } else {
3249 theseOptions = null;
3250 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003251 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003252 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003253 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003254 if (res < 0) {
3255 return res;
3256 }
3257
Dianne Hackbornbe707852011-11-11 14:32:10 -08003258 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003259 }
3260 }
3261 } finally {
3262 Binder.restoreCallingIdentity(origId);
3263 }
3264
Dianne Hackborna4972e92012-03-14 10:38:05 -07003265 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003266 }
3267
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003268 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3269 long thisTime, long totalTime) {
3270 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3271 WaitResult w = mWaitingActivityLaunched.get(i);
3272 w.timeout = timeout;
3273 if (r != null) {
3274 w.who = new ComponentName(r.info.packageName, r.info.name);
3275 }
3276 w.thisTime = thisTime;
3277 w.totalTime = totalTime;
3278 }
3279 mService.notifyAll();
3280 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003281
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003282 void reportActivityVisibleLocked(ActivityRecord r) {
3283 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3284 WaitResult w = mWaitingActivityVisible.get(i);
3285 w.timeout = false;
3286 if (r != null) {
3287 w.who = new ComponentName(r.info.packageName, r.info.name);
3288 }
3289 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3290 w.thisTime = w.totalTime;
3291 }
3292 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003293
3294 if (mDismissKeyguardOnNextActivity) {
3295 mDismissKeyguardOnNextActivity = false;
3296 mService.mWindowManager.dismissKeyguard();
3297 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003298 }
3299
3300 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3301 String resultWho, int requestCode, int resultCode, Intent data) {
3302
3303 if (callingUid > 0) {
3304 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003305 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003306 }
3307
3308 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3309 + " : who=" + resultWho + " req=" + requestCode
3310 + " res=" + resultCode + " data=" + data);
3311 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3312 try {
3313 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3314 list.add(new ResultInfo(resultWho, requestCode,
3315 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003316 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003317 return;
3318 } catch (Exception e) {
3319 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3320 }
3321 }
3322
3323 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3324 }
3325
3326 private final void stopActivityLocked(ActivityRecord r) {
3327 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3328 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3329 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3330 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003331 if (!mService.mSleeping) {
3332 if (DEBUG_STATES) {
3333 Slog.d(TAG, "no-history finish of " + r);
3334 }
3335 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003336 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003337 } else {
3338 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3339 + " on stop because we're just sleeping");
3340 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003341 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003342 }
3343
3344 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003345 if (mMainStack) {
3346 if (mService.mFocusedActivity == r) {
3347 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3348 }
3349 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003350 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003351 try {
3352 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003353 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3354 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003355 r.state = ActivityState.STOPPING;
3356 if (DEBUG_VISBILITY) Slog.v(
3357 TAG, "Stopping visible=" + r.visible + " for " + r);
3358 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003359 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003360 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003361 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003362 if (mService.isSleeping()) {
3363 r.setSleeping(true);
3364 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003365 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3366 msg.obj = r;
3367 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003368 } catch (Exception e) {
3369 // Maybe just ignore exceptions here... if the process
3370 // has crashed, our death notification will clean things
3371 // up.
3372 Slog.w(TAG, "Exception thrown during pause", e);
3373 // Just in case, assume it to be stopped.
3374 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003375 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003376 r.state = ActivityState.STOPPED;
3377 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003378 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003379 }
3380 }
3381 }
3382 }
3383
3384 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3385 boolean remove) {
3386 int N = mStoppingActivities.size();
3387 if (N <= 0) return null;
3388
3389 ArrayList<ActivityRecord> stops = null;
3390
3391 final boolean nowVisible = mResumedActivity != null
3392 && mResumedActivity.nowVisible
3393 && !mResumedActivity.waitingVisible;
3394 for (int i=0; i<N; i++) {
3395 ActivityRecord s = mStoppingActivities.get(i);
3396 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3397 + nowVisible + " waitingVisible=" + s.waitingVisible
3398 + " finishing=" + s.finishing);
3399 if (s.waitingVisible && nowVisible) {
3400 mWaitingVisibleActivities.remove(s);
3401 s.waitingVisible = false;
3402 if (s.finishing) {
3403 // If this activity is finishing, it is sitting on top of
3404 // everyone else but we now know it is no longer needed...
3405 // so get rid of it. Otherwise, we need to go through the
3406 // normal flow and hide it once we determine that it is
3407 // hidden by the activities in front of it.
3408 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003409 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003410 }
3411 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003412 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003413 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3414 if (stops == null) {
3415 stops = new ArrayList<ActivityRecord>();
3416 }
3417 stops.add(s);
3418 mStoppingActivities.remove(i);
3419 N--;
3420 i--;
3421 }
3422 }
3423
3424 return stops;
3425 }
3426
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003427 final void scheduleIdleLocked() {
3428 Message msg = Message.obtain();
3429 msg.what = IDLE_NOW_MSG;
3430 mHandler.sendMessage(msg);
3431 }
3432
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003433 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003434 Configuration config) {
3435 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3436
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003437 ActivityRecord res = null;
3438
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003439 ArrayList<ActivityRecord> stops = null;
3440 ArrayList<ActivityRecord> finishes = null;
3441 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003442 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003443 int NS = 0;
3444 int NF = 0;
3445 int NT = 0;
3446 IApplicationThread sendThumbnail = null;
3447 boolean booting = false;
3448 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003449 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003450
3451 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003452 ActivityRecord r = ActivityRecord.forToken(token);
3453 if (r != null) {
3454 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003455 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003456 }
3457
3458 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003459 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003460 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003461 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003462
3463 if (fromTimeout) {
3464 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3465 }
3466
3467 // This is a hack to semi-deal with a race condition
3468 // in the client where it can be constructed with a
3469 // newer configuration from when we asked it to launch.
3470 // We'll update with whatever configuration it now says
3471 // it used to launch.
3472 if (config != null) {
3473 r.configuration = config;
3474 }
3475
3476 // No longer need to keep the device awake.
3477 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3478 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3479 mLaunchingActivity.release();
3480 }
3481
3482 // We are now idle. If someone is waiting for a thumbnail from
3483 // us, we can now deliver.
3484 r.idle = true;
3485 mService.scheduleAppGcsLocked();
3486 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3487 sendThumbnail = r.app.thread;
3488 r.thumbnailNeeded = false;
3489 }
3490
3491 // If this activity is fullscreen, set up to hide those under it.
3492
3493 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3494 ensureActivitiesVisibleLocked(null, 0);
3495
3496 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3497 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003498 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003499 mService.mBooted = true;
3500 enableScreen = true;
3501 }
3502 }
3503
3504 } else if (fromTimeout) {
3505 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3506 }
3507
3508 // Atomically retrieve all of the other things to do.
3509 stops = processStoppingActivitiesLocked(true);
3510 NS = stops != null ? stops.size() : 0;
3511 if ((NF=mFinishingActivities.size()) > 0) {
3512 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3513 mFinishingActivities.clear();
3514 }
3515 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3516 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3517 mService.mCancelledThumbnails.clear();
3518 }
3519
3520 if (mMainStack) {
3521 booting = mService.mBooting;
3522 mService.mBooting = false;
3523 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003524 if (mStartingUsers.size() > 0) {
3525 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3526 mStartingUsers.clear();
3527 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003528 }
3529
3530 int i;
3531
3532 // Send thumbnail if requested.
3533 if (sendThumbnail != null) {
3534 try {
3535 sendThumbnail.requestThumbnail(token);
3536 } catch (Exception e) {
3537 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3538 mService.sendPendingThumbnail(null, token, null, null, true);
3539 }
3540 }
3541
3542 // Stop any activities that are scheduled to do so but have been
3543 // waiting for the next one to start.
3544 for (i=0; i<NS; i++) {
3545 ActivityRecord r = (ActivityRecord)stops.get(i);
3546 synchronized (mService) {
3547 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003548 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003549 } else {
3550 stopActivityLocked(r);
3551 }
3552 }
3553 }
3554
3555 // Finish any activities that are scheduled to do so but have been
3556 // waiting for the next one to start.
3557 for (i=0; i<NF; i++) {
3558 ActivityRecord r = (ActivityRecord)finishes.get(i);
3559 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003560 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003561 }
3562 }
3563
3564 // Report back to any thumbnail receivers.
3565 for (i=0; i<NT; i++) {
3566 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3567 mService.sendPendingThumbnail(r, null, null, null, true);
3568 }
3569
3570 if (booting) {
3571 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003572 } else if (startingUsers != null) {
3573 for (i=0; i<startingUsers.size(); i++) {
3574 mService.finishUserSwitch(startingUsers.get(i));
3575 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003576 }
3577
3578 mService.trimApplications();
3579 //dump();
3580 //mWindowManager.dump();
3581
3582 if (enableScreen) {
3583 mService.enableScreenAfterBoot();
3584 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003585
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003586 if (activityRemoved) {
3587 resumeTopActivityLocked(null);
3588 }
3589
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003590 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003591 }
3592
3593 /**
3594 * @return Returns true if the activity is being finished, false if for
3595 * some reason it is being left as-is.
3596 */
3597 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003598 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003599 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003600 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003601 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003602 + ", result=" + resultCode + ", data=" + resultData
3603 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003604 if (index < 0) {
3605 return false;
3606 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003607 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003608
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003609 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003610 return true;
3611 }
3612
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003613 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3614 ActivityRecord self = isInStackLocked(token);
3615 if (self == null) {
3616 return;
3617 }
3618
3619 int i;
3620 for (i=mHistory.size()-1; i>=0; i--) {
3621 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3622 if (r.resultTo == self && r.requestCode == requestCode) {
3623 if ((r.resultWho == null && resultWho == null) ||
3624 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3625 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003626 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003627 }
3628 }
3629 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003630 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003631 }
3632
3633 final boolean finishActivityAffinityLocked(IBinder token) {
3634 int index = indexOfTokenLocked(token);
3635 if (DEBUG_RESULTS) Slog.v(
3636 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3637 if (index < 0) {
3638 return false;
3639 }
3640 ActivityRecord r = mHistory.get(index);
3641
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003642 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003643 ActivityRecord cur = mHistory.get(index);
3644 if (cur.task != r.task) {
3645 break;
3646 }
3647 if (cur.taskAffinity == null && r.taskAffinity != null) {
3648 break;
3649 }
3650 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3651 break;
3652 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003653 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3654 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003655 index--;
3656 }
3657 return true;
3658 }
3659
Dianne Hackborn5c607432012-02-28 14:44:19 -08003660 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3661 // send the result
3662 ActivityRecord resultTo = r.resultTo;
3663 if (resultTo != null) {
3664 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3665 + " who=" + r.resultWho + " req=" + r.requestCode
3666 + " res=" + resultCode + " data=" + resultData);
3667 if (r.info.applicationInfo.uid > 0) {
3668 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3669 resultTo.packageName, resultData,
3670 resultTo.getUriPermissionsLocked());
3671 }
3672 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3673 resultData);
3674 r.resultTo = null;
3675 }
3676 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3677
3678 // Make sure this HistoryRecord is not holding on to other resources,
3679 // because clients have remote IPC references to this object so we
3680 // can't assume that will go away and want to avoid circular IPC refs.
3681 r.results = null;
3682 r.pendingResults = null;
3683 r.newIntents = null;
3684 r.icicle = null;
3685 }
3686
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003687 /**
3688 * @return Returns true if this activity has been removed from the history
3689 * list, or false if it is still in the list and will be removed later.
3690 */
3691 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003692 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3693 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003694 }
3695
3696 /**
3697 * @return Returns true if this activity has been removed from the history
3698 * list, or false if it is still in the list and will be removed later.
3699 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003700 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3701 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003702 if (r.finishing) {
3703 Slog.w(TAG, "Duplicate finish request for " + r);
3704 return false;
3705 }
3706
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003707 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003708 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3709 System.identityHashCode(r),
3710 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003712 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003713 if (next.task == r.task) {
3714 if (r.frontOfTask) {
3715 // The next activity is now the front of the task.
3716 next.frontOfTask = true;
3717 }
3718 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3719 // If the caller asked that this activity (and all above it)
3720 // be cleared when the task is reset, don't lose that information,
3721 // but propagate it up to the next activity.
3722 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3723 }
3724 }
3725 }
3726
3727 r.pauseKeyDispatchingLocked();
3728 if (mMainStack) {
3729 if (mService.mFocusedActivity == r) {
3730 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3731 }
3732 }
3733
Dianne Hackborn5c607432012-02-28 14:44:19 -08003734 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003735
3736 if (mService.mPendingThumbnails.size() > 0) {
3737 // There are clients waiting to receive thumbnails so, in case
3738 // this is an activity that someone is waiting for, add it
3739 // to the pending list so we can correctly update the clients.
3740 mService.mCancelledThumbnails.add(r);
3741 }
3742
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003743 if (immediate) {
3744 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003745 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003746 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003748 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003749 if (DEBUG_TRANSITION) Slog.v(TAG,
3750 "Prepare close transition: finishing " + r);
3751 mService.mWindowManager.prepareAppTransition(endTask
3752 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003753 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003754
3755 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003756 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003757
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003758 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003759 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3760 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3761 startPausingLocked(false, false);
3762 }
3763
3764 } else if (r.state != ActivityState.PAUSING) {
3765 // If the activity is PAUSING, we will complete the finish once
3766 // it is done pausing; else we can just directly finish it here.
3767 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3768 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003769 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770 } else {
3771 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3772 }
3773
3774 return false;
3775 }
3776
3777 private static final int FINISH_IMMEDIATELY = 0;
3778 private static final int FINISH_AFTER_PAUSE = 1;
3779 private static final int FINISH_AFTER_VISIBLE = 2;
3780
3781 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003782 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003783 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003784 if (index < 0) {
3785 return null;
3786 }
3787
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003788 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003789 }
3790
3791 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003792 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003793 // First things first: if this activity is currently visible,
3794 // and the resumed activity is not yet visible, then hold off on
3795 // finishing until the resumed one becomes visible.
3796 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3797 if (!mStoppingActivities.contains(r)) {
3798 mStoppingActivities.add(r);
3799 if (mStoppingActivities.size() > 3) {
3800 // If we already have a few activities waiting to stop,
3801 // then give up on things going idle and start clearing
3802 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003803 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003804 } else {
3805 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003806 }
3807 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003808 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3809 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003810 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003811 if (oomAdj) {
3812 mService.updateOomAdjLocked();
3813 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003814 return r;
3815 }
3816
3817 // make sure the record is cleaned out of other places.
3818 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003819 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003820 mWaitingVisibleActivities.remove(r);
3821 if (mResumedActivity == r) {
3822 mResumedActivity = null;
3823 }
3824 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003825 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003826 r.state = ActivityState.FINISHING;
3827
3828 if (mode == FINISH_IMMEDIATELY
3829 || prevState == ActivityState.STOPPED
3830 || prevState == ActivityState.INITIALIZING) {
3831 // If this activity is already stopped, we can just finish
3832 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003833 boolean activityRemoved = destroyActivityLocked(r, true,
3834 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003835 if (activityRemoved) {
3836 resumeTopActivityLocked(null);
3837 }
3838 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003839 } else {
3840 // Need to go through the full pause cycle to get this
3841 // activity into the stopped state and then finish it.
3842 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3843 mFinishingActivities.add(r);
3844 resumeTopActivityLocked(null);
3845 }
3846 return r;
3847 }
3848
3849 /**
3850 * Perform the common clean-up of an activity record. This is called both
3851 * as part of destroyActivityLocked() (when destroying the client-side
3852 * representation) and cleaning things up as a result of its hosting
3853 * processing going away, in which case there is no remaining client-side
3854 * state to destroy so only the cleanup here is needed.
3855 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003856 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3857 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003858 if (mResumedActivity == r) {
3859 mResumedActivity = null;
3860 }
3861 if (mService.mFocusedActivity == r) {
3862 mService.mFocusedActivity = null;
3863 }
3864
3865 r.configDestroy = false;
3866 r.frozenBeforeDestroy = false;
3867
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003868 if (setState) {
3869 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3870 r.state = ActivityState.DESTROYED;
3871 }
3872
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003873 // Make sure this record is no longer in the pending finishes list.
3874 // This could happen, for example, if we are trimming activities
3875 // down to the max limit while they are still waiting to finish.
3876 mFinishingActivities.remove(r);
3877 mWaitingVisibleActivities.remove(r);
3878
3879 // Remove any pending results.
3880 if (r.finishing && r.pendingResults != null) {
3881 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3882 PendingIntentRecord rec = apr.get();
3883 if (rec != null) {
3884 mService.cancelIntentSenderLocked(rec, false);
3885 }
3886 }
3887 r.pendingResults = null;
3888 }
3889
3890 if (cleanServices) {
3891 cleanUpActivityServicesLocked(r);
3892 }
3893
3894 if (mService.mPendingThumbnails.size() > 0) {
3895 // There are clients waiting to receive thumbnails so, in case
3896 // this is an activity that someone is waiting for, add it
3897 // to the pending list so we can correctly update the clients.
3898 mService.mCancelledThumbnails.add(r);
3899 }
3900
3901 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003902 removeTimeoutsForActivityLocked(r);
3903 }
3904
3905 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003906 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003907 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003909 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003910 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003911 }
3912
Dianne Hackborn5c607432012-02-28 14:44:19 -08003913 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003914 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003915 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003916 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003917 if (DEBUG_ADD_REMOVE) {
3918 RuntimeException here = new RuntimeException("here");
3919 here.fillInStackTrace();
3920 Slog.i(TAG, "Removing activity " + r + " from stack");
3921 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003922 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003923 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003924 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3925 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003926 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003927 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003928 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003929 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003930 }
3931 cleanUpActivityServicesLocked(r);
3932 r.removeUriPermissionsLocked();
3933 }
3934 }
3935
3936 /**
3937 * Perform clean-up of service connections in an activity record.
3938 */
3939 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3940 // Throw away any services that have been bound by this activity.
3941 if (r.connections != null) {
3942 Iterator<ConnectionRecord> it = r.connections.iterator();
3943 while (it.hasNext()) {
3944 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003945 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003946 }
3947 r.connections = null;
3948 }
3949 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003950
3951 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
3952 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3953 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
3954 mHandler.sendMessage(msg);
3955 }
3956
Dianne Hackborn28695e02011-11-02 21:59:51 -07003957 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003958 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003959 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003960 for (int i=mHistory.size()-1; i>=0; i--) {
3961 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003962 if (r.finishing) {
3963 continue;
3964 }
3965 if (r.fullscreen) {
3966 lastIsOpaque = true;
3967 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003968 if (owner != null && r.app != owner) {
3969 continue;
3970 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003971 if (!lastIsOpaque) {
3972 continue;
3973 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003974 // We can destroy this one if we have its icicle saved and
3975 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003976 if (r.app != null && r != mResumedActivity && r != mPausingActivity
3977 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003978 && r.state != ActivityState.DESTROYING
3979 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003980 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3981 + " resumed=" + mResumedActivity
3982 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003983 if (destroyActivityLocked(r, true, oomAdj, reason)) {
3984 activityRemoved = true;
3985 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003986 }
3987 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003988 if (activityRemoved) {
3989 resumeTopActivityLocked(null);
3990 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003991 }
3992
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003993 /**
3994 * Destroy the current CLIENT SIDE instance of an activity. This may be
3995 * called both when actually finishing an activity, or when performing
3996 * a configuration switch where we destroy the current client-side object
3997 * but then create a new client-side object for this same HistoryRecord.
3998 */
3999 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004000 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004001 if (DEBUG_SWITCH) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004002 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004003 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4004 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
4005 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004006 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004007
4008 boolean removedFromHistory = false;
4009
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004010 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004011
4012 final boolean hadApp = r.app != null;
4013
4014 if (hadApp) {
4015 if (removeFromApp) {
4016 int idx = r.app.activities.indexOf(r);
4017 if (idx >= 0) {
4018 r.app.activities.remove(idx);
4019 }
4020 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4021 mService.mHeavyWeightProcess = null;
4022 mService.mHandler.sendEmptyMessage(
4023 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4024 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004025 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004026 // No longer have activities, so update oom adj.
4027 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004028 }
4029 }
4030
4031 boolean skipDestroy = false;
4032
4033 try {
4034 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004035 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004036 r.configChangeFlags);
4037 } catch (Exception e) {
4038 // We can just ignore exceptions here... if the process
4039 // has crashed, our death notification will clean things
4040 // up.
4041 //Slog.w(TAG, "Exception thrown during finish", e);
4042 if (r.finishing) {
4043 removeActivityFromHistoryLocked(r);
4044 removedFromHistory = true;
4045 skipDestroy = true;
4046 }
4047 }
4048
4049 r.app = null;
4050 r.nowVisible = false;
4051
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004052 // If the activity is finishing, we need to wait on removing it
4053 // from the list to give it a chance to do its cleanup. During
4054 // that time it may make calls back with its token so we need to
4055 // be able to find it on the list and so we don't want to remove
4056 // it from the list yet. Otherwise, we can just immediately put
4057 // it in the destroyed state since we are not removing it from the
4058 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004059 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004060 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4061 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004062 r.state = ActivityState.DESTROYING;
4063 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4064 msg.obj = r;
4065 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4066 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004067 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4068 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004069 r.state = ActivityState.DESTROYED;
4070 }
4071 } else {
4072 // remove this record from the history.
4073 if (r.finishing) {
4074 removeActivityFromHistoryLocked(r);
4075 removedFromHistory = true;
4076 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004077 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4078 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004079 r.state = ActivityState.DESTROYED;
4080 }
4081 }
4082
4083 r.configChangeFlags = 0;
4084
4085 if (!mLRUActivities.remove(r) && hadApp) {
4086 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4087 }
4088
4089 return removedFromHistory;
4090 }
4091
4092 final void activityDestroyed(IBinder token) {
4093 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004094 final long origId = Binder.clearCallingIdentity();
4095 try {
4096 ActivityRecord r = ActivityRecord.forToken(token);
4097 if (r != null) {
4098 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004099 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004100
4101 int index = indexOfActivityLocked(r);
4102 if (index >= 0) {
4103 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004104 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004105 removeActivityFromHistoryLocked(r);
4106 }
4107 }
4108 resumeTopActivityLocked(null);
4109 } finally {
4110 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004111 }
4112 }
4113 }
4114
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004115 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004116 int i = list.size();
4117 if (localLOGV) Slog.v(
4118 TAG, "Removing app " + app + " from list " + list
4119 + " with " + i + " entries");
4120 while (i > 0) {
4121 i--;
4122 ActivityRecord r = (ActivityRecord)list.get(i);
4123 if (localLOGV) Slog.v(
4124 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4125 if (r.app == app) {
4126 if (localLOGV) Slog.v(TAG, "Removing this entry!");
4127 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004128 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004129 }
4130 }
4131 }
4132
4133 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
4134 removeHistoryRecordsForAppLocked(mLRUActivities, app);
4135 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004136 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004137 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
4138 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
4139 }
4140
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004141 /**
4142 * Move the current home activity's task (if one exists) to the front
4143 * of the stack.
4144 */
4145 final void moveHomeToFrontLocked() {
4146 TaskRecord homeTask = null;
4147 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004148 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004149 if (hr.isHomeActivity) {
4150 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004151 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004152 }
4153 }
4154 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004155 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004156 }
4157 }
4158
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004159 final void updateTransitLocked(int transit, Bundle options) {
4160 if (options != null) {
4161 ActivityRecord r = topRunningActivityLocked(null);
4162 if (r != null && r.state != ActivityState.RESUMED) {
4163 r.updateOptionsLocked(options);
4164 } else {
4165 ActivityOptions.abort(options);
4166 }
4167 }
4168 mService.mWindowManager.prepareAppTransition(transit, false);
4169 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004170
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004171 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004172 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4173
4174 final int task = tr.taskId;
4175 int top = mHistory.size()-1;
4176
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004177 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004178 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004179 if (reason != null &&
4180 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4181 ActivityOptions.abort(options);
4182 } else {
4183 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4184 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004185 return;
4186 }
4187
Dianne Hackbornbe707852011-11-11 14:32:10 -08004188 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004189
4190 // Applying the affinities may have removed entries from the history,
4191 // so get the size again.
4192 top = mHistory.size()-1;
4193 int pos = top;
4194
4195 // Shift all activities with this task up to the top
4196 // of the stack, keeping them in the same internal order.
4197 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004198 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004199 if (localLOGV) Slog.v(
4200 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004201 if (r.task.taskId == task) {
4202 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004203 if (DEBUG_ADD_REMOVE) {
4204 RuntimeException here = new RuntimeException("here");
4205 here.fillInStackTrace();
4206 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4207 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004208 mHistory.remove(pos);
4209 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004210 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004211 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004212 }
4213 pos--;
4214 }
4215
4216 if (DEBUG_TRANSITION) Slog.v(TAG,
4217 "Prepare to front transition: task=" + tr);
4218 if (reason != null &&
4219 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004220 mService.mWindowManager.prepareAppTransition(
4221 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004222 ActivityRecord r = topRunningActivityLocked(null);
4223 if (r != null) {
4224 mNoAnimActivities.add(r);
4225 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004226 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004227 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004228 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 }
4230
4231 mService.mWindowManager.moveAppTokensToTop(moved);
4232 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004233 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004234 }
4235
4236 finishTaskMoveLocked(task);
4237 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4238 }
4239
4240 private final void finishTaskMoveLocked(int task) {
4241 resumeTopActivityLocked(null);
4242 }
4243
4244 /**
4245 * Worker method for rearranging history stack. Implements the function of moving all
4246 * activities for a specific task (gathering them if disjoint) into a single group at the
4247 * bottom of the stack.
4248 *
4249 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4250 * to premeptively cancel the move.
4251 *
4252 * @param task The taskId to collect and move to the bottom.
4253 * @return Returns true if the move completed, false if not.
4254 */
4255 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4256 Slog.i(TAG, "moveTaskToBack: " + task);
4257
4258 // If we have a watcher, preflight the move before committing to it. First check
4259 // for *other* available tasks, but if none are available, then try again allowing the
4260 // current task to be selected.
4261 if (mMainStack && mService.mController != null) {
4262 ActivityRecord next = topRunningActivityLocked(null, task);
4263 if (next == null) {
4264 next = topRunningActivityLocked(null, 0);
4265 }
4266 if (next != null) {
4267 // ask watcher if this is allowed
4268 boolean moveOK = true;
4269 try {
4270 moveOK = mService.mController.activityResuming(next.packageName);
4271 } catch (RemoteException e) {
4272 mService.mController = null;
4273 }
4274 if (!moveOK) {
4275 return false;
4276 }
4277 }
4278 }
4279
Dianne Hackbornbe707852011-11-11 14:32:10 -08004280 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004281
4282 if (DEBUG_TRANSITION) Slog.v(TAG,
4283 "Prepare to back transition: task=" + task);
4284
4285 final int N = mHistory.size();
4286 int bottom = 0;
4287 int pos = 0;
4288
4289 // Shift all activities with this task down to the bottom
4290 // of the stack, keeping them in the same internal order.
4291 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004292 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004293 if (localLOGV) Slog.v(
4294 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4295 if (r.task.taskId == task) {
4296 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004297 if (DEBUG_ADD_REMOVE) {
4298 RuntimeException here = new RuntimeException("here");
4299 here.fillInStackTrace();
4300 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4301 + bottom, here);
4302 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004303 mHistory.remove(pos);
4304 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004305 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004306 bottom++;
4307 }
4308 pos++;
4309 }
4310
4311 if (reason != null &&
4312 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004313 mService.mWindowManager.prepareAppTransition(
4314 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004315 ActivityRecord r = topRunningActivityLocked(null);
4316 if (r != null) {
4317 mNoAnimActivities.add(r);
4318 }
4319 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004320 mService.mWindowManager.prepareAppTransition(
4321 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004322 }
4323 mService.mWindowManager.moveAppTokensToBottom(moved);
4324 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004325 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004326 }
4327
4328 finishTaskMoveLocked(task);
4329 return true;
4330 }
4331
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004332 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4333 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4334 ActivityRecord resumed = mResumedActivity;
4335 if (resumed != null && resumed.thumbHolder == tr) {
4336 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4337 } else {
4338 info.mainThumbnail = tr.lastThumbnail;
4339 }
4340 return info;
4341 }
4342
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004343 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4344 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004345 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4346 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004347 if (taskRequired) {
4348 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4349 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004350 return null;
4351 }
4352
4353 if (subTaskIndex < 0) {
4354 // Just remove the entire task.
4355 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4356 return info.root;
4357 }
4358
4359 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004360 if (taskRequired) {
4361 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4362 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004363 return null;
4364 }
4365
4366 // Remove all of this task's activies starting at the sub task.
4367 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4368 performClearTaskAtIndexLocked(taskId, subtask.index);
4369 return subtask.activity;
4370 }
4371
4372 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4373 ActivityRecord resumed = mResumedActivity;
4374 final TaskAccessInfo thumbs = new TaskAccessInfo();
4375 // How many different sub-thumbnails?
4376 final int NA = mHistory.size();
4377 int j = 0;
4378 ThumbnailHolder holder = null;
4379 while (j < NA) {
4380 ActivityRecord ar = mHistory.get(j);
4381 if (!ar.finishing && ar.task.taskId == taskId) {
4382 holder = ar.thumbHolder;
4383 break;
4384 }
4385 j++;
4386 }
4387
4388 if (j >= NA) {
4389 return thumbs;
4390 }
4391
4392 thumbs.root = mHistory.get(j);
4393 thumbs.rootIndex = j;
4394
4395 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4396 thumbs.subtasks = subtasks;
4397 ActivityRecord lastActivity = null;
4398 while (j < NA) {
4399 ActivityRecord ar = mHistory.get(j);
4400 j++;
4401 if (ar.finishing) {
4402 continue;
4403 }
4404 if (ar.task.taskId != taskId) {
4405 break;
4406 }
4407 lastActivity = ar;
4408 if (ar.thumbHolder != holder && holder != null) {
4409 thumbs.numSubThumbbails++;
4410 holder = ar.thumbHolder;
4411 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4412 sub.thumbnail = holder.lastThumbnail;
4413 sub.activity = ar;
4414 sub.index = j-1;
4415 subtasks.add(sub);
4416 }
4417 }
4418 if (lastActivity != null && subtasks.size() > 0) {
4419 if (resumed == lastActivity) {
4420 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4421 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4422 }
4423 }
4424 if (thumbs.numSubThumbbails > 0) {
4425 thumbs.retriever = new IThumbnailRetriever.Stub() {
4426 public Bitmap getThumbnail(int index) {
4427 if (index < 0 || index >= thumbs.subtasks.size()) {
4428 return null;
4429 }
4430 return thumbs.subtasks.get(index).thumbnail;
4431 }
4432 };
4433 }
4434 return thumbs;
4435 }
4436
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004437 private final void logStartActivity(int tag, ActivityRecord r,
4438 TaskRecord task) {
4439 EventLog.writeEvent(tag,
4440 System.identityHashCode(r), task.taskId,
4441 r.shortComponentName, r.intent.getAction(),
4442 r.intent.getType(), r.intent.getDataString(),
4443 r.intent.getFlags());
4444 }
4445
4446 /**
4447 * Make sure the given activity matches the current configuration. Returns
4448 * false if the activity had to be destroyed. Returns true if the
4449 * configuration is the same, or the activity will remain running as-is
4450 * for whatever reason. Ensures the HistoryRecord is updated with the
4451 * correct configuration and all other bookkeeping is handled.
4452 */
4453 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4454 int globalChanges) {
4455 if (mConfigWillChange) {
4456 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4457 "Skipping config check (will change): " + r);
4458 return true;
4459 }
4460
4461 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4462 "Ensuring correct configuration: " + r);
4463
4464 // Short circuit: if the two configurations are the exact same
4465 // object (the common case), then there is nothing to do.
4466 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004467 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004468 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4469 "Configuration unchanged in " + r);
4470 return true;
4471 }
4472
4473 // We don't worry about activities that are finishing.
4474 if (r.finishing) {
4475 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4476 "Configuration doesn't matter in finishing " + r);
4477 r.stopFreezingScreenLocked(false);
4478 return true;
4479 }
4480
4481 // Okay we now are going to make this activity have the new config.
4482 // But then we need to figure out how it needs to deal with that.
4483 Configuration oldConfig = r.configuration;
4484 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004485
4486 // Determine what has changed. May be nothing, if this is a config
4487 // that has come back from the app after going idle. In that case
4488 // we just want to leave the official config object now in the
4489 // activity and do nothing else.
4490 final int changes = oldConfig.diff(newConfig);
4491 if (changes == 0 && !r.forceNewConfig) {
4492 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4493 "Configuration no differences in " + r);
4494 return true;
4495 }
4496
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004497 // If the activity isn't currently running, just leave the new
4498 // configuration and it will pick that up next time it starts.
4499 if (r.app == null || r.app.thread == null) {
4500 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4501 "Configuration doesn't matter not running " + r);
4502 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004503 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004504 return true;
4505 }
4506
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004507 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004508 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4509 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4510 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004511 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004512 + ", newConfig=" + newConfig);
4513 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004514 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004515 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4516 r.configChangeFlags |= changes;
4517 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004518 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004519 if (r.app == null || r.app.thread == null) {
4520 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004521 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004522 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004523 } else if (r.state == ActivityState.PAUSING) {
4524 // A little annoying: we are waiting for this activity to
4525 // finish pausing. Let's not do anything now, but just
4526 // flag that it needs to be restarted when done pausing.
4527 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004528 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004529 r.configDestroy = true;
4530 return true;
4531 } else if (r.state == ActivityState.RESUMED) {
4532 // Try to optimize this case: the configuration is changing
4533 // and we need to restart the top, resumed activity.
4534 // Instead of doing the normal handshaking, just say
4535 // "restart!".
4536 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004537 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004538 relaunchActivityLocked(r, r.configChangeFlags, true);
4539 r.configChangeFlags = 0;
4540 } else {
4541 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004542 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004543 relaunchActivityLocked(r, r.configChangeFlags, false);
4544 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004545 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004546
4547 // All done... tell the caller we weren't able to keep this
4548 // activity around.
4549 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004550 }
4551
4552 // Default case: the activity can handle this new configuration, so
4553 // hand it over. Note that we don't need to give it the new
4554 // configuration, since we always send configuration changes to all
4555 // process when they happen so it can just use whatever configuration
4556 // it last got.
4557 if (r.app != null && r.app.thread != null) {
4558 try {
4559 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004560 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004561 } catch (RemoteException e) {
4562 // If process died, whatever.
4563 }
4564 }
4565 r.stopFreezingScreenLocked(false);
4566
4567 return true;
4568 }
4569
4570 private final boolean relaunchActivityLocked(ActivityRecord r,
4571 int changes, boolean andResume) {
4572 List<ResultInfo> results = null;
4573 List<Intent> newIntents = null;
4574 if (andResume) {
4575 results = r.results;
4576 newIntents = r.newIntents;
4577 }
4578 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4579 + " with results=" + results + " newIntents=" + newIntents
4580 + " andResume=" + andResume);
4581 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4582 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4583 r.task.taskId, r.shortComponentName);
4584
4585 r.startFreezingScreenLocked(r.app, 0);
4586
4587 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004588 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4589 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4590 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004591 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004592 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004593 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004594 // Note: don't need to call pauseIfSleepingLocked() here, because
4595 // the caller will only pass in 'andResume' if this activity is
4596 // currently resumed, which implies we aren't sleeping.
4597 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004598 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004599 }
4600
4601 if (andResume) {
4602 r.results = null;
4603 r.newIntents = null;
4604 if (mMainStack) {
4605 mService.reportResumedActivityLocked(r);
4606 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004607 r.state = ActivityState.RESUMED;
4608 } else {
4609 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4610 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004611 }
4612
4613 return true;
4614 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004615
4616 public void dismissKeyguardOnNextActivityLocked() {
4617 mDismissKeyguardOnNextActivity = true;
4618 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004619}