blob: df50d898dee7be41a00ed18778abc0b8fcdbac99 [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 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001206
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001207 if (mMainStack) {
1208 mService.setFocusedActivityLocked(next);
1209 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001210 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001211 ensureActivitiesVisibleLocked(null, 0);
1212 mService.mWindowManager.executeAppTransition();
1213 mNoAnimActivities.clear();
1214
1215 // Mark the point when the activity is resuming
1216 // TODO: To be more accurate, the mark should be before the onCreate,
1217 // not after the onResume. But for subsequent starts, onResume is fine.
1218 if (next.app != null) {
1219 synchronized (mService.mProcessStatsThread) {
1220 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1221 }
1222 } else {
1223 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1224 }
1225 }
1226
1227 /**
1228 * Make sure that all activities that need to be visible (that is, they
1229 * currently can be seen by the user) actually are.
1230 */
1231 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1232 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1233 if (DEBUG_VISBILITY) Slog.v(
1234 TAG, "ensureActivitiesVisible behind " + top
1235 + " configChanges=0x" + Integer.toHexString(configChanges));
1236
1237 // If the top activity is not fullscreen, then we need to
1238 // make sure any activities under it are now visible.
1239 final int count = mHistory.size();
1240 int i = count-1;
1241 while (mHistory.get(i) != top) {
1242 i--;
1243 }
1244 ActivityRecord r;
1245 boolean behindFullscreen = false;
1246 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001247 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001248 if (DEBUG_VISBILITY) Slog.v(
1249 TAG, "Make visible? " + r + " finishing=" + r.finishing
1250 + " state=" + r.state);
1251 if (r.finishing) {
1252 continue;
1253 }
1254
1255 final boolean doThisProcess = onlyThisProcess == null
1256 || onlyThisProcess.equals(r.processName);
1257
1258 // First: if this is not the current activity being started, make
1259 // sure it matches the current configuration.
1260 if (r != starting && doThisProcess) {
1261 ensureActivityConfigurationLocked(r, 0);
1262 }
1263
1264 if (r.app == null || r.app.thread == null) {
1265 if (onlyThisProcess == null
1266 || onlyThisProcess.equals(r.processName)) {
1267 // This activity needs to be visible, but isn't even
1268 // running... get it started, but don't resume it
1269 // at this point.
1270 if (DEBUG_VISBILITY) Slog.v(
1271 TAG, "Start and freeze screen for " + r);
1272 if (r != starting) {
1273 r.startFreezingScreenLocked(r.app, configChanges);
1274 }
1275 if (!r.visible) {
1276 if (DEBUG_VISBILITY) Slog.v(
1277 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001278 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001279 }
1280 if (r != starting) {
1281 startSpecificActivityLocked(r, false, false);
1282 }
1283 }
1284
1285 } else if (r.visible) {
1286 // If this activity is already visible, then there is nothing
1287 // else to do here.
1288 if (DEBUG_VISBILITY) Slog.v(
1289 TAG, "Skipping: already visible at " + r);
1290 r.stopFreezingScreenLocked(false);
1291
1292 } else if (onlyThisProcess == null) {
1293 // This activity is not currently visible, but is running.
1294 // Tell it to become visible.
1295 r.visible = true;
1296 if (r.state != ActivityState.RESUMED && r != starting) {
1297 // If this activity is paused, tell it
1298 // to now show its window.
1299 if (DEBUG_VISBILITY) Slog.v(
1300 TAG, "Making visible and scheduling visibility: " + r);
1301 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001302 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001303 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001304 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001305 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001306 r.stopFreezingScreenLocked(false);
1307 } catch (Exception e) {
1308 // Just skip on any failure; we'll make it
1309 // visible when it next restarts.
1310 Slog.w(TAG, "Exception thrown making visibile: "
1311 + r.intent.getComponent(), e);
1312 }
1313 }
1314 }
1315
1316 // Aggregate current change flags.
1317 configChanges |= r.configChangeFlags;
1318
1319 if (r.fullscreen) {
1320 // At this point, nothing else needs to be shown
1321 if (DEBUG_VISBILITY) Slog.v(
1322 TAG, "Stopping: fullscreen at " + r);
1323 behindFullscreen = true;
1324 i--;
1325 break;
1326 }
1327 }
1328
1329 // Now for any activities that aren't visible to the user, make
1330 // sure they no longer are keeping the screen frozen.
1331 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001332 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001333 if (DEBUG_VISBILITY) Slog.v(
1334 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1335 + " state=" + r.state
1336 + " behindFullscreen=" + behindFullscreen);
1337 if (!r.finishing) {
1338 if (behindFullscreen) {
1339 if (r.visible) {
1340 if (DEBUG_VISBILITY) Slog.v(
1341 TAG, "Making invisible: " + r);
1342 r.visible = false;
1343 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001344 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001345 if ((r.state == ActivityState.STOPPING
1346 || r.state == ActivityState.STOPPED)
1347 && r.app != null && r.app.thread != null) {
1348 if (DEBUG_VISBILITY) Slog.v(
1349 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001350 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001351 }
1352 } catch (Exception e) {
1353 // Just skip on any failure; we'll make it
1354 // visible when it next restarts.
1355 Slog.w(TAG, "Exception thrown making hidden: "
1356 + r.intent.getComponent(), e);
1357 }
1358 } else {
1359 if (DEBUG_VISBILITY) Slog.v(
1360 TAG, "Already invisible: " + r);
1361 }
1362 } else if (r.fullscreen) {
1363 if (DEBUG_VISBILITY) Slog.v(
1364 TAG, "Now behindFullscreen: " + r);
1365 behindFullscreen = true;
1366 }
1367 }
1368 i--;
1369 }
1370 }
1371
1372 /**
1373 * Version of ensureActivitiesVisible that can easily be called anywhere.
1374 */
1375 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1376 int configChanges) {
1377 ActivityRecord r = topRunningActivityLocked(null);
1378 if (r != null) {
1379 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1380 }
1381 }
1382
1383 /**
1384 * Ensure that the top activity in the stack is resumed.
1385 *
1386 * @param prev The previously resumed activity, for when in the process
1387 * of pausing; can be null to call from elsewhere.
1388 *
1389 * @return Returns true if something is being resumed, or false if
1390 * nothing happened.
1391 */
1392 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001393 return resumeTopActivityLocked(prev, null);
1394 }
1395
1396 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001397 // Find the first activity that is not finishing.
1398 ActivityRecord next = topRunningActivityLocked(null);
1399
1400 // Remember how we'll process this pause/resume situation, and ensure
1401 // that the state is reset however we wind up proceeding.
1402 final boolean userLeaving = mUserLeaving;
1403 mUserLeaving = false;
1404
1405 if (next == null) {
1406 // There are no more activities! Let's just start up the
1407 // Launcher...
1408 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001409 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001410 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001411 }
1412 }
1413
1414 next.delayedResume = false;
1415
1416 // If the top activity is the resumed one, nothing to do.
1417 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1418 // Make sure we have executed any pending transitions, since there
1419 // should be nothing left to do at this point.
1420 mService.mWindowManager.executeAppTransition();
1421 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001422 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001423 return false;
1424 }
1425
1426 // If we are sleeping, and there is no resumed activity, and the top
1427 // activity is paused, well that is the state we want.
1428 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001429 && mLastPausedActivity == next
1430 && (next.state == ActivityState.PAUSED
1431 || next.state == ActivityState.STOPPED
1432 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001433 // Make sure we have executed any pending transitions, since there
1434 // should be nothing left to do at this point.
1435 mService.mWindowManager.executeAppTransition();
1436 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001437 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001438 return false;
1439 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001440
1441 // Make sure that the user who owns this activity is started. If not,
1442 // we will just leave it as is because someone should be bringing
1443 // another user's activities to the top of the stack.
1444 if (mService.mStartedUsers.get(next.userId) == null) {
1445 Slog.w(TAG, "Skipping resume of top activity " + next
1446 + ": user " + next.userId + " is stopped");
1447 return false;
1448 }
1449
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001450 // The activity may be waiting for stop, but that is no longer
1451 // appropriate for it.
1452 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001453 mGoingToSleepActivities.remove(next);
1454 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001455 mWaitingVisibleActivities.remove(next);
1456
Dianne Hackborn84375872012-06-01 19:03:50 -07001457 next.updateOptionsLocked(options);
1458
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001459 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1460
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001461 // If we are currently pausing an activity, then don't do anything
1462 // until that is done.
1463 if (mPausingActivity != null) {
1464 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1465 return false;
1466 }
1467
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001468 // Okay we are now going to start a switch, to 'next'. We may first
1469 // have to pause the current activity, but this is an important point
1470 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001471 // XXX "App Redirected" dialog is getting too many false positives
1472 // at this point, so turn off for now.
1473 if (false) {
1474 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1475 long now = SystemClock.uptimeMillis();
1476 final boolean inTime = mLastStartedActivity.startTime != 0
1477 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1478 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1479 final int nextUid = next.info.applicationInfo.uid;
1480 if (inTime && lastUid != nextUid
1481 && lastUid != next.launchedFromUid
1482 && mService.checkPermission(
1483 android.Manifest.permission.STOP_APP_SWITCHES,
1484 -1, next.launchedFromUid)
1485 != PackageManager.PERMISSION_GRANTED) {
1486 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1487 } else {
1488 next.startTime = now;
1489 mLastStartedActivity = next;
1490 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001491 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001492 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001493 mLastStartedActivity = next;
1494 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001495 }
1496
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001497 // We need to start pausing the current activity so the top one
1498 // can be resumed...
1499 if (mResumedActivity != null) {
1500 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001501 // At this point we want to put the upcoming activity's process
1502 // at the top of the LRU list, since we know we will be needing it
1503 // very soon and it would be a waste to let it get killed if it
1504 // happens to be sitting towards the end.
1505 if (next.app != null && next.app.thread != null) {
1506 // No reason to do full oom adj update here; we'll let that
1507 // happen whenever it needs to later.
1508 mService.updateLruProcessLocked(next.app, false, true);
1509 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001510 startPausingLocked(userLeaving, false);
1511 return true;
1512 }
1513
Christopher Tated3f175c2012-06-14 14:16:54 -07001514 // If the most recent activity was noHistory but was only stopped rather
1515 // than stopped+finished because the device went to sleep, we need to make
1516 // sure to finish it as we're making a new activity topmost.
1517 final ActivityRecord last = mLastPausedActivity;
1518 if (mService.mSleeping && last != null && !last.finishing) {
1519 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1520 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1521 if (DEBUG_STATES) {
1522 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1523 }
1524 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001525 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001526 }
1527 }
1528
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001529 if (prev != null && prev != next) {
1530 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1531 prev.waitingVisible = true;
1532 mWaitingVisibleActivities.add(prev);
1533 if (DEBUG_SWITCH) Slog.v(
1534 TAG, "Resuming top, waiting visible to hide: " + prev);
1535 } else {
1536 // The next activity is already visible, so hide the previous
1537 // activity's windows right now so we can show the new one ASAP.
1538 // We only do this if the previous is finishing, which should mean
1539 // it is on top of the one being resumed so hiding it quickly
1540 // is good. Otherwise, we want to do the normal route of allowing
1541 // the resumed activity to be shown so we can decide if the
1542 // previous should actually be hidden depending on whether the
1543 // new one is found to be full-screen or not.
1544 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001545 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001546 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1547 + prev + ", waitingVisible="
1548 + (prev != null ? prev.waitingVisible : null)
1549 + ", nowVisible=" + next.nowVisible);
1550 } else {
1551 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1552 + prev + ", waitingVisible="
1553 + (prev != null ? prev.waitingVisible : null)
1554 + ", nowVisible=" + next.nowVisible);
1555 }
1556 }
1557 }
1558
Dianne Hackborne7f97212011-02-24 14:40:20 -08001559 // Launching this app's activity, make sure the app is no longer
1560 // considered stopped.
1561 try {
1562 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001563 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001564 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001565 } catch (IllegalArgumentException e) {
1566 Slog.w(TAG, "Failed trying to unstop package "
1567 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001568 }
1569
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001570 // We are starting up the next activity, so tell the window manager
1571 // that the previous one will be hidden soon. This way it can know
1572 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001573 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001574 if (prev != null) {
1575 if (prev.finishing) {
1576 if (DEBUG_TRANSITION) Slog.v(TAG,
1577 "Prepare close transition: prev=" + prev);
1578 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001579 mService.mWindowManager.prepareAppTransition(
1580 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 } else {
1582 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1583 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001584 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001585 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001586 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1587 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001588 } else {
1589 if (DEBUG_TRANSITION) Slog.v(TAG,
1590 "Prepare open transition: prev=" + prev);
1591 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001592 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001593 mService.mWindowManager.prepareAppTransition(
1594 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001595 } else {
1596 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1597 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001598 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001599 }
1600 }
1601 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001602 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1603 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001604 }
1605 } else if (mHistory.size() > 1) {
1606 if (DEBUG_TRANSITION) Slog.v(TAG,
1607 "Prepare open transition: no previous");
1608 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001609 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001610 mService.mWindowManager.prepareAppTransition(
1611 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001612 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001613 mService.mWindowManager.prepareAppTransition(
1614 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001615 }
1616 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001617 if (!noAnim) {
1618 next.applyOptionsLocked();
1619 } else {
1620 next.clearOptionsLocked();
1621 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001622
1623 if (next.app != null && next.app.thread != null) {
1624 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1625
1626 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001627 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001628
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001629 // schedule launch ticks to collect information about slow apps.
1630 next.startLaunchTickingLocked();
1631
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001632 ActivityRecord lastResumedActivity = mResumedActivity;
1633 ActivityState lastState = next.state;
1634
1635 mService.updateCpuStats();
1636
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001637 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001638 next.state = ActivityState.RESUMED;
1639 mResumedActivity = next;
1640 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001641 if (mMainStack) {
1642 mService.addRecentTaskLocked(next.task);
1643 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 mService.updateLruProcessLocked(next.app, true, true);
1645 updateLRUListLocked(next);
1646
1647 // Have the window manager re-evaluate the orientation of
1648 // the screen based on the new activity order.
1649 boolean updated = false;
1650 if (mMainStack) {
1651 synchronized (mService) {
1652 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1653 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001654 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001655 if (config != null) {
1656 next.frozenBeforeDestroy = true;
1657 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001658 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001659 }
1660 }
1661 if (!updated) {
1662 // The configuration update wasn't able to keep the existing
1663 // instance of the activity, and instead started a new one.
1664 // We should be all done, but let's just make sure our activity
1665 // is still at the top and schedule another run if something
1666 // weird happened.
1667 ActivityRecord nextNext = topRunningActivityLocked(null);
1668 if (DEBUG_SWITCH) Slog.i(TAG,
1669 "Activity config changed during resume: " + next
1670 + ", new next: " + nextNext);
1671 if (nextNext != next) {
1672 // Do over!
1673 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1674 }
1675 if (mMainStack) {
1676 mService.setFocusedActivityLocked(next);
1677 }
1678 ensureActivitiesVisibleLocked(null, 0);
1679 mService.mWindowManager.executeAppTransition();
1680 mNoAnimActivities.clear();
1681 return true;
1682 }
1683
1684 try {
1685 // Deliver all pending results.
1686 ArrayList a = next.results;
1687 if (a != null) {
1688 final int N = a.size();
1689 if (!next.finishing && N > 0) {
1690 if (DEBUG_RESULTS) Slog.v(
1691 TAG, "Delivering results to " + next
1692 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001693 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 }
1695 }
1696
1697 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001698 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 }
1700
1701 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1702 System.identityHashCode(next),
1703 next.task.taskId, next.shortComponentName);
1704
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001705 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001706 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001707 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001708 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001709 mService.isNextTransitionForward());
1710
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001711 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001712
1713 } catch (Exception e) {
1714 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001715 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1716 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001717 next.state = lastState;
1718 mResumedActivity = lastResumedActivity;
1719 Slog.i(TAG, "Restarting because process died: " + next);
1720 if (!next.hasBeenLaunched) {
1721 next.hasBeenLaunched = true;
1722 } else {
1723 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1724 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001725 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001726 mService.compatibilityInfoForPackageLocked(
1727 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001728 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001729 next.labelRes, next.icon, next.windowFlags,
1730 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001731 }
1732 }
1733 startSpecificActivityLocked(next, true, false);
1734 return true;
1735 }
1736
1737 // From this point on, if something goes wrong there is no way
1738 // to recover the activity.
1739 try {
1740 next.visible = true;
1741 completeResumeLocked(next);
1742 } catch (Exception e) {
1743 // If any exception gets thrown, toss away this
1744 // activity and try the next one.
1745 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001746 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001747 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001748 return true;
1749 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001750 next.stopped = false;
1751
1752 } else {
1753 // Whoops, need to restart this activity!
1754 if (!next.hasBeenLaunched) {
1755 next.hasBeenLaunched = true;
1756 } else {
1757 if (SHOW_APP_STARTING_PREVIEW) {
1758 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001759 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001760 mService.compatibilityInfoForPackageLocked(
1761 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001762 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001763 next.labelRes, next.icon, next.windowFlags,
1764 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001765 }
1766 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1767 }
1768 startSpecificActivityLocked(next, true, true);
1769 }
1770
1771 return true;
1772 }
1773
1774 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001775 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 final int NH = mHistory.size();
1777
1778 int addPos = -1;
1779
1780 if (!newTask) {
1781 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 boolean startIt = true;
1783 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001784 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 if (p.finishing) {
1786 continue;
1787 }
1788 if (p.task == r.task) {
1789 // Here it is! Now, if this is not yet visible to the
1790 // user, then just add it without starting; it will
1791 // get started when the user navigates back to it.
1792 addPos = i+1;
1793 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001794 if (DEBUG_ADD_REMOVE) {
1795 RuntimeException here = new RuntimeException("here");
1796 here.fillInStackTrace();
1797 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1798 here);
1799 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001800 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001801 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001802 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 r.info.screenOrientation, r.fullscreen);
1804 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001805 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001806 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001807 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001808 return;
1809 }
1810 break;
1811 }
1812 if (p.fullscreen) {
1813 startIt = false;
1814 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001815 }
1816 }
1817
1818 // Place a new activity at top of stack, so it is next to interact
1819 // with the user.
1820 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001821 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001822 }
1823
1824 // If we are not placing the new activity frontmost, we do not want
1825 // to deliver the onUserLeaving callback to the actual frontmost
1826 // activity
1827 if (addPos < NH) {
1828 mUserLeaving = false;
1829 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1830 }
1831
1832 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001833 if (DEBUG_ADD_REMOVE) {
1834 RuntimeException here = new RuntimeException("here");
1835 here.fillInStackTrace();
1836 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1837 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001838 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001839 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001840 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001841 if (NH > 0) {
1842 // We want to show the starting preview window if we are
1843 // switching to a new task, or the next activity's process is
1844 // not currently running.
1845 boolean showStartingIcon = newTask;
1846 ProcessRecord proc = r.app;
1847 if (proc == null) {
1848 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1849 }
1850 if (proc == null || proc.thread == null) {
1851 showStartingIcon = true;
1852 }
1853 if (DEBUG_TRANSITION) Slog.v(TAG,
1854 "Prepare open transition: starting " + r);
1855 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001856 mService.mWindowManager.prepareAppTransition(
1857 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001858 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001859 } else {
1860 mService.mWindowManager.prepareAppTransition(newTask
1861 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001862 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001863 mNoAnimActivities.remove(r);
1864 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001865 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001866 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001867 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001868 boolean doShow = true;
1869 if (newTask) {
1870 // Even though this activity is starting fresh, we still need
1871 // to reset it to make sure we apply affinities to move any
1872 // existing activities from other tasks in to it.
1873 // If the caller has requested that the target task be
1874 // reset, then do so.
1875 if ((r.intent.getFlags()
1876 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1877 resetTaskIfNeededLocked(r, r);
1878 doShow = topRunningNonDelayedActivityLocked(null) == r;
1879 }
1880 }
1881 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1882 // Figure out if we are transitioning from another activity that is
1883 // "has the same starting icon" as the next one. This allows the
1884 // window manager to keep the previous window it had previously
1885 // created, if it still had one.
1886 ActivityRecord prev = mResumedActivity;
1887 if (prev != null) {
1888 // We don't want to reuse the previous starting preview if:
1889 // (1) The current activity is in a different task.
1890 if (prev.task != r.task) prev = null;
1891 // (2) The current activity is already displayed.
1892 else if (prev.nowVisible) prev = null;
1893 }
1894 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001895 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001896 mService.compatibilityInfoForPackageLocked(
1897 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001898 r.labelRes, r.icon, r.windowFlags,
1899 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001900 }
1901 } else {
1902 // If this is the first activity, don't do any fancy animations,
1903 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001904 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001905 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001906 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001907 }
1908 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001909 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001910 }
1911
1912 if (doResume) {
1913 resumeTopActivityLocked(null);
1914 }
1915 }
1916
Dianne Hackbornbe707852011-11-11 14:32:10 -08001917 final void validateAppTokensLocked() {
1918 mValidateAppTokens.clear();
1919 mValidateAppTokens.ensureCapacity(mHistory.size());
1920 for (int i=0; i<mHistory.size(); i++) {
1921 mValidateAppTokens.add(mHistory.get(i).appToken);
1922 }
1923 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1924 }
1925
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001926 /**
1927 * Perform a reset of the given task, if needed as part of launching it.
1928 * Returns the new HistoryRecord at the top of the task.
1929 */
1930 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1931 ActivityRecord newActivity) {
1932 boolean forceReset = (newActivity.info.flags
1933 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001934 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1935 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001936 if ((newActivity.info.flags
1937 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1938 forceReset = true;
1939 }
1940 }
1941
1942 final TaskRecord task = taskTop.task;
1943
1944 // We are going to move through the history list so that we can look
1945 // at each activity 'target' with 'below' either the interesting
1946 // activity immediately below it in the stack or null.
1947 ActivityRecord target = null;
1948 int targetI = 0;
1949 int taskTopI = -1;
1950 int replyChainEnd = -1;
1951 int lastReparentPos = -1;
1952 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001953 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001954
1955 if (below != null && below.finishing) {
1956 continue;
1957 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001958 // Don't check any lower in the stack if we're crossing a user boundary.
1959 if (below != null && below.userId != taskTop.userId) {
1960 break;
1961 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001962 if (target == null) {
1963 target = below;
1964 targetI = i;
1965 // If we were in the middle of a reply chain before this
1966 // task, it doesn't appear like the root of the chain wants
1967 // anything interesting, so drop it.
1968 replyChainEnd = -1;
1969 continue;
1970 }
1971
1972 final int flags = target.info.flags;
1973
1974 final boolean finishOnTaskLaunch =
1975 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1976 final boolean allowTaskReparenting =
1977 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1978
1979 if (target.task == task) {
1980 // We are inside of the task being reset... we'll either
1981 // finish this activity, push it out for another task,
1982 // or leave it as-is. We only do this
1983 // for activities that are not the root of the task (since
1984 // if we finish the root, we may no longer have the task!).
1985 if (taskTopI < 0) {
1986 taskTopI = targetI;
1987 }
1988 if (below != null && below.task == task) {
1989 final boolean clearWhenTaskReset =
1990 (target.intent.getFlags()
1991 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1992 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1993 // If this activity is sending a reply to a previous
1994 // activity, we can't do anything with it now until
1995 // we reach the start of the reply chain.
1996 // XXX note that we are assuming the result is always
1997 // to the previous activity, which is almost always
1998 // the case but we really shouldn't count on.
1999 if (replyChainEnd < 0) {
2000 replyChainEnd = targetI;
2001 }
2002 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2003 && target.taskAffinity != null
2004 && !target.taskAffinity.equals(task.affinity)) {
2005 // If this activity has an affinity for another
2006 // task, then we need to move it out of here. We will
2007 // move it as far out of the way as possible, to the
2008 // bottom of the activity stack. This also keeps it
2009 // correctly ordered with any activities we previously
2010 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002011 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002012 if (target.taskAffinity != null
2013 && target.taskAffinity.equals(p.task.affinity)) {
2014 // If the activity currently at the bottom has the
2015 // same task affinity as the one we are moving,
2016 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002017 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002018 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2019 + " out to bottom task " + p.task);
2020 } else {
2021 mService.mCurTask++;
2022 if (mService.mCurTask <= 0) {
2023 mService.mCurTask = 1;
2024 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002025 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2026 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002027 target.task.affinityIntent = target.intent;
2028 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2029 + " out to new task " + target.task);
2030 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002031 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002032 if (replyChainEnd < 0) {
2033 replyChainEnd = targetI;
2034 }
2035 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002036 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002037 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002038 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039 if (p.finishing) {
2040 continue;
2041 }
2042 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2043 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002044 p.setTask(target.task, curThumbHolder, false);
2045 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002046 if (DEBUG_ADD_REMOVE) {
2047 RuntimeException here = new RuntimeException("here");
2048 here.fillInStackTrace();
2049 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2050 + dstPos, here);
2051 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002052 mHistory.remove(srcPos);
2053 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002054 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2055 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002056 dstPos++;
2057 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002058 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002059 }
2060 i++;
2061 }
2062 if (taskTop == p) {
2063 taskTop = below;
2064 }
2065 if (taskTopI == replyChainEnd) {
2066 taskTopI = -1;
2067 }
2068 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002069 } else if (forceReset || finishOnTaskLaunch
2070 || clearWhenTaskReset) {
2071 // If the activity should just be removed -- either
2072 // because it asks for it, or the task should be
2073 // cleared -- then finish it and anything that is
2074 // part of its reply chain.
2075 if (clearWhenTaskReset) {
2076 // In this case, we want to finish this activity
2077 // and everything above it, so be sneaky and pretend
2078 // like these are all in the reply chain.
2079 replyChainEnd = targetI+1;
2080 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002081 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002082 replyChainEnd)).task == task) {
2083 replyChainEnd++;
2084 }
2085 replyChainEnd--;
2086 } else if (replyChainEnd < 0) {
2087 replyChainEnd = targetI;
2088 }
2089 ActivityRecord p = null;
2090 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002091 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002092 if (p.finishing) {
2093 continue;
2094 }
2095 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002096 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002097 replyChainEnd--;
2098 srcPos--;
2099 }
2100 }
2101 if (taskTop == p) {
2102 taskTop = below;
2103 }
2104 if (taskTopI == replyChainEnd) {
2105 taskTopI = -1;
2106 }
2107 replyChainEnd = -1;
2108 } else {
2109 // If we were in the middle of a chain, well the
2110 // activity that started it all doesn't want anything
2111 // special, so leave it all as-is.
2112 replyChainEnd = -1;
2113 }
2114 } else {
2115 // Reached the bottom of the task -- any reply chain
2116 // should be left as-is.
2117 replyChainEnd = -1;
2118 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002119
2120 } else if (target.resultTo != null && (below == null
2121 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002122 // If this activity is sending a reply to a previous
2123 // activity, we can't do anything with it now until
2124 // we reach the start of the reply chain.
2125 // XXX note that we are assuming the result is always
2126 // to the previous activity, which is almost always
2127 // the case but we really shouldn't count on.
2128 if (replyChainEnd < 0) {
2129 replyChainEnd = targetI;
2130 }
2131
2132 } else if (taskTopI >= 0 && allowTaskReparenting
2133 && task.affinity != null
2134 && task.affinity.equals(target.taskAffinity)) {
2135 // We are inside of another task... if this activity has
2136 // an affinity for our task, then either remove it if we are
2137 // clearing or move it over to our task. Note that
2138 // we currently punt on the case where we are resetting a
2139 // task that is not at the top but who has activities above
2140 // with an affinity to it... this is really not a normal
2141 // case, and we will need to later pull that task to the front
2142 // and usually at that point we will do the reset and pick
2143 // up those remaining activities. (This only happens if
2144 // someone starts an activity in a new task from an activity
2145 // in a task that is not currently on top.)
2146 if (forceReset || finishOnTaskLaunch) {
2147 if (replyChainEnd < 0) {
2148 replyChainEnd = targetI;
2149 }
2150 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002151 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2152 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002153 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002154 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002155 if (p.finishing) {
2156 continue;
2157 }
2158 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002159 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002160 taskTopI--;
2161 lastReparentPos--;
2162 replyChainEnd--;
2163 srcPos--;
2164 }
2165 }
2166 replyChainEnd = -1;
2167 } else {
2168 if (replyChainEnd < 0) {
2169 replyChainEnd = targetI;
2170 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002171 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2172 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002173 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002174 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002175 if (p.finishing) {
2176 continue;
2177 }
2178 if (lastReparentPos < 0) {
2179 lastReparentPos = taskTopI;
2180 taskTop = p;
2181 } else {
2182 lastReparentPos--;
2183 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002184 if (DEBUG_ADD_REMOVE) {
2185 RuntimeException here = new RuntimeException("here");
2186 here.fillInStackTrace();
2187 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2188 + lastReparentPos, here);
2189 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002190 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002191 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002192 mHistory.add(lastReparentPos, p);
2193 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002194 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002195 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002196 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2197 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002198 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002199 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002200 }
2201 }
2202 replyChainEnd = -1;
2203
2204 // Now we've moved it in to place... but what if this is
2205 // a singleTop activity and we have put it on top of another
2206 // instance of the same activity? Then we drop the instance
2207 // below so it remains singleTop.
2208 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2209 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002210 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002211 if (p.finishing) {
2212 continue;
2213 }
2214 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2215 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002216 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002217 taskTopI--;
2218 lastReparentPos--;
2219 }
2220 }
2221 }
2222 }
2223 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002224
2225 } else if (below != null && below.task != target.task) {
2226 // We hit the botton of a task; the reply chain can't
2227 // pass through it.
2228 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 }
2230
2231 target = below;
2232 targetI = i;
2233 }
2234
2235 return taskTop;
2236 }
2237
2238 /**
2239 * Perform clear operation as requested by
2240 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2241 * stack to the given task, then look for
2242 * an instance of that activity in the stack and, if found, finish all
2243 * activities on top of it and return the instance.
2244 *
2245 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002246 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002247 * or null if none was found.
2248 */
2249 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002250 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002251 int i = mHistory.size();
2252
2253 // First find the requested task.
2254 while (i > 0) {
2255 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002256 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 if (r.task.taskId == taskId) {
2258 i++;
2259 break;
2260 }
2261 }
2262
2263 // Now clear it.
2264 while (i > 0) {
2265 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002266 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002267 if (r.finishing) {
2268 continue;
2269 }
2270 if (r.task.taskId != taskId) {
2271 return null;
2272 }
2273 if (r.realActivity.equals(newR.realActivity)) {
2274 // Here it is! Now finish everything in front...
2275 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002276 while (i < (mHistory.size()-1)) {
2277 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002278 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002279 if (r.task.taskId != taskId) {
2280 break;
2281 }
2282 if (r.finishing) {
2283 continue;
2284 }
2285 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002286 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002287 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002288 }
2289 }
2290
2291 // Finally, if this is a normal launch mode (that is, not
2292 // expecting onNewIntent()), then we will finish the current
2293 // instance of the activity so a new fresh one can be started.
2294 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2295 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2296 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002297 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002298 if (index >= 0) {
2299 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002300 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002301 }
2302 return null;
2303 }
2304 }
2305
2306 return ret;
2307 }
2308 }
2309
2310 return null;
2311 }
2312
2313 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002314 * Completely remove all activities associated with an existing
2315 * task starting at a specified index.
2316 */
2317 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002318 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002319 ActivityRecord r = mHistory.get(i);
2320 if (r.task.taskId != taskId) {
2321 // Whoops hit the end.
2322 return;
2323 }
2324 if (r.finishing) {
2325 i++;
2326 continue;
2327 }
2328 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002329 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002330 i++;
2331 }
2332 }
2333 }
2334
2335 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002336 * Completely remove all activities associated with an existing task.
2337 */
2338 private final void performClearTaskLocked(int taskId) {
2339 int i = mHistory.size();
2340
2341 // First find the requested task.
2342 while (i > 0) {
2343 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002344 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002345 if (r.task.taskId == taskId) {
2346 i++;
2347 break;
2348 }
2349 }
2350
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002351 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002352 while (i > 0) {
2353 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002354 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002355 if (r.finishing) {
2356 continue;
2357 }
2358 if (r.task.taskId != taskId) {
2359 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002360 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002361 return;
2362 }
2363 }
2364 }
2365
2366 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 * Find the activity in the history stack within the given task. Returns
2368 * the index within the history at which it's found, or < 0 if not found.
2369 */
2370 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2371 int i = mHistory.size();
2372 while (i > 0) {
2373 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002374 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002375 if (candidate.finishing) {
2376 continue;
2377 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002378 if (candidate.task.taskId != task) {
2379 break;
2380 }
2381 if (candidate.realActivity.equals(r.realActivity)) {
2382 return i;
2383 }
2384 }
2385
2386 return -1;
2387 }
2388
2389 /**
2390 * Reorder the history stack so that the activity at the given index is
2391 * brought to the front.
2392 */
2393 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002394 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002395 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002396 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002397 if (DEBUG_ADD_REMOVE) {
2398 RuntimeException here = new RuntimeException("here");
2399 here.fillInStackTrace();
2400 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2401 + top, here);
2402 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002403 mHistory.add(top, newTop);
2404 oldTop.frontOfTask = false;
2405 newTop.frontOfTask = true;
2406 return newTop;
2407 }
2408
2409 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002410 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002411 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002412 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002413 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002414
Dianne Hackborna4972e92012-03-14 10:38:05 -07002415 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002416
2417 ProcessRecord callerApp = null;
2418 if (caller != null) {
2419 callerApp = mService.getRecordForAppLocked(caller);
2420 if (callerApp != null) {
2421 callingPid = callerApp.pid;
2422 callingUid = callerApp.info.uid;
2423 } else {
2424 Slog.w(TAG, "Unable to find app for caller " + caller
2425 + " (pid=" + callingPid + ") when starting: "
2426 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002427 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002428 }
2429 }
2430
Dianne Hackborna4972e92012-03-14 10:38:05 -07002431 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002432 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002433 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002434 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002435 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002436
2437 ActivityRecord sourceRecord = null;
2438 ActivityRecord resultRecord = null;
2439 if (resultTo != null) {
2440 int index = indexOfTokenLocked(resultTo);
2441 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002442 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002443 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002444 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002445 if (requestCode >= 0 && !sourceRecord.finishing) {
2446 resultRecord = sourceRecord;
2447 }
2448 }
2449 }
2450
2451 int launchFlags = intent.getFlags();
2452
2453 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2454 && sourceRecord != null) {
2455 // Transfer the result target from the source activity to the new
2456 // one being started, including any failures.
2457 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002458 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002459 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002460 }
2461 resultRecord = sourceRecord.resultTo;
2462 resultWho = sourceRecord.resultWho;
2463 requestCode = sourceRecord.requestCode;
2464 sourceRecord.resultTo = null;
2465 if (resultRecord != null) {
2466 resultRecord.removeResultsLocked(
2467 sourceRecord, resultWho, requestCode);
2468 }
2469 }
2470
Dianne Hackborna4972e92012-03-14 10:38:05 -07002471 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002472 // We couldn't find a class that can handle the given Intent.
2473 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002474 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002475 }
2476
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002478 // We couldn't find the specific class specified in the Intent.
2479 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002480 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002481 }
2482
Dianne Hackborna4972e92012-03-14 10:38:05 -07002483 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002484 if (resultRecord != null) {
2485 sendActivityResultLocked(-1,
2486 resultRecord, resultWho, requestCode,
2487 Activity.RESULT_CANCELED, null);
2488 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002489 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002490 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002491 return err;
2492 }
2493
Jeff Sharkey35be7562012-04-18 19:16:15 -07002494 final int startAnyPerm = mService.checkPermission(
2495 START_ANY_ACTIVITY, callingPid, callingUid);
2496 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002497 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002498 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002499 if (resultRecord != null) {
2500 sendActivityResultLocked(-1,
2501 resultRecord, resultWho, requestCode,
2502 Activity.RESULT_CANCELED, null);
2503 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002504 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002505 String msg;
2506 if (!aInfo.exported) {
2507 msg = "Permission Denial: starting " + intent.toString()
2508 + " from " + callerApp + " (pid=" + callingPid
2509 + ", uid=" + callingUid + ")"
2510 + " not exported from uid " + aInfo.applicationInfo.uid;
2511 } else {
2512 msg = "Permission Denial: starting " + intent.toString()
2513 + " from " + callerApp + " (pid=" + callingPid
2514 + ", uid=" + callingUid + ")"
2515 + " requires " + aInfo.permission;
2516 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002517 Slog.w(TAG, msg);
2518 throw new SecurityException(msg);
2519 }
2520
2521 if (mMainStack) {
2522 if (mService.mController != null) {
2523 boolean abort = false;
2524 try {
2525 // The Intent we give to the watcher has the extra data
2526 // stripped off, since it can contain private information.
2527 Intent watchIntent = intent.cloneFilter();
2528 abort = !mService.mController.activityStarting(watchIntent,
2529 aInfo.applicationInfo.packageName);
2530 } catch (RemoteException e) {
2531 mService.mController = null;
2532 }
2533
2534 if (abort) {
2535 if (resultRecord != null) {
2536 sendActivityResultLocked(-1,
2537 resultRecord, resultWho, requestCode,
2538 Activity.RESULT_CANCELED, null);
2539 }
2540 // We pretend to the caller that it was really started, but
2541 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002542 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002543 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002544 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002545 }
2546 }
2547 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002548
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002549 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2550 intent, resolvedType, aInfo, mService.mConfiguration,
2551 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002552 if (outActivity != null) {
2553 outActivity[0] = r;
2554 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002555
2556 if (mMainStack) {
2557 if (mResumedActivity == null
2558 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2559 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2560 PendingActivityLaunch pal = new PendingActivityLaunch();
2561 pal.r = r;
2562 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002563 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002564 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002565 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002566 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002567 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002568 }
2569 }
2570
2571 if (mService.mDidAppSwitch) {
2572 // This is the second allowed switch since we stopped switches,
2573 // so now just generally allow switches. Use case: user presses
2574 // home (switches disabled, switch to home, mDidAppSwitch now true);
2575 // user taps a home icon (coming from home so allowed, we hit here
2576 // and now allow anyone to switch again).
2577 mService.mAppSwitchesAllowedTime = 0;
2578 } else {
2579 mService.mDidAppSwitch = true;
2580 }
2581
2582 mService.doPendingActivityLaunchesLocked(false);
2583 }
2584
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002585 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002586 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002587 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002588 // Someone asked to have the keyguard dismissed on the next
2589 // activity start, but we are not actually doing an activity
2590 // switch... just dismiss the keyguard now, because we
2591 // probably want to see whatever is behind it.
2592 mDismissKeyguardOnNextActivity = false;
2593 mService.mWindowManager.dismissKeyguard();
2594 }
2595 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 }
2597
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002598 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2599 if ((launchFlags &
2600 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2601 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2602 // Caller wants to appear on home activity, so before starting
2603 // their own activity we will bring home to the front.
2604 moveHomeToFrontLocked();
2605 }
2606 }
2607
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002608 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002609 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2610 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 final Intent intent = r.intent;
2612 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002613 final int userId = r.userId;
2614
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 int launchFlags = intent.getFlags();
2616
2617 // We'll invoke onUserLeaving before onPause only if the launching
2618 // activity did not explicitly state that this is an automated launch.
2619 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2620 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2621 "startActivity() => mUserLeaving=" + mUserLeaving);
2622
2623 // If the caller has asked not to resume at this point, we make note
2624 // of this in the record so that we can skip it when trying to find
2625 // the top running activity.
2626 if (!doResume) {
2627 r.delayedResume = true;
2628 }
2629
2630 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2631 != 0 ? r : null;
2632
2633 // If the onlyIfNeeded flag is set, then we can do this if the activity
2634 // being launched is the same as the one making the call... or, as
2635 // a special case, if we do not know the caller then we count the
2636 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002637 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002638 ActivityRecord checkedCaller = sourceRecord;
2639 if (checkedCaller == null) {
2640 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2641 }
2642 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2643 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002644 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002645 }
2646 }
2647
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002648 if (sourceRecord == null) {
2649 // This activity is not being started from another... in this
2650 // case we -always- start a new task.
2651 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2652 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2653 + intent);
2654 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2655 }
2656 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2657 // The original activity who is starting us is running as a single
2658 // instance... this new activity it is starting must go on its
2659 // own task.
2660 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2661 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2662 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2663 // The activity being started is a single instance... it always
2664 // gets launched into its own task.
2665 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2666 }
2667
2668 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2669 // For whatever reason this activity is being launched into a new
2670 // task... yet the caller has requested a result back. Well, that
2671 // is pretty messed up, so instead immediately send back a cancel
2672 // and let the new task continue launched as normal without a
2673 // dependency on its originator.
2674 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2675 sendActivityResultLocked(-1,
2676 r.resultTo, r.resultWho, r.requestCode,
2677 Activity.RESULT_CANCELED, null);
2678 r.resultTo = null;
2679 }
2680
2681 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002682 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002683 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002684 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2685 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2686 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2687 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2688 // If bring to front is requested, and no result is requested, and
2689 // we can find a task that was started with this same
2690 // component, then instead of launching bring that one to the front.
2691 if (r.resultTo == null) {
2692 // See if there is a task to bring to the front. If this is
2693 // a SINGLE_INSTANCE activity, there can be one and only one
2694 // instance of it in the history, and it is always in its own
2695 // unique task, so we do a special search.
2696 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2697 ? findTaskLocked(intent, r.info)
2698 : findActivityLocked(intent, r.info);
2699 if (taskTop != null) {
2700 if (taskTop.task.intent == null) {
2701 // This task was started because of movement of
2702 // the activity based on affinity... now that we
2703 // are actually launching it, we can assign the
2704 // base intent.
2705 taskTop.task.setIntent(intent, r.info);
2706 }
2707 // If the target task is not in the front, then we need
2708 // to bring it to the front... except... well, with
2709 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2710 // to have the same behavior as if a new instance was
2711 // being started, which means not bringing it to the front
2712 // if the caller is not itself in the front.
2713 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002714 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002715 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2716 boolean callerAtFront = sourceRecord == null
2717 || curTop.task == sourceRecord.task;
2718 if (callerAtFront) {
2719 // We really do want to push this one into the
2720 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002721 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002722 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002723 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002724 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002725 }
2726 }
2727 // If the caller has requested that the target task be
2728 // reset, then do so.
2729 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2730 taskTop = resetTaskIfNeededLocked(taskTop, r);
2731 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002732 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002733 // We don't need to start a new activity, and
2734 // the client said not to do anything if that
2735 // is the case, so this is it! And for paranoia, make
2736 // sure we have correctly resumed the top activity.
2737 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002738 resumeTopActivityLocked(null, options);
2739 } else {
2740 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002742 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002744 if ((launchFlags &
2745 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2746 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2747 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002748 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002749 // not be too hard...
2750 reuseTask = taskTop.task;
2751 performClearTaskLocked(taskTop.task.taskId);
2752 reuseTask.setIntent(r.intent, r.info);
2753 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002754 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2755 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2756 // In this situation we want to remove all activities
2757 // from the task up to the one being started. In most
2758 // cases this means we are resetting the task to its
2759 // initial state.
2760 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002761 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002762 if (top != null) {
2763 if (top.frontOfTask) {
2764 // Activity aliases may mean we use different
2765 // intents for the top activity, so make sure
2766 // the task now has the identity of the new
2767 // intent.
2768 top.task.setIntent(r.intent, r.info);
2769 }
2770 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002771 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002772 } else {
2773 // A special case: we need to
2774 // start the activity because it is not currently
2775 // running, and the caller has asked to clear the
2776 // current task to have this activity at the top.
2777 addingToTask = true;
2778 // Now pretend like this activity is being started
2779 // by the top of its task, so it is put in the
2780 // right place.
2781 sourceRecord = taskTop;
2782 }
2783 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2784 // In this case the top activity on the task is the
2785 // same as the one being launched, so we take that
2786 // as a request to bring the task to the foreground.
2787 // If the top activity in the task is the root
2788 // activity, deliver this new intent to it if it
2789 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002790 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2791 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002792 && taskTop.realActivity.equals(r.realActivity)) {
2793 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2794 if (taskTop.frontOfTask) {
2795 taskTop.task.setIntent(r.intent, r.info);
2796 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002797 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002798 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2799 // In this case we are launching the root activity
2800 // of the task, but with a different intent. We
2801 // should start a new instance on top.
2802 addingToTask = true;
2803 sourceRecord = taskTop;
2804 }
2805 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2806 // In this case an activity is being launched in to an
2807 // existing task, without resetting that task. This
2808 // is typically the situation of launching an activity
2809 // from a notification or shortcut. We want to place
2810 // the new activity on top of the current task.
2811 addingToTask = true;
2812 sourceRecord = taskTop;
2813 } else if (!taskTop.task.rootWasReset) {
2814 // In this case we are launching in to an existing task
2815 // that has not yet been started from its front door.
2816 // The current task has been brought to the front.
2817 // Ideally, we'd probably like to place this new task
2818 // at the bottom of its stack, but that's a little hard
2819 // to do with the current organization of the code so
2820 // for now we'll just drop it.
2821 taskTop.task.setIntent(r.intent, r.info);
2822 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002823 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002824 // We didn't do anything... but it was needed (a.k.a., client
2825 // don't use that intent!) And for paranoia, make
2826 // sure we have correctly resumed the top activity.
2827 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002828 resumeTopActivityLocked(null, options);
2829 } else {
2830 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002831 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002832 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002833 }
2834 }
2835 }
2836 }
2837
2838 //String uri = r.intent.toURI();
2839 //Intent intent2 = new Intent(uri);
2840 //Slog.i(TAG, "Given intent: " + r.intent);
2841 //Slog.i(TAG, "URI is: " + uri);
2842 //Slog.i(TAG, "To intent: " + intent2);
2843
2844 if (r.packageName != null) {
2845 // If the activity being launched is the same as the one currently
2846 // at the top, then we need to check if it should only be launched
2847 // once.
2848 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2849 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002850 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002851 if (top.app != null && top.app.thread != null) {
2852 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2853 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2854 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2855 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2856 // For paranoia, make sure we have correctly
2857 // resumed the top activity.
2858 if (doResume) {
2859 resumeTopActivityLocked(null);
2860 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002861 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002862 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002863 // We don't need to start a new activity, and
2864 // the client said not to do anything if that
2865 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002866 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002868 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002869 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002870 }
2871 }
2872 }
2873 }
2874
2875 } else {
2876 if (r.resultTo != null) {
2877 sendActivityResultLocked(-1,
2878 r.resultTo, r.resultWho, r.requestCode,
2879 Activity.RESULT_CANCELED, null);
2880 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002881 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002882 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002883 }
2884
2885 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002886 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002887
2888 // Should this be considered a new task?
2889 if (r.resultTo == null && !addingToTask
2890 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002891 if (reuseTask == null) {
2892 // todo: should do better management of integers.
2893 mService.mCurTask++;
2894 if (mService.mCurTask <= 0) {
2895 mService.mCurTask = 1;
2896 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002897 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002898 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2899 + " in new task " + r.task);
2900 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002901 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002902 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002903 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002904 if (!movedHome) {
2905 moveHomeToFrontFromLaunchLocked(launchFlags);
2906 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907
2908 } else if (sourceRecord != null) {
2909 if (!addingToTask &&
2910 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2911 // In this case, we are adding the activity to an existing
2912 // task, but the caller has asked to clear that task if the
2913 // activity is already running.
2914 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002915 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002916 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002917 if (top != null) {
2918 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002919 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002920 // For paranoia, make sure we have correctly
2921 // resumed the top activity.
2922 if (doResume) {
2923 resumeTopActivityLocked(null);
2924 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002925 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002926 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002927 }
2928 } else if (!addingToTask &&
2929 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2930 // In this case, we are launching an activity in our own task
2931 // that may already be running somewhere in the history, and
2932 // we want to shuffle it to the front of the stack if so.
2933 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2934 if (where >= 0) {
2935 ActivityRecord top = moveActivityToFrontLocked(where);
2936 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002937 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002938 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002939 if (doResume) {
2940 resumeTopActivityLocked(null);
2941 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002942 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002943 }
2944 }
2945 // An existing activity is starting this new activity, so we want
2946 // to keep the new one in the same task as the one that is starting
2947 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002948 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002949 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2950 + " in existing task " + r.task);
2951
2952 } else {
2953 // This not being started from an existing activity, and not part
2954 // of a new task... just put it in the top task, though these days
2955 // this case should never happen.
2956 final int N = mHistory.size();
2957 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002958 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002959 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002960 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002961 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002962 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2963 + " in new guessed " + r.task);
2964 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002965
Dianne Hackborn39792d22010-08-19 18:01:52 -07002966 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002967 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002968
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002969 if (newTask) {
2970 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2971 }
2972 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002973 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002974 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002975 }
2976
Dianne Hackborna4972e92012-03-14 10:38:05 -07002977 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002978 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002979 // Collect information about the target of the Intent.
2980 ActivityInfo aInfo;
2981 try {
2982 ResolveInfo rInfo =
2983 AppGlobals.getPackageManager().resolveIntent(
2984 intent, resolvedType,
2985 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002986 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002987 aInfo = rInfo != null ? rInfo.activityInfo : null;
2988 } catch (RemoteException e) {
2989 aInfo = null;
2990 }
2991
2992 if (aInfo != null) {
2993 // Store the found target back into the intent, because now that
2994 // we have it we never want to do this again. For example, if the
2995 // user navigates back to this point in the history, we should
2996 // always restart the exact same activity.
2997 intent.setComponent(new ComponentName(
2998 aInfo.applicationInfo.packageName, aInfo.name));
2999
3000 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003001 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003002 if (!aInfo.processName.equals("system")) {
3003 mService.setDebugApp(aInfo.processName, true, false);
3004 }
3005 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003006
Dianne Hackborna4972e92012-03-14 10:38:05 -07003007 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003008 if (!aInfo.processName.equals("system")) {
3009 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3010 }
3011 }
3012
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003013 if (profileFile != null) {
3014 if (!aInfo.processName.equals("system")) {
3015 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003016 profileFile, profileFd,
3017 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003018 }
3019 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003020 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003021 return aInfo;
3022 }
3023
3024 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003025 Intent intent, String resolvedType, IBinder resultTo,
3026 String resultWho, int requestCode, int startFlags, String profileFile,
3027 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3028 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003029 // Refuse possible leaked file descriptors
3030 if (intent != null && intent.hasFileDescriptors()) {
3031 throw new IllegalArgumentException("File descriptors passed in Intent");
3032 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003033 boolean componentSpecified = intent.getComponent() != null;
3034
3035 // Don't modify the client's object!
3036 intent = new Intent(intent);
3037
3038 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003039 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003040 profileFile, profileFd, userId);
Amith Yamasania10d1aa2012-08-21 09:49:53 -07003041 if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_MULTIPROCESS) == 0
3042 && mService.isSingleton(aInfo.processName, aInfo.applicationInfo, null, 0)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07003043 userId = 0;
3044 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003045 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003046
3047 synchronized (mService) {
3048 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003049 if (callingUid >= 0) {
3050 callingPid = -1;
3051 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003052 callingPid = Binder.getCallingPid();
3053 callingUid = Binder.getCallingUid();
3054 } else {
3055 callingPid = callingUid = -1;
3056 }
3057
3058 mConfigWillChange = config != null
3059 && mService.mConfiguration.diff(config) != 0;
3060 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3061 "Starting activity when config will change = " + mConfigWillChange);
3062
3063 final long origId = Binder.clearCallingIdentity();
3064
3065 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003066 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003067 // This may be a heavy-weight process! Check to see if we already
3068 // have another, different heavy-weight process running.
3069 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3070 if (mService.mHeavyWeightProcess != null &&
3071 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3072 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3073 int realCallingPid = callingPid;
3074 int realCallingUid = callingUid;
3075 if (caller != null) {
3076 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3077 if (callerApp != null) {
3078 realCallingPid = callerApp.pid;
3079 realCallingUid = callerApp.info.uid;
3080 } else {
3081 Slog.w(TAG, "Unable to find app for caller " + caller
3082 + " (pid=" + realCallingPid + ") when starting: "
3083 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003084 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003085 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003086 }
3087 }
3088
3089 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003090 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003091 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003092 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003093 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003094
3095 Intent newIntent = new Intent();
3096 if (requestCode >= 0) {
3097 // Caller is requesting a result.
3098 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3099 }
3100 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3101 new IntentSender(target));
3102 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3103 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3104 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3105 hist.packageName);
3106 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3107 hist.task.taskId);
3108 }
3109 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3110 aInfo.packageName);
3111 newIntent.setFlags(intent.getFlags());
3112 newIntent.setClassName("android",
3113 HeavyWeightSwitcherActivity.class.getName());
3114 intent = newIntent;
3115 resolvedType = null;
3116 caller = null;
3117 callingUid = Binder.getCallingUid();
3118 callingPid = Binder.getCallingPid();
3119 componentSpecified = true;
3120 try {
3121 ResolveInfo rInfo =
3122 AppGlobals.getPackageManager().resolveIntent(
3123 intent, null,
3124 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003125 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003126 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003127 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003128 } catch (RemoteException e) {
3129 aInfo = null;
3130 }
3131 }
3132 }
3133 }
3134
3135 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003136 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3137 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003138
3139 if (mConfigWillChange && mMainStack) {
3140 // If the caller also wants to switch to a new configuration,
3141 // do so now. This allows a clean switch, as we are waiting
3142 // for the current activity to pause (so we will not destroy
3143 // it), and have not yet started the next activity.
3144 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3145 "updateConfiguration()");
3146 mConfigWillChange = false;
3147 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3148 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003149 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003150 }
3151
3152 Binder.restoreCallingIdentity(origId);
3153
3154 if (outResult != null) {
3155 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003156 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003157 mWaitingActivityLaunched.add(outResult);
3158 do {
3159 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003160 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003161 } catch (InterruptedException e) {
3162 }
3163 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003164 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003165 ActivityRecord r = this.topRunningActivityLocked(null);
3166 if (r.nowVisible) {
3167 outResult.timeout = false;
3168 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3169 outResult.totalTime = 0;
3170 outResult.thisTime = 0;
3171 } else {
3172 outResult.thisTime = SystemClock.uptimeMillis();
3173 mWaitingActivityVisible.add(outResult);
3174 do {
3175 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003176 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003177 } catch (InterruptedException e) {
3178 }
3179 } while (!outResult.timeout && outResult.who == null);
3180 }
3181 }
3182 }
3183
3184 return res;
3185 }
3186 }
3187
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003188 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003189 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3190 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003191 if (intents == null) {
3192 throw new NullPointerException("intents is null");
3193 }
3194 if (resolvedTypes == null) {
3195 throw new NullPointerException("resolvedTypes is null");
3196 }
3197 if (intents.length != resolvedTypes.length) {
3198 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3199 }
3200
3201 ActivityRecord[] outActivity = new ActivityRecord[1];
3202
3203 int callingPid;
3204 if (callingUid >= 0) {
3205 callingPid = -1;
3206 } else if (caller == null) {
3207 callingPid = Binder.getCallingPid();
3208 callingUid = Binder.getCallingUid();
3209 } else {
3210 callingPid = callingUid = -1;
3211 }
3212 final long origId = Binder.clearCallingIdentity();
3213 try {
3214 synchronized (mService) {
3215
3216 for (int i=0; i<intents.length; i++) {
3217 Intent intent = intents[i];
3218 if (intent == null) {
3219 continue;
3220 }
3221
3222 // Refuse possible leaked file descriptors
3223 if (intent != null && intent.hasFileDescriptors()) {
3224 throw new IllegalArgumentException("File descriptors passed in Intent");
3225 }
3226
3227 boolean componentSpecified = intent.getComponent() != null;
3228
3229 // Don't modify the client's object!
3230 intent = new Intent(intent);
3231
3232 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003233 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003234 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003235 // TODO: New, check if this is correct
3236 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003237
3238 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3239 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3240 throw new IllegalArgumentException(
3241 "FLAG_CANT_SAVE_STATE not supported here");
3242 }
3243
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003244 Bundle theseOptions;
3245 if (options != null && i == intents.length-1) {
3246 theseOptions = options;
3247 } else {
3248 theseOptions = null;
3249 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003250 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003251 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003252 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003253 if (res < 0) {
3254 return res;
3255 }
3256
Dianne Hackbornbe707852011-11-11 14:32:10 -08003257 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003258 }
3259 }
3260 } finally {
3261 Binder.restoreCallingIdentity(origId);
3262 }
3263
Dianne Hackborna4972e92012-03-14 10:38:05 -07003264 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003265 }
3266
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003267 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3268 long thisTime, long totalTime) {
3269 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3270 WaitResult w = mWaitingActivityLaunched.get(i);
3271 w.timeout = timeout;
3272 if (r != null) {
3273 w.who = new ComponentName(r.info.packageName, r.info.name);
3274 }
3275 w.thisTime = thisTime;
3276 w.totalTime = totalTime;
3277 }
3278 mService.notifyAll();
3279 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003280
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003281 void reportActivityVisibleLocked(ActivityRecord r) {
3282 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3283 WaitResult w = mWaitingActivityVisible.get(i);
3284 w.timeout = false;
3285 if (r != null) {
3286 w.who = new ComponentName(r.info.packageName, r.info.name);
3287 }
3288 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3289 w.thisTime = w.totalTime;
3290 }
3291 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003292
3293 if (mDismissKeyguardOnNextActivity) {
3294 mDismissKeyguardOnNextActivity = false;
3295 mService.mWindowManager.dismissKeyguard();
3296 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003297 }
3298
3299 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3300 String resultWho, int requestCode, int resultCode, Intent data) {
3301
3302 if (callingUid > 0) {
3303 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003304 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003305 }
3306
3307 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3308 + " : who=" + resultWho + " req=" + requestCode
3309 + " res=" + resultCode + " data=" + data);
3310 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3311 try {
3312 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3313 list.add(new ResultInfo(resultWho, requestCode,
3314 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003315 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003316 return;
3317 } catch (Exception e) {
3318 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3319 }
3320 }
3321
3322 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3323 }
3324
3325 private final void stopActivityLocked(ActivityRecord r) {
3326 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3327 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3328 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3329 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003330 if (!mService.mSleeping) {
3331 if (DEBUG_STATES) {
3332 Slog.d(TAG, "no-history finish of " + r);
3333 }
3334 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003335 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003336 } else {
3337 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3338 + " on stop because we're just sleeping");
3339 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003340 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003341 }
3342
3343 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003344 if (mMainStack) {
3345 if (mService.mFocusedActivity == r) {
3346 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3347 }
3348 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003349 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003350 try {
3351 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003352 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3353 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003354 r.state = ActivityState.STOPPING;
3355 if (DEBUG_VISBILITY) Slog.v(
3356 TAG, "Stopping visible=" + r.visible + " for " + r);
3357 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003358 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003359 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003360 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003361 if (mService.isSleeping()) {
3362 r.setSleeping(true);
3363 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003364 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3365 msg.obj = r;
3366 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003367 } catch (Exception e) {
3368 // Maybe just ignore exceptions here... if the process
3369 // has crashed, our death notification will clean things
3370 // up.
3371 Slog.w(TAG, "Exception thrown during pause", e);
3372 // Just in case, assume it to be stopped.
3373 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003374 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003375 r.state = ActivityState.STOPPED;
3376 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003377 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003378 }
3379 }
3380 }
3381 }
3382
3383 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3384 boolean remove) {
3385 int N = mStoppingActivities.size();
3386 if (N <= 0) return null;
3387
3388 ArrayList<ActivityRecord> stops = null;
3389
3390 final boolean nowVisible = mResumedActivity != null
3391 && mResumedActivity.nowVisible
3392 && !mResumedActivity.waitingVisible;
3393 for (int i=0; i<N; i++) {
3394 ActivityRecord s = mStoppingActivities.get(i);
3395 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3396 + nowVisible + " waitingVisible=" + s.waitingVisible
3397 + " finishing=" + s.finishing);
3398 if (s.waitingVisible && nowVisible) {
3399 mWaitingVisibleActivities.remove(s);
3400 s.waitingVisible = false;
3401 if (s.finishing) {
3402 // If this activity is finishing, it is sitting on top of
3403 // everyone else but we now know it is no longer needed...
3404 // so get rid of it. Otherwise, we need to go through the
3405 // normal flow and hide it once we determine that it is
3406 // hidden by the activities in front of it.
3407 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003408 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003409 }
3410 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003411 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003412 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3413 if (stops == null) {
3414 stops = new ArrayList<ActivityRecord>();
3415 }
3416 stops.add(s);
3417 mStoppingActivities.remove(i);
3418 N--;
3419 i--;
3420 }
3421 }
3422
3423 return stops;
3424 }
3425
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003426 final void scheduleIdleLocked() {
3427 Message msg = Message.obtain();
3428 msg.what = IDLE_NOW_MSG;
3429 mHandler.sendMessage(msg);
3430 }
3431
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003432 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003433 Configuration config) {
3434 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3435
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003436 ActivityRecord res = null;
3437
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003438 ArrayList<ActivityRecord> stops = null;
3439 ArrayList<ActivityRecord> finishes = null;
3440 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003441 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003442 int NS = 0;
3443 int NF = 0;
3444 int NT = 0;
3445 IApplicationThread sendThumbnail = null;
3446 boolean booting = false;
3447 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003448 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003449
3450 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003451 ActivityRecord r = ActivityRecord.forToken(token);
3452 if (r != null) {
3453 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003454 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003455 }
3456
3457 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003458 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003459 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003460 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003461
3462 if (fromTimeout) {
3463 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3464 }
3465
3466 // This is a hack to semi-deal with a race condition
3467 // in the client where it can be constructed with a
3468 // newer configuration from when we asked it to launch.
3469 // We'll update with whatever configuration it now says
3470 // it used to launch.
3471 if (config != null) {
3472 r.configuration = config;
3473 }
3474
3475 // No longer need to keep the device awake.
3476 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3477 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3478 mLaunchingActivity.release();
3479 }
3480
3481 // We are now idle. If someone is waiting for a thumbnail from
3482 // us, we can now deliver.
3483 r.idle = true;
3484 mService.scheduleAppGcsLocked();
3485 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3486 sendThumbnail = r.app.thread;
3487 r.thumbnailNeeded = false;
3488 }
3489
3490 // If this activity is fullscreen, set up to hide those under it.
3491
3492 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3493 ensureActivitiesVisibleLocked(null, 0);
3494
3495 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3496 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003497 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003498 mService.mBooted = true;
3499 enableScreen = true;
3500 }
3501 }
3502
3503 } else if (fromTimeout) {
3504 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3505 }
3506
3507 // Atomically retrieve all of the other things to do.
3508 stops = processStoppingActivitiesLocked(true);
3509 NS = stops != null ? stops.size() : 0;
3510 if ((NF=mFinishingActivities.size()) > 0) {
3511 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3512 mFinishingActivities.clear();
3513 }
3514 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3515 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3516 mService.mCancelledThumbnails.clear();
3517 }
3518
3519 if (mMainStack) {
3520 booting = mService.mBooting;
3521 mService.mBooting = false;
3522 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003523 if (mStartingUsers.size() > 0) {
3524 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3525 mStartingUsers.clear();
3526 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003527 }
3528
3529 int i;
3530
3531 // Send thumbnail if requested.
3532 if (sendThumbnail != null) {
3533 try {
3534 sendThumbnail.requestThumbnail(token);
3535 } catch (Exception e) {
3536 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3537 mService.sendPendingThumbnail(null, token, null, null, true);
3538 }
3539 }
3540
3541 // Stop any activities that are scheduled to do so but have been
3542 // waiting for the next one to start.
3543 for (i=0; i<NS; i++) {
3544 ActivityRecord r = (ActivityRecord)stops.get(i);
3545 synchronized (mService) {
3546 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003547 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003548 } else {
3549 stopActivityLocked(r);
3550 }
3551 }
3552 }
3553
3554 // Finish any activities that are scheduled to do so but have been
3555 // waiting for the next one to start.
3556 for (i=0; i<NF; i++) {
3557 ActivityRecord r = (ActivityRecord)finishes.get(i);
3558 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003559 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003560 }
3561 }
3562
3563 // Report back to any thumbnail receivers.
3564 for (i=0; i<NT; i++) {
3565 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3566 mService.sendPendingThumbnail(r, null, null, null, true);
3567 }
3568
3569 if (booting) {
3570 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003571 } else if (startingUsers != null) {
3572 for (i=0; i<startingUsers.size(); i++) {
3573 mService.finishUserSwitch(startingUsers.get(i));
3574 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003575 }
3576
3577 mService.trimApplications();
3578 //dump();
3579 //mWindowManager.dump();
3580
3581 if (enableScreen) {
3582 mService.enableScreenAfterBoot();
3583 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003584
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003585 if (activityRemoved) {
3586 resumeTopActivityLocked(null);
3587 }
3588
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003589 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 }
3591
3592 /**
3593 * @return Returns true if the activity is being finished, false if for
3594 * some reason it is being left as-is.
3595 */
3596 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003597 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003599 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003600 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003601 + ", result=" + resultCode + ", data=" + resultData
3602 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003603 if (index < 0) {
3604 return false;
3605 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003606 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003607
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003608 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003609 return true;
3610 }
3611
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003612 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3613 ActivityRecord self = isInStackLocked(token);
3614 if (self == null) {
3615 return;
3616 }
3617
3618 int i;
3619 for (i=mHistory.size()-1; i>=0; i--) {
3620 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3621 if (r.resultTo == self && r.requestCode == requestCode) {
3622 if ((r.resultWho == null && resultWho == null) ||
3623 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3624 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003625 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003626 }
3627 }
3628 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003629 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003630 }
3631
3632 final boolean finishActivityAffinityLocked(IBinder token) {
3633 int index = indexOfTokenLocked(token);
3634 if (DEBUG_RESULTS) Slog.v(
3635 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3636 if (index < 0) {
3637 return false;
3638 }
3639 ActivityRecord r = mHistory.get(index);
3640
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003641 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003642 ActivityRecord cur = mHistory.get(index);
3643 if (cur.task != r.task) {
3644 break;
3645 }
3646 if (cur.taskAffinity == null && r.taskAffinity != null) {
3647 break;
3648 }
3649 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3650 break;
3651 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003652 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3653 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003654 index--;
3655 }
3656 return true;
3657 }
3658
Dianne Hackborn5c607432012-02-28 14:44:19 -08003659 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3660 // send the result
3661 ActivityRecord resultTo = r.resultTo;
3662 if (resultTo != null) {
3663 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3664 + " who=" + r.resultWho + " req=" + r.requestCode
3665 + " res=" + resultCode + " data=" + resultData);
3666 if (r.info.applicationInfo.uid > 0) {
3667 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3668 resultTo.packageName, resultData,
3669 resultTo.getUriPermissionsLocked());
3670 }
3671 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3672 resultData);
3673 r.resultTo = null;
3674 }
3675 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3676
3677 // Make sure this HistoryRecord is not holding on to other resources,
3678 // because clients have remote IPC references to this object so we
3679 // can't assume that will go away and want to avoid circular IPC refs.
3680 r.results = null;
3681 r.pendingResults = null;
3682 r.newIntents = null;
3683 r.icicle = null;
3684 }
3685
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003686 /**
3687 * @return Returns true if this activity has been removed from the history
3688 * list, or false if it is still in the list and will be removed later.
3689 */
3690 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003691 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3692 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003693 }
3694
3695 /**
3696 * @return Returns true if this activity has been removed from the history
3697 * list, or false if it is still in the list and will be removed later.
3698 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003699 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3700 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003701 if (r.finishing) {
3702 Slog.w(TAG, "Duplicate finish request for " + r);
3703 return false;
3704 }
3705
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003706 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003707 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3708 System.identityHashCode(r),
3709 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003710 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003711 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003712 if (next.task == r.task) {
3713 if (r.frontOfTask) {
3714 // The next activity is now the front of the task.
3715 next.frontOfTask = true;
3716 }
3717 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3718 // If the caller asked that this activity (and all above it)
3719 // be cleared when the task is reset, don't lose that information,
3720 // but propagate it up to the next activity.
3721 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3722 }
3723 }
3724 }
3725
3726 r.pauseKeyDispatchingLocked();
3727 if (mMainStack) {
3728 if (mService.mFocusedActivity == r) {
3729 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3730 }
3731 }
3732
Dianne Hackborn5c607432012-02-28 14:44:19 -08003733 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003734
3735 if (mService.mPendingThumbnails.size() > 0) {
3736 // There are clients waiting to receive thumbnails so, in case
3737 // this is an activity that someone is waiting for, add it
3738 // to the pending list so we can correctly update the clients.
3739 mService.mCancelledThumbnails.add(r);
3740 }
3741
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003742 if (immediate) {
3743 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003744 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003745 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003746 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003747 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003748 if (DEBUG_TRANSITION) Slog.v(TAG,
3749 "Prepare close transition: finishing " + r);
3750 mService.mWindowManager.prepareAppTransition(endTask
3751 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003752 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003753
3754 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003755 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003757 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003758 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3759 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3760 startPausingLocked(false, false);
3761 }
3762
3763 } else if (r.state != ActivityState.PAUSING) {
3764 // If the activity is PAUSING, we will complete the finish once
3765 // it is done pausing; else we can just directly finish it here.
3766 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3767 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003768 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003769 } else {
3770 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3771 }
3772
3773 return false;
3774 }
3775
3776 private static final int FINISH_IMMEDIATELY = 0;
3777 private static final int FINISH_AFTER_PAUSE = 1;
3778 private static final int FINISH_AFTER_VISIBLE = 2;
3779
3780 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003781 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003782 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003783 if (index < 0) {
3784 return null;
3785 }
3786
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003787 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003788 }
3789
3790 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003791 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792 // First things first: if this activity is currently visible,
3793 // and the resumed activity is not yet visible, then hold off on
3794 // finishing until the resumed one becomes visible.
3795 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3796 if (!mStoppingActivities.contains(r)) {
3797 mStoppingActivities.add(r);
3798 if (mStoppingActivities.size() > 3) {
3799 // If we already have a few activities waiting to stop,
3800 // then give up on things going idle and start clearing
3801 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003802 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003803 } else {
3804 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003805 }
3806 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003807 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3808 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003809 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003810 if (oomAdj) {
3811 mService.updateOomAdjLocked();
3812 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003813 return r;
3814 }
3815
3816 // make sure the record is cleaned out of other places.
3817 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003818 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003819 mWaitingVisibleActivities.remove(r);
3820 if (mResumedActivity == r) {
3821 mResumedActivity = null;
3822 }
3823 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003824 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003825 r.state = ActivityState.FINISHING;
3826
3827 if (mode == FINISH_IMMEDIATELY
3828 || prevState == ActivityState.STOPPED
3829 || prevState == ActivityState.INITIALIZING) {
3830 // If this activity is already stopped, we can just finish
3831 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003832 boolean activityRemoved = destroyActivityLocked(r, true,
3833 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003834 if (activityRemoved) {
3835 resumeTopActivityLocked(null);
3836 }
3837 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003838 } else {
3839 // Need to go through the full pause cycle to get this
3840 // activity into the stopped state and then finish it.
3841 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3842 mFinishingActivities.add(r);
3843 resumeTopActivityLocked(null);
3844 }
3845 return r;
3846 }
3847
3848 /**
3849 * Perform the common clean-up of an activity record. This is called both
3850 * as part of destroyActivityLocked() (when destroying the client-side
3851 * representation) and cleaning things up as a result of its hosting
3852 * processing going away, in which case there is no remaining client-side
3853 * state to destroy so only the cleanup here is needed.
3854 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003855 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3856 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003857 if (mResumedActivity == r) {
3858 mResumedActivity = null;
3859 }
3860 if (mService.mFocusedActivity == r) {
3861 mService.mFocusedActivity = null;
3862 }
3863
3864 r.configDestroy = false;
3865 r.frozenBeforeDestroy = false;
3866
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003867 if (setState) {
3868 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3869 r.state = ActivityState.DESTROYED;
3870 }
3871
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003872 // Make sure this record is no longer in the pending finishes list.
3873 // This could happen, for example, if we are trimming activities
3874 // down to the max limit while they are still waiting to finish.
3875 mFinishingActivities.remove(r);
3876 mWaitingVisibleActivities.remove(r);
3877
3878 // Remove any pending results.
3879 if (r.finishing && r.pendingResults != null) {
3880 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3881 PendingIntentRecord rec = apr.get();
3882 if (rec != null) {
3883 mService.cancelIntentSenderLocked(rec, false);
3884 }
3885 }
3886 r.pendingResults = null;
3887 }
3888
3889 if (cleanServices) {
3890 cleanUpActivityServicesLocked(r);
3891 }
3892
3893 if (mService.mPendingThumbnails.size() > 0) {
3894 // There are clients waiting to receive thumbnails so, in case
3895 // this is an activity that someone is waiting for, add it
3896 // to the pending list so we can correctly update the clients.
3897 mService.mCancelledThumbnails.add(r);
3898 }
3899
3900 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003901 removeTimeoutsForActivityLocked(r);
3902 }
3903
3904 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003905 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003906 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003907 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003908 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003909 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003910 }
3911
Dianne Hackborn5c607432012-02-28 14:44:19 -08003912 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003913 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003914 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003915 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003916 if (DEBUG_ADD_REMOVE) {
3917 RuntimeException here = new RuntimeException("here");
3918 here.fillInStackTrace();
3919 Slog.i(TAG, "Removing activity " + r + " from stack");
3920 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003921 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003922 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003923 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3924 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003925 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003926 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003927 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003928 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003929 }
3930 cleanUpActivityServicesLocked(r);
3931 r.removeUriPermissionsLocked();
3932 }
3933 }
3934
3935 /**
3936 * Perform clean-up of service connections in an activity record.
3937 */
3938 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3939 // Throw away any services that have been bound by this activity.
3940 if (r.connections != null) {
3941 Iterator<ConnectionRecord> it = r.connections.iterator();
3942 while (it.hasNext()) {
3943 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003944 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003945 }
3946 r.connections = null;
3947 }
3948 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003949
3950 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
3951 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3952 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
3953 mHandler.sendMessage(msg);
3954 }
3955
Dianne Hackborn28695e02011-11-02 21:59:51 -07003956 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003957 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003958 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003959 for (int i=mHistory.size()-1; i>=0; i--) {
3960 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003961 if (r.finishing) {
3962 continue;
3963 }
3964 if (r.fullscreen) {
3965 lastIsOpaque = true;
3966 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003967 if (owner != null && r.app != owner) {
3968 continue;
3969 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003970 if (!lastIsOpaque) {
3971 continue;
3972 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003973 // We can destroy this one if we have its icicle saved and
3974 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003975 if (r.app != null && r != mResumedActivity && r != mPausingActivity
3976 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003977 && r.state != ActivityState.DESTROYING
3978 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003979 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3980 + " resumed=" + mResumedActivity
3981 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003982 if (destroyActivityLocked(r, true, oomAdj, reason)) {
3983 activityRemoved = true;
3984 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003985 }
3986 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003987 if (activityRemoved) {
3988 resumeTopActivityLocked(null);
3989 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003990 }
3991
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003992 /**
3993 * Destroy the current CLIENT SIDE instance of an activity. This may be
3994 * called both when actually finishing an activity, or when performing
3995 * a configuration switch where we destroy the current client-side object
3996 * but then create a new client-side object for this same HistoryRecord.
3997 */
3998 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003999 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004000 if (DEBUG_SWITCH) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004001 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004002 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4003 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
4004 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004005 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004006
4007 boolean removedFromHistory = false;
4008
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004009 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004010
4011 final boolean hadApp = r.app != null;
4012
4013 if (hadApp) {
4014 if (removeFromApp) {
4015 int idx = r.app.activities.indexOf(r);
4016 if (idx >= 0) {
4017 r.app.activities.remove(idx);
4018 }
4019 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4020 mService.mHeavyWeightProcess = null;
4021 mService.mHandler.sendEmptyMessage(
4022 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4023 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004024 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004025 // No longer have activities, so update oom adj.
4026 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004027 }
4028 }
4029
4030 boolean skipDestroy = false;
4031
4032 try {
4033 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004034 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004035 r.configChangeFlags);
4036 } catch (Exception e) {
4037 // We can just ignore exceptions here... if the process
4038 // has crashed, our death notification will clean things
4039 // up.
4040 //Slog.w(TAG, "Exception thrown during finish", e);
4041 if (r.finishing) {
4042 removeActivityFromHistoryLocked(r);
4043 removedFromHistory = true;
4044 skipDestroy = true;
4045 }
4046 }
4047
4048 r.app = null;
4049 r.nowVisible = false;
4050
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004051 // If the activity is finishing, we need to wait on removing it
4052 // from the list to give it a chance to do its cleanup. During
4053 // that time it may make calls back with its token so we need to
4054 // be able to find it on the list and so we don't want to remove
4055 // it from the list yet. Otherwise, we can just immediately put
4056 // it in the destroyed state since we are not removing it from the
4057 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004058 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004059 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4060 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004061 r.state = ActivityState.DESTROYING;
4062 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4063 msg.obj = r;
4064 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4065 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004066 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4067 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004068 r.state = ActivityState.DESTROYED;
4069 }
4070 } else {
4071 // remove this record from the history.
4072 if (r.finishing) {
4073 removeActivityFromHistoryLocked(r);
4074 removedFromHistory = true;
4075 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004076 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4077 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004078 r.state = ActivityState.DESTROYED;
4079 }
4080 }
4081
4082 r.configChangeFlags = 0;
4083
4084 if (!mLRUActivities.remove(r) && hadApp) {
4085 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4086 }
4087
4088 return removedFromHistory;
4089 }
4090
4091 final void activityDestroyed(IBinder token) {
4092 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004093 final long origId = Binder.clearCallingIdentity();
4094 try {
4095 ActivityRecord r = ActivityRecord.forToken(token);
4096 if (r != null) {
4097 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004098 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004099
4100 int index = indexOfActivityLocked(r);
4101 if (index >= 0) {
4102 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004103 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004104 removeActivityFromHistoryLocked(r);
4105 }
4106 }
4107 resumeTopActivityLocked(null);
4108 } finally {
4109 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004110 }
4111 }
4112 }
4113
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004114 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004115 int i = list.size();
4116 if (localLOGV) Slog.v(
4117 TAG, "Removing app " + app + " from list " + list
4118 + " with " + i + " entries");
4119 while (i > 0) {
4120 i--;
4121 ActivityRecord r = (ActivityRecord)list.get(i);
4122 if (localLOGV) Slog.v(
4123 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4124 if (r.app == app) {
4125 if (localLOGV) Slog.v(TAG, "Removing this entry!");
4126 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004127 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004128 }
4129 }
4130 }
4131
4132 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
4133 removeHistoryRecordsForAppLocked(mLRUActivities, app);
4134 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004135 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004136 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
4137 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
4138 }
4139
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004140 /**
4141 * Move the current home activity's task (if one exists) to the front
4142 * of the stack.
4143 */
4144 final void moveHomeToFrontLocked() {
4145 TaskRecord homeTask = null;
4146 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004147 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004148 if (hr.isHomeActivity) {
4149 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004150 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004151 }
4152 }
4153 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004154 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004155 }
4156 }
4157
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004158 final void updateTransitLocked(int transit, Bundle options) {
4159 if (options != null) {
4160 ActivityRecord r = topRunningActivityLocked(null);
4161 if (r != null && r.state != ActivityState.RESUMED) {
4162 r.updateOptionsLocked(options);
4163 } else {
4164 ActivityOptions.abort(options);
4165 }
4166 }
4167 mService.mWindowManager.prepareAppTransition(transit, false);
4168 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004169
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004170 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004171 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4172
4173 final int task = tr.taskId;
4174 int top = mHistory.size()-1;
4175
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004176 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004177 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004178 if (reason != null &&
4179 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4180 ActivityOptions.abort(options);
4181 } else {
4182 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4183 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004184 return;
4185 }
4186
Dianne Hackbornbe707852011-11-11 14:32:10 -08004187 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004188
4189 // Applying the affinities may have removed entries from the history,
4190 // so get the size again.
4191 top = mHistory.size()-1;
4192 int pos = top;
4193
4194 // Shift all activities with this task up to the top
4195 // of the stack, keeping them in the same internal order.
4196 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004197 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004198 if (localLOGV) Slog.v(
4199 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004200 if (r.task.taskId == task) {
4201 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004202 if (DEBUG_ADD_REMOVE) {
4203 RuntimeException here = new RuntimeException("here");
4204 here.fillInStackTrace();
4205 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4206 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004207 mHistory.remove(pos);
4208 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004209 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004210 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004211 }
4212 pos--;
4213 }
4214
4215 if (DEBUG_TRANSITION) Slog.v(TAG,
4216 "Prepare to front transition: task=" + tr);
4217 if (reason != null &&
4218 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004219 mService.mWindowManager.prepareAppTransition(
4220 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004221 ActivityRecord r = topRunningActivityLocked(null);
4222 if (r != null) {
4223 mNoAnimActivities.add(r);
4224 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004225 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004226 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004227 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004228 }
4229
4230 mService.mWindowManager.moveAppTokensToTop(moved);
4231 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004232 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004233 }
4234
4235 finishTaskMoveLocked(task);
4236 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4237 }
4238
4239 private final void finishTaskMoveLocked(int task) {
4240 resumeTopActivityLocked(null);
4241 }
4242
4243 /**
4244 * Worker method for rearranging history stack. Implements the function of moving all
4245 * activities for a specific task (gathering them if disjoint) into a single group at the
4246 * bottom of the stack.
4247 *
4248 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4249 * to premeptively cancel the move.
4250 *
4251 * @param task The taskId to collect and move to the bottom.
4252 * @return Returns true if the move completed, false if not.
4253 */
4254 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4255 Slog.i(TAG, "moveTaskToBack: " + task);
4256
4257 // If we have a watcher, preflight the move before committing to it. First check
4258 // for *other* available tasks, but if none are available, then try again allowing the
4259 // current task to be selected.
4260 if (mMainStack && mService.mController != null) {
4261 ActivityRecord next = topRunningActivityLocked(null, task);
4262 if (next == null) {
4263 next = topRunningActivityLocked(null, 0);
4264 }
4265 if (next != null) {
4266 // ask watcher if this is allowed
4267 boolean moveOK = true;
4268 try {
4269 moveOK = mService.mController.activityResuming(next.packageName);
4270 } catch (RemoteException e) {
4271 mService.mController = null;
4272 }
4273 if (!moveOK) {
4274 return false;
4275 }
4276 }
4277 }
4278
Dianne Hackbornbe707852011-11-11 14:32:10 -08004279 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004280
4281 if (DEBUG_TRANSITION) Slog.v(TAG,
4282 "Prepare to back transition: task=" + task);
4283
4284 final int N = mHistory.size();
4285 int bottom = 0;
4286 int pos = 0;
4287
4288 // Shift all activities with this task down to the bottom
4289 // of the stack, keeping them in the same internal order.
4290 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004291 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004292 if (localLOGV) Slog.v(
4293 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4294 if (r.task.taskId == task) {
4295 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004296 if (DEBUG_ADD_REMOVE) {
4297 RuntimeException here = new RuntimeException("here");
4298 here.fillInStackTrace();
4299 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4300 + bottom, here);
4301 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004302 mHistory.remove(pos);
4303 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004304 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004305 bottom++;
4306 }
4307 pos++;
4308 }
4309
4310 if (reason != null &&
4311 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004312 mService.mWindowManager.prepareAppTransition(
4313 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004314 ActivityRecord r = topRunningActivityLocked(null);
4315 if (r != null) {
4316 mNoAnimActivities.add(r);
4317 }
4318 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004319 mService.mWindowManager.prepareAppTransition(
4320 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004321 }
4322 mService.mWindowManager.moveAppTokensToBottom(moved);
4323 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004324 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004325 }
4326
4327 finishTaskMoveLocked(task);
4328 return true;
4329 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004330
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004331 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4332 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4333 ActivityRecord resumed = mResumedActivity;
4334 if (resumed != null && resumed.thumbHolder == tr) {
4335 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004336 }
4337 return info;
4338 }
4339
Dianne Hackborn15491c62012-09-19 10:59:14 -07004340 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4341 ActivityRecord resumed = mResumedActivity;
4342 if (resumed != null && resumed.task == tr) {
4343 // This task is the current resumed task, we just need to take
4344 // a screenshot of it and return that.
4345 return resumed.stack.screenshotActivities(resumed);
4346 }
4347 // Return the information about the task, to figure out the top
4348 // thumbnail to return.
4349 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4350 if (info.numSubThumbbails <= 0) {
4351 return info.mainThumbnail;
4352 } else {
4353 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
4354 }
4355 }
4356
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004357 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4358 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004359 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4360 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004361 if (taskRequired) {
4362 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4363 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004364 return null;
4365 }
4366
4367 if (subTaskIndex < 0) {
4368 // Just remove the entire task.
4369 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4370 return info.root;
4371 }
4372
4373 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004374 if (taskRequired) {
4375 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4376 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004377 return null;
4378 }
4379
4380 // Remove all of this task's activies starting at the sub task.
4381 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4382 performClearTaskAtIndexLocked(taskId, subtask.index);
4383 return subtask.activity;
4384 }
4385
4386 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004387 final TaskAccessInfo thumbs = new TaskAccessInfo();
4388 // How many different sub-thumbnails?
4389 final int NA = mHistory.size();
4390 int j = 0;
4391 ThumbnailHolder holder = null;
4392 while (j < NA) {
4393 ActivityRecord ar = mHistory.get(j);
4394 if (!ar.finishing && ar.task.taskId == taskId) {
4395 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004396 if (holder != null) {
4397 thumbs.mainThumbnail = holder.lastThumbnail;
4398 }
4399 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004400 break;
4401 }
4402 j++;
4403 }
4404
4405 if (j >= NA) {
4406 return thumbs;
4407 }
4408
4409 thumbs.root = mHistory.get(j);
4410 thumbs.rootIndex = j;
4411
4412 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4413 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004414 while (j < NA) {
4415 ActivityRecord ar = mHistory.get(j);
4416 j++;
4417 if (ar.finishing) {
4418 continue;
4419 }
4420 if (ar.task.taskId != taskId) {
4421 break;
4422 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004423 if (ar.thumbHolder != holder && holder != null) {
4424 thumbs.numSubThumbbails++;
4425 holder = ar.thumbHolder;
4426 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004427 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004428 sub.activity = ar;
4429 sub.index = j-1;
4430 subtasks.add(sub);
4431 }
4432 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004433 if (thumbs.numSubThumbbails > 0) {
4434 thumbs.retriever = new IThumbnailRetriever.Stub() {
4435 public Bitmap getThumbnail(int index) {
4436 if (index < 0 || index >= thumbs.subtasks.size()) {
4437 return null;
4438 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004439 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4440 ActivityRecord resumed = mResumedActivity;
4441 if (resumed != null && resumed.thumbHolder == sub.holder) {
4442 return resumed.stack.screenshotActivities(resumed);
4443 }
4444 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004445 }
4446 };
4447 }
4448 return thumbs;
4449 }
4450
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004451 private final void logStartActivity(int tag, ActivityRecord r,
4452 TaskRecord task) {
4453 EventLog.writeEvent(tag,
4454 System.identityHashCode(r), task.taskId,
4455 r.shortComponentName, r.intent.getAction(),
4456 r.intent.getType(), r.intent.getDataString(),
4457 r.intent.getFlags());
4458 }
4459
4460 /**
4461 * Make sure the given activity matches the current configuration. Returns
4462 * false if the activity had to be destroyed. Returns true if the
4463 * configuration is the same, or the activity will remain running as-is
4464 * for whatever reason. Ensures the HistoryRecord is updated with the
4465 * correct configuration and all other bookkeeping is handled.
4466 */
4467 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4468 int globalChanges) {
4469 if (mConfigWillChange) {
4470 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4471 "Skipping config check (will change): " + r);
4472 return true;
4473 }
4474
4475 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4476 "Ensuring correct configuration: " + r);
4477
4478 // Short circuit: if the two configurations are the exact same
4479 // object (the common case), then there is nothing to do.
4480 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004481 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004482 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4483 "Configuration unchanged in " + r);
4484 return true;
4485 }
4486
4487 // We don't worry about activities that are finishing.
4488 if (r.finishing) {
4489 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4490 "Configuration doesn't matter in finishing " + r);
4491 r.stopFreezingScreenLocked(false);
4492 return true;
4493 }
4494
4495 // Okay we now are going to make this activity have the new config.
4496 // But then we need to figure out how it needs to deal with that.
4497 Configuration oldConfig = r.configuration;
4498 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004499
4500 // Determine what has changed. May be nothing, if this is a config
4501 // that has come back from the app after going idle. In that case
4502 // we just want to leave the official config object now in the
4503 // activity and do nothing else.
4504 final int changes = oldConfig.diff(newConfig);
4505 if (changes == 0 && !r.forceNewConfig) {
4506 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4507 "Configuration no differences in " + r);
4508 return true;
4509 }
4510
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004511 // If the activity isn't currently running, just leave the new
4512 // configuration and it will pick that up next time it starts.
4513 if (r.app == null || r.app.thread == null) {
4514 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4515 "Configuration doesn't matter not running " + r);
4516 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004517 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004518 return true;
4519 }
4520
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004521 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004522 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4523 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4524 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004525 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004526 + ", newConfig=" + newConfig);
4527 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004528 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004529 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4530 r.configChangeFlags |= changes;
4531 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004532 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004533 if (r.app == null || r.app.thread == null) {
4534 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004535 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004536 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004537 } else if (r.state == ActivityState.PAUSING) {
4538 // A little annoying: we are waiting for this activity to
4539 // finish pausing. Let's not do anything now, but just
4540 // flag that it needs to be restarted when done pausing.
4541 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004542 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004543 r.configDestroy = true;
4544 return true;
4545 } else if (r.state == ActivityState.RESUMED) {
4546 // Try to optimize this case: the configuration is changing
4547 // and we need to restart the top, resumed activity.
4548 // Instead of doing the normal handshaking, just say
4549 // "restart!".
4550 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004551 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004552 relaunchActivityLocked(r, r.configChangeFlags, true);
4553 r.configChangeFlags = 0;
4554 } else {
4555 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004556 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004557 relaunchActivityLocked(r, r.configChangeFlags, false);
4558 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004559 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004560
4561 // All done... tell the caller we weren't able to keep this
4562 // activity around.
4563 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004564 }
4565
4566 // Default case: the activity can handle this new configuration, so
4567 // hand it over. Note that we don't need to give it the new
4568 // configuration, since we always send configuration changes to all
4569 // process when they happen so it can just use whatever configuration
4570 // it last got.
4571 if (r.app != null && r.app.thread != null) {
4572 try {
4573 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004574 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004575 } catch (RemoteException e) {
4576 // If process died, whatever.
4577 }
4578 }
4579 r.stopFreezingScreenLocked(false);
4580
4581 return true;
4582 }
4583
4584 private final boolean relaunchActivityLocked(ActivityRecord r,
4585 int changes, boolean andResume) {
4586 List<ResultInfo> results = null;
4587 List<Intent> newIntents = null;
4588 if (andResume) {
4589 results = r.results;
4590 newIntents = r.newIntents;
4591 }
4592 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4593 + " with results=" + results + " newIntents=" + newIntents
4594 + " andResume=" + andResume);
4595 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4596 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4597 r.task.taskId, r.shortComponentName);
4598
4599 r.startFreezingScreenLocked(r.app, 0);
4600
4601 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004602 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4603 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4604 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004605 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004606 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004607 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004608 // Note: don't need to call pauseIfSleepingLocked() here, because
4609 // the caller will only pass in 'andResume' if this activity is
4610 // currently resumed, which implies we aren't sleeping.
4611 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004612 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004613 }
4614
4615 if (andResume) {
4616 r.results = null;
4617 r.newIntents = null;
4618 if (mMainStack) {
4619 mService.reportResumedActivityLocked(r);
4620 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004621 r.state = ActivityState.RESUMED;
4622 } else {
4623 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4624 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004625 }
4626
4627 return true;
4628 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004629
4630 public void dismissKeyguardOnNextActivityLocked() {
4631 mDismissKeyguardOnNextActivity = true;
4632 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004633}