blob: f72d31806bf358217107c121136e57182e908203 [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;
Dianne Hackborne302a162012-05-15 14:58:32 -070055import android.os.Process;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.RemoteException;
57import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070058import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070059import android.util.EventLog;
60import android.util.Log;
61import android.util.Slog;
Craig Mautner59c00972012-07-30 12:10:24 -070062import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070063import android.view.WindowManagerPolicy;
64
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070065import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070066import java.lang.ref.WeakReference;
67import java.util.ArrayList;
68import java.util.Iterator;
69import java.util.List;
70
71/**
72 * State and management of a single stack of activities.
73 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070074final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070075 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070076 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070077 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
78 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
79 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
80 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
81 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
82 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
83 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
84 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
85
Dianne Hackbornce86ba82011-07-13 19:33:41 -070086 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070087 static final boolean DEBUG_ADD_REMOVE = false;
88 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070089
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070090 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
91
92 // How long we wait until giving up on the last activity telling us it
93 // is idle.
94 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070095
96 // Ticks during which we check progress while waiting for an app to launch.
97 static final int LAUNCH_TICK = 500;
98
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070099 // How long we wait until giving up on the last activity to pause. This
100 // is short because it directly impacts the responsiveness of starting the
101 // next activity.
102 static final int PAUSE_TIMEOUT = 500;
103
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700104 // How long we wait for the activity to tell us it has stopped before
105 // giving up. This is a good amount of time because we really need this
106 // from the application in order to get its saved state.
107 static final int STOP_TIMEOUT = 10*1000;
108
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800109 // How long we can hold the sleep wake lock before giving up.
110 static final int SLEEP_TIMEOUT = 5*1000;
111
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700112 // How long we can hold the launch wake lock before giving up.
113 static final int LAUNCH_TIMEOUT = 10*1000;
114
115 // How long we wait until giving up on an activity telling us it has
116 // finished destroying itself.
117 static final int DESTROY_TIMEOUT = 10*1000;
118
119 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800120 // disabled.
121 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700122
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700123 // How long between activity launches that we consider safe to not warn
124 // the user about an unexpected activity being launched on top.
125 static final long START_WARN_TIME = 5*1000;
126
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700127 // Set to false to disable the preview that is shown while a new activity
128 // is being started.
129 static final boolean SHOW_APP_STARTING_PREVIEW = true;
130
131 enum ActivityState {
132 INITIALIZING,
133 RESUMED,
134 PAUSING,
135 PAUSED,
136 STOPPING,
137 STOPPED,
138 FINISHING,
139 DESTROYING,
140 DESTROYED
141 }
142
143 final ActivityManagerService mService;
144 final boolean mMainStack;
145
146 final Context mContext;
147
148 /**
149 * The back history of all previous (and possibly still
150 * running) activities. It contains HistoryRecord objects.
151 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700152 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800153
154 /**
155 * Used for validating app tokens with window manager.
156 */
157 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
158
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700159 /**
160 * List of running activities, sorted by recent usage.
161 * The first entry in the list is the least recently used.
162 * It contains HistoryRecord objects.
163 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700164 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700165
166 /**
167 * List of activities that are waiting for a new activity
168 * to become visible before completing whatever operation they are
169 * supposed to do.
170 */
171 final ArrayList<ActivityRecord> mWaitingVisibleActivities
172 = new ArrayList<ActivityRecord>();
173
174 /**
175 * List of activities that are ready to be stopped, but waiting
176 * for the next activity to settle down before doing so. It contains
177 * HistoryRecord objects.
178 */
179 final ArrayList<ActivityRecord> mStoppingActivities
180 = new ArrayList<ActivityRecord>();
181
182 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800183 * List of activities that are in the process of going to sleep.
184 */
185 final ArrayList<ActivityRecord> mGoingToSleepActivities
186 = new ArrayList<ActivityRecord>();
187
188 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700189 * Animations that for the current transition have requested not to
190 * be considered for the transition animation.
191 */
192 final ArrayList<ActivityRecord> mNoAnimActivities
193 = new ArrayList<ActivityRecord>();
194
195 /**
196 * List of activities that are ready to be finished, but waiting
197 * for the previous activity to settle down before doing so. It contains
198 * HistoryRecord objects.
199 */
200 final ArrayList<ActivityRecord> mFinishingActivities
201 = new ArrayList<ActivityRecord>();
202
203 /**
204 * List of people waiting to find out about the next launched activity.
205 */
206 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
207 = new ArrayList<IActivityManager.WaitResult>();
208
209 /**
210 * List of people waiting to find out about the next visible activity.
211 */
212 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
213 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700214
215 final ArrayList<UserStartedState> mStartingUsers
216 = new ArrayList<UserStartedState>();
217
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700218 /**
219 * Set when the system is going to sleep, until we have
220 * successfully paused the current activity and released our wake lock.
221 * At that point the system is allowed to actually sleep.
222 */
223 final PowerManager.WakeLock mGoingToSleep;
224
225 /**
226 * We don't want to allow the device to go to sleep while in the process
227 * of launching an activity. This is primarily to allow alarm intent
228 * receivers to launch an activity and get that to run before the device
229 * goes back to sleep.
230 */
231 final PowerManager.WakeLock mLaunchingActivity;
232
233 /**
234 * When we are in the process of pausing an activity, before starting the
235 * next one, this variable holds the activity that is currently being paused.
236 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800237 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700238
239 /**
240 * This is the last activity that we put into the paused state. This is
241 * used to determine if we need to do an activity transition while sleeping,
242 * when we normally hold the top activity paused.
243 */
244 ActivityRecord mLastPausedActivity = null;
245
246 /**
247 * Current activity that is resumed, or null if there is none.
248 */
249 ActivityRecord mResumedActivity = null;
250
251 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700252 * This is the last activity that has been started. It is only used to
253 * identify when multiple activities are started at once so that the user
254 * can be warned they may not be in the activity they think they are.
255 */
256 ActivityRecord mLastStartedActivity = null;
257
258 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700259 * Set when we know we are going to be calling updateConfiguration()
260 * soon, so want to skip intermediate config checks.
261 */
262 boolean mConfigWillChange;
263
264 /**
265 * Set to indicate whether to issue an onUserLeaving callback when a
266 * newly launched activity is being brought in front of us.
267 */
268 boolean mUserLeaving = false;
269
270 long mInitialStartTime = 0;
271
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800272 /**
273 * Set when we have taken too long waiting to go to sleep.
274 */
275 boolean mSleepTimeout = false;
276
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700277 /**
278 * Dismiss the keyguard after the next activity is displayed?
279 */
280 boolean mDismissKeyguardOnNextActivity = false;
281
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800282 int mThumbnailWidth = -1;
283 int mThumbnailHeight = -1;
284
Amith Yamasani742a6712011-05-04 14:49:28 -0700285 private int mCurrentUser;
286
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800287 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
288 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
289 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
290 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
291 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
292 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
293 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700294 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700295 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700296 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
297
298 static class ScheduleDestroyArgs {
299 final ProcessRecord mOwner;
300 final boolean mOomAdj;
301 final String mReason;
302 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
303 mOwner = owner;
304 mOomAdj = oomAdj;
305 mReason = reason;
306 }
307 }
308
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700309 final Handler mHandler = new Handler() {
310 //public Handler() {
311 // if (localLOGV) Slog.v(TAG, "Handler started!");
312 //}
313
314 public void handleMessage(Message msg) {
315 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800316 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700317 synchronized (mService) {
318 if (mService.isSleeping()) {
319 Slog.w(TAG, "Sleep timeout! Sleeping now.");
320 mSleepTimeout = true;
321 checkReadyForSleepLocked();
322 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800323 }
324 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700325 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800326 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700327 // We don't at this point know if the activity is fullscreen,
328 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800329 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700330 synchronized (mService) {
331 if (r.app != null) {
332 mService.logAppTooSlow(r.app, r.pauseTime,
333 "pausing " + r);
334 }
335 }
336
Dianne Hackbornbe707852011-11-11 14:32:10 -0800337 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700338 } break;
339 case IDLE_TIMEOUT_MSG: {
340 if (mService.mDidDexOpt) {
341 mService.mDidDexOpt = false;
342 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
343 nmsg.obj = msg.obj;
344 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
345 return;
346 }
347 // We don't at this point know if the activity is fullscreen,
348 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800349 ActivityRecord r = (ActivityRecord)msg.obj;
350 Slog.w(TAG, "Activity idle timeout for " + r);
351 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700352 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700353 case LAUNCH_TICK_MSG: {
354 ActivityRecord r = (ActivityRecord)msg.obj;
355 synchronized (mService) {
356 if (r.continueLaunchTickingLocked()) {
357 mService.logAppTooSlow(r.app, r.launchTickTime,
358 "launching " + r);
359 }
360 }
361 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700362 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800363 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700364 // We don't at this point know if the activity is fullscreen,
365 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800366 Slog.w(TAG, "Activity destroy timeout for " + r);
367 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700368 } break;
369 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800370 ActivityRecord r = (ActivityRecord)msg.obj;
371 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700372 } break;
373 case LAUNCH_TIMEOUT_MSG: {
374 if (mService.mDidDexOpt) {
375 mService.mDidDexOpt = false;
376 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
377 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
378 return;
379 }
380 synchronized (mService) {
381 if (mLaunchingActivity.isHeld()) {
382 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
383 mLaunchingActivity.release();
384 }
385 }
386 } break;
387 case RESUME_TOP_ACTIVITY_MSG: {
388 synchronized (mService) {
389 resumeTopActivityLocked(null);
390 }
391 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700392 case STOP_TIMEOUT_MSG: {
393 ActivityRecord r = (ActivityRecord)msg.obj;
394 // We don't at this point know if the activity is fullscreen,
395 // so we need to be conservative and assume it isn't.
396 Slog.w(TAG, "Activity stop timeout for " + r);
397 synchronized (mService) {
398 if (r.isInHistory()) {
399 activityStoppedLocked(r, null, null, null);
400 }
401 }
402 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700403 case DESTROY_ACTIVITIES_MSG: {
404 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
405 synchronized (mService) {
406 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
407 }
408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700409 }
410 }
411 };
412
413 ActivityStack(ActivityManagerService service, Context context, boolean mainStack) {
414 mService = service;
415 mContext = context;
416 mMainStack = mainStack;
417 PowerManager pm =
418 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
419 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
420 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
421 mLaunchingActivity.setReferenceCounted(false);
422 }
423
424 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
425 int i = mHistory.size()-1;
426 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700427 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700428 if (!r.finishing && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700429 return r;
430 }
431 i--;
432 }
433 return null;
434 }
435
436 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
437 int i = mHistory.size()-1;
438 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700439 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700440 if (!r.finishing && !r.delayedResume && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700441 return r;
442 }
443 i--;
444 }
445 return null;
446 }
447
448 /**
449 * This is a simplified version of topRunningActivityLocked that provides a number of
450 * optional skip-over modes. It is intended for use with the ActivityController hook only.
451 *
452 * @param token If non-null, any history records matching this token will be skipped.
453 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
454 *
455 * @return Returns the HistoryRecord of the next activity on the stack.
456 */
457 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
458 int i = mHistory.size()-1;
459 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700460 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700461 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700462 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
463 && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700464 return r;
465 }
466 i--;
467 }
468 return null;
469 }
470
471 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800472 return mHistory.indexOf(ActivityRecord.forToken(token));
473 }
474
475 final int indexOfActivityLocked(ActivityRecord r) {
476 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700477 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700478
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700479 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800480 ActivityRecord r = ActivityRecord.forToken(token);
481 if (mHistory.contains(r)) {
482 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700483 }
484 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700485 }
486
487 private final boolean updateLRUListLocked(ActivityRecord r) {
488 final boolean hadit = mLRUActivities.remove(r);
489 mLRUActivities.add(r);
490 return hadit;
491 }
492
493 /**
494 * Returns the top activity in any existing task matching the given
495 * Intent. Returns null if no such task is found.
496 */
497 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
498 ComponentName cls = intent.getComponent();
499 if (info.targetActivity != null) {
500 cls = new ComponentName(info.packageName, info.targetActivity);
501 }
502
503 TaskRecord cp = null;
504
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700505 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700506 final int N = mHistory.size();
507 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700508 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700509 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700510 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
511 cp = r.task;
512 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
513 // + "/aff=" + r.task.affinity + " to new cls="
514 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
515 if (r.task.affinity != null) {
516 if (r.task.affinity.equals(info.taskAffinity)) {
517 //Slog.i(TAG, "Found matching affinity!");
518 return r;
519 }
520 } else if (r.task.intent != null
521 && r.task.intent.getComponent().equals(cls)) {
522 //Slog.i(TAG, "Found matching class!");
523 //dump();
524 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
525 return r;
526 } else if (r.task.affinityIntent != null
527 && r.task.affinityIntent.getComponent().equals(cls)) {
528 //Slog.i(TAG, "Found matching class!");
529 //dump();
530 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
531 return r;
532 }
533 }
534 }
535
536 return null;
537 }
538
539 /**
540 * Returns the first activity (starting from the top of the stack) that
541 * is the same as the given activity. Returns null if no such activity
542 * is found.
543 */
544 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
545 ComponentName cls = intent.getComponent();
546 if (info.targetActivity != null) {
547 cls = new ComponentName(info.packageName, info.targetActivity);
548 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700549 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700550
551 final int N = mHistory.size();
552 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700553 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700554 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700555 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700556 //Slog.i(TAG, "Found matching class!");
557 //dump();
558 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
559 return r;
560 }
561 }
562 }
563
564 return null;
565 }
566
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700567 final void showAskCompatModeDialogLocked(ActivityRecord r) {
568 Message msg = Message.obtain();
569 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
570 msg.obj = r.task.askedCompatMode ? null : r;
571 mService.mHandler.sendMessage(msg);
572 }
573
Amith Yamasani742a6712011-05-04 14:49:28 -0700574 /*
575 * Move the activities around in the stack to bring a user to the foreground.
576 * @return whether there are any activities for the specified user.
577 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700578 final boolean switchUserLocked(int userId, UserStartedState uss) {
579 mCurrentUser = userId;
580 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700581
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700582 // Only one activity? Nothing to do...
583 if (mHistory.size() < 2)
584 return false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700585
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700586 boolean haveActivities = false;
587 // Check if the top activity is from the new user.
588 ActivityRecord top = mHistory.get(mHistory.size() - 1);
589 if (top.userId == userId) return true;
590 // Otherwise, move the user's activities to the top.
591 int N = mHistory.size();
592 int i = 0;
593 while (i < N) {
594 ActivityRecord r = mHistory.get(i);
595 if (r.userId == userId) {
596 ActivityRecord moveToTop = mHistory.remove(i);
597 mHistory.add(moveToTop);
598 // No need to check the top one now
599 N--;
600 haveActivities = true;
601 } else {
602 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700603 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700604 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700605 // Transition from the old top to the new top
606 resumeTopActivityLocked(top);
607 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700608 }
609
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700610 final boolean realStartActivityLocked(ActivityRecord r,
611 ProcessRecord app, boolean andResume, boolean checkConfig)
612 throws RemoteException {
613
614 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800615 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700616
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700617 // schedule launch ticks to collect information about slow apps.
618 r.startLaunchTickingLocked();
619
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700620 // Have the window manager re-evaluate the orientation of
621 // the screen based on the new activity order. Note that
622 // as a result of this, it can call back into the activity
623 // manager with a new orientation. We don't care about that,
624 // because the activity is not currently running so we are
625 // just restarting it anyway.
626 if (checkConfig) {
627 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
628 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800629 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800630 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700631 }
632
633 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700634 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700635
636 if (localLOGV) Slog.v(TAG, "Launching: " + r);
637
638 int idx = app.activities.indexOf(r);
639 if (idx < 0) {
640 app.activities.add(r);
641 }
642 mService.updateLruProcessLocked(app, true, true);
643
644 try {
645 if (app.thread == null) {
646 throw new RemoteException();
647 }
648 List<ResultInfo> results = null;
649 List<Intent> newIntents = null;
650 if (andResume) {
651 results = r.results;
652 newIntents = r.newIntents;
653 }
654 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
655 + " icicle=" + r.icicle
656 + " with results=" + results + " newIntents=" + newIntents
657 + " andResume=" + andResume);
658 if (andResume) {
659 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
660 System.identityHashCode(r),
661 r.task.taskId, r.shortComponentName);
662 }
663 if (r.isHomeActivity) {
664 mService.mHomeProcess = app;
665 }
666 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800667 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400668 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700669 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700670 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700671 String profileFile = null;
672 ParcelFileDescriptor profileFd = null;
673 boolean profileAutoStop = false;
674 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
675 if (mService.mProfileProc == null || mService.mProfileProc == app) {
676 mService.mProfileProc = app;
677 profileFile = mService.mProfileFile;
678 profileFd = mService.mProfileFd;
679 profileAutoStop = mService.mAutoStopProfiler;
680 }
681 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700682 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700683 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700684 if (profileFd != null) {
685 try {
686 profileFd = profileFd.dup();
687 } catch (IOException e) {
688 profileFd = null;
689 }
690 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800691 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800692 System.identityHashCode(r), r.info,
693 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700694 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700695 mService.isNextTransitionForward(), profileFile, profileFd,
696 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700697
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700698 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700699 // This may be a heavy-weight process! Note that the package
700 // manager will ensure that only activity can run in the main
701 // process of the .apk, which is the only thing that will be
702 // considered heavy-weight.
703 if (app.processName.equals(app.info.packageName)) {
704 if (mService.mHeavyWeightProcess != null
705 && mService.mHeavyWeightProcess != app) {
706 Log.w(TAG, "Starting new heavy weight process " + app
707 + " when already running "
708 + mService.mHeavyWeightProcess);
709 }
710 mService.mHeavyWeightProcess = app;
711 Message msg = mService.mHandler.obtainMessage(
712 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
713 msg.obj = r;
714 mService.mHandler.sendMessage(msg);
715 }
716 }
717
718 } catch (RemoteException e) {
719 if (r.launchFailed) {
720 // This is the second time we failed -- finish activity
721 // and give up.
722 Slog.e(TAG, "Second failure launching "
723 + r.intent.getComponent().flattenToShortString()
724 + ", giving up", e);
725 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800726 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700727 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700728 return false;
729 }
730
731 // This is the first time we failed -- restart process and
732 // retry.
733 app.activities.remove(r);
734 throw e;
735 }
736
737 r.launchFailed = false;
738 if (updateLRUListLocked(r)) {
739 Slog.w(TAG, "Activity " + r
740 + " being launched, but already in LRU list");
741 }
742
743 if (andResume) {
744 // As part of the process of launching, ActivityThread also performs
745 // a resume.
746 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700747 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
748 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700749 r.stopped = false;
750 mResumedActivity = r;
751 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800752 if (mMainStack) {
753 mService.addRecentTaskLocked(r.task);
754 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700755 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800756 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700757 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
758 r.icicle = null;
759 r.haveState = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700760 } else {
761 // This activity is not starting in the resumed state... which
762 // should look like we asked it to pause+stop (but remain visible),
763 // and it has done so and reported back the current icicle and
764 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700765 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
766 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700767 r.state = ActivityState.STOPPED;
768 r.stopped = true;
769 }
770
771 // Launch the new version setup screen if needed. We do this -after-
772 // launching the initial activity (that is, home), so that it can have
773 // a chance to initialize itself while in the background, making the
774 // switch back to it faster and look better.
775 if (mMainStack) {
776 mService.startSetupActivityLocked();
777 }
778
779 return true;
780 }
781
782 private final void startSpecificActivityLocked(ActivityRecord r,
783 boolean andResume, boolean checkConfig) {
784 // Is this activity's application already running?
785 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
786 r.info.applicationInfo.uid);
787
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700788 if (r.launchTime == 0) {
789 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700790 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700791 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700792 }
793 } else if (mInitialStartTime == 0) {
794 mInitialStartTime = SystemClock.uptimeMillis();
795 }
796
797 if (app != null && app.thread != null) {
798 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700799 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700800 realStartActivityLocked(r, app, andResume, checkConfig);
801 return;
802 } catch (RemoteException e) {
803 Slog.w(TAG, "Exception when starting activity "
804 + r.intent.getComponent().flattenToShortString(), e);
805 }
806
807 // If a dead object exception was thrown -- fall through to
808 // restart the application.
809 }
810
811 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800812 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700813 }
814
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800815 void stopIfSleepingLocked() {
816 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700817 if (!mGoingToSleep.isHeld()) {
818 mGoingToSleep.acquire();
819 if (mLaunchingActivity.isHeld()) {
820 mLaunchingActivity.release();
821 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
822 }
823 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800824 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
825 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
826 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
827 checkReadyForSleepLocked();
828 }
829 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700830
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800831 void awakeFromSleepingLocked() {
832 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
833 mSleepTimeout = false;
834 if (mGoingToSleep.isHeld()) {
835 mGoingToSleep.release();
836 }
837 // Ensure activities are no longer sleeping.
838 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700839 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800840 r.setSleeping(false);
841 }
842 mGoingToSleepActivities.clear();
843 }
844
845 void activitySleptLocked(ActivityRecord r) {
846 mGoingToSleepActivities.remove(r);
847 checkReadyForSleepLocked();
848 }
849
850 void checkReadyForSleepLocked() {
851 if (!mService.isSleeping()) {
852 // Do not care.
853 return;
854 }
855
856 if (!mSleepTimeout) {
857 if (mResumedActivity != null) {
858 // Still have something resumed; can't sleep until it is paused.
859 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700860 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
861 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800862 return;
863 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800864 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800865 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800866 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800867 return;
868 }
869
870 if (mStoppingActivities.size() > 0) {
871 // Still need to tell some activities to stop; can't sleep yet.
872 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
873 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700874 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800875 return;
876 }
877
878 ensureActivitiesVisibleLocked(null, 0);
879
880 // Make sure any stopped but visible activities are now sleeping.
881 // This ensures that the activity's onStop() is called.
882 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700883 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800884 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
885 r.setSleeping(true);
886 }
887 }
888
889 if (mGoingToSleepActivities.size() > 0) {
890 // Still need to tell some activities to sleep; can't sleep yet.
891 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
892 + mGoingToSleepActivities.size() + " activities");
893 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700894 }
895 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800896
897 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
898
899 if (mGoingToSleep.isHeld()) {
900 mGoingToSleep.release();
901 }
902 if (mService.mShuttingDown) {
903 mService.notifyAll();
904 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700905 }
Craig Mautner59c00972012-07-30 12:10:24 -0700906
Dianne Hackbornd2835932010-12-13 16:28:46 -0800907 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800908 if (who.noDisplay) {
909 return null;
910 }
911
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800912 Resources res = mService.mContext.getResources();
913 int w = mThumbnailWidth;
914 int h = mThumbnailHeight;
915 if (w < 0) {
916 mThumbnailWidth = w =
917 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
918 mThumbnailHeight = h =
919 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
920 }
921
922 if (w > 0) {
Craig Mautner59c00972012-07-30 12:10:24 -0700923 return mService.mWindowManager.screenshotApplications(who.appToken,
924 Display.DEFAULT_DISPLAY, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800925 }
926 return null;
927 }
928
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700929 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800930 if (mPausingActivity != null) {
931 RuntimeException e = new RuntimeException();
932 Slog.e(TAG, "Trying to pause when pause is already pending for "
933 + mPausingActivity, e);
934 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700935 ActivityRecord prev = mResumedActivity;
936 if (prev == null) {
937 RuntimeException e = new RuntimeException();
938 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
939 resumeTopActivityLocked(null);
940 return;
941 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700942 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
943 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700944 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800945 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700946 mLastPausedActivity = prev;
947 prev.state = ActivityState.PAUSING;
948 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700949 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700950
951 mService.updateCpuStats();
952
953 if (prev.app != null && prev.app.thread != null) {
954 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
955 try {
956 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
957 System.identityHashCode(prev),
958 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800959 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
960 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700961 if (mMainStack) {
962 mService.updateUsageStats(prev, false);
963 }
964 } catch (Exception e) {
965 // Ignore exception, if process died other code will cleanup.
966 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800967 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700968 mLastPausedActivity = null;
969 }
970 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800971 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700972 mLastPausedActivity = null;
973 }
974
975 // If we are not going to sleep, we want to ensure the device is
976 // awake until the next activity is started.
977 if (!mService.mSleeping && !mService.mShuttingDown) {
978 mLaunchingActivity.acquire();
979 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
980 // To be safe, don't allow the wake lock to be held for too long.
981 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
982 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
983 }
984 }
985
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800986
987 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700988 // Have the window manager pause its key dispatching until the new
989 // activity has started. If we're pausing the activity just because
990 // the screen is being turned off and the UI is sleeping, don't interrupt
991 // key dispatch; the same activity will pick it up again on wakeup.
992 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800993 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700994 } else {
995 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
996 }
997
998 // Schedule a pause timeout in case the app doesn't respond.
999 // We don't give it much time because this directly impacts the
1000 // responsiveness seen by the user.
1001 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1002 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001003 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001004 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1005 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1006 } else {
1007 // This activity failed to schedule the
1008 // pause, so just treat it as being paused now.
1009 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001010 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001011 }
1012 }
1013
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001014 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001015 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001016 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001017
1018 ActivityRecord r = null;
1019
1020 synchronized (mService) {
1021 int index = indexOfTokenLocked(token);
1022 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001023 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001024 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001025 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001026 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1027 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001028 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001029 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001030 } else {
1031 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
1032 System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001033 mPausingActivity != null
1034 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001035 }
1036 }
1037 }
1038 }
1039
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001040 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1041 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001042 if (r.state != ActivityState.STOPPING) {
1043 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1044 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1045 return;
1046 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001047 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001048 if (icicle != null) {
1049 // If icicle is null, this is happening due to a timeout, so we
1050 // haven't really saved the state.
1051 r.icicle = icicle;
1052 r.haveState = true;
1053 r.updateThumbnail(thumbnail, description);
1054 }
1055 if (!r.stopped) {
1056 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1057 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1058 r.stopped = true;
1059 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001060 if (r.finishing) {
1061 r.clearOptionsLocked();
1062 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001063 if (r.configDestroy) {
1064 destroyActivityLocked(r, true, false, "stop-config");
1065 resumeTopActivityLocked(null);
1066 } else {
1067 // Now that this process has stopped, we may want to consider
1068 // it to be the previous app to try to keep around in case
1069 // the user wants to return to it.
1070 ProcessRecord fgApp = null;
1071 if (mResumedActivity != null) {
1072 fgApp = mResumedActivity.app;
1073 } else if (mPausingActivity != null) {
1074 fgApp = mPausingActivity.app;
1075 }
1076 if (r.app != null && fgApp != null && r.app != fgApp
1077 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1078 && r.app != mService.mHomeProcess) {
1079 mService.mPreviousProcess = r.app;
1080 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1081 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001082 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001083 }
1084 }
1085 }
1086
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001087 private final void completePauseLocked() {
1088 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001089 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1090
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001091 if (prev != null) {
1092 if (prev.finishing) {
1093 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001094 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001095 } else if (prev.app != null) {
1096 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1097 if (prev.waitingVisible) {
1098 prev.waitingVisible = false;
1099 mWaitingVisibleActivities.remove(prev);
1100 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1101 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001102 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001103 if (prev.configDestroy) {
1104 // The previous is being paused because the configuration
1105 // is changing, which means it is actually stopping...
1106 // To juggle the fact that we are also starting a new
1107 // instance right now, we need to first completely stop
1108 // the current instance before starting the new one.
1109 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1110 destroyActivityLocked(prev, true, false, "pause-config");
1111 } else {
1112 mStoppingActivities.add(prev);
1113 if (mStoppingActivities.size() > 3) {
1114 // If we already have a few activities waiting to stop,
1115 // then give up on things going idle and start clearing
1116 // them out.
1117 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1118 scheduleIdleLocked();
1119 } else {
1120 checkReadyForSleepLocked();
1121 }
1122 }
1123 } else {
1124 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1125 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001126 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001127 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001128 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001129
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001130 if (!mService.isSleeping()) {
1131 resumeTopActivityLocked(prev);
1132 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001133 checkReadyForSleepLocked();
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001134 if (topRunningActivityLocked(null) == null) {
1135 // If there are no more activities available to run, then
1136 // do resume anyway to start something.
1137 resumeTopActivityLocked(null);
1138 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001139 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001140
1141 if (prev != null) {
1142 prev.resumeKeyDispatchingLocked();
1143 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001144
1145 if (prev.app != null && prev.cpuTimeAtResume > 0
1146 && mService.mBatteryStatsService.isOnBattery()) {
1147 long diff = 0;
1148 synchronized (mService.mProcessStatsThread) {
1149 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1150 - prev.cpuTimeAtResume;
1151 }
1152 if (diff > 0) {
1153 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1154 synchronized (bsi) {
1155 BatteryStatsImpl.Uid.Proc ps =
1156 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1157 prev.info.packageName);
1158 if (ps != null) {
1159 ps.addForegroundTimeLocked(diff);
1160 }
1161 }
1162 }
1163 }
1164 prev.cpuTimeAtResume = 0; // reset it
1165 }
1166
1167 /**
1168 * Once we know that we have asked an application to put an activity in
1169 * the resumed state (either by launching it or explicitly telling it),
1170 * this function updates the rest of our state to match that fact.
1171 */
1172 private final void completeResumeLocked(ActivityRecord next) {
1173 next.idle = false;
1174 next.results = null;
1175 next.newIntents = null;
1176
1177 // schedule an idle timeout in case the app doesn't do it for us.
1178 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1179 msg.obj = next;
1180 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1181
1182 if (false) {
1183 // The activity was never told to pause, so just keep
1184 // things going as-is. To maintain our own state,
1185 // we need to emulate it coming back and saying it is
1186 // idle.
1187 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1188 msg.obj = next;
1189 mHandler.sendMessage(msg);
1190 }
1191
1192 if (mMainStack) {
1193 mService.reportResumedActivityLocked(next);
1194 }
1195
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001196 next.clearThumbnail();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001197 if (mMainStack) {
1198 mService.setFocusedActivityLocked(next);
1199 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001200 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001201 ensureActivitiesVisibleLocked(null, 0);
1202 mService.mWindowManager.executeAppTransition();
1203 mNoAnimActivities.clear();
1204
1205 // Mark the point when the activity is resuming
1206 // TODO: To be more accurate, the mark should be before the onCreate,
1207 // not after the onResume. But for subsequent starts, onResume is fine.
1208 if (next.app != null) {
1209 synchronized (mService.mProcessStatsThread) {
1210 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1211 }
1212 } else {
1213 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1214 }
1215 }
1216
1217 /**
1218 * Make sure that all activities that need to be visible (that is, they
1219 * currently can be seen by the user) actually are.
1220 */
1221 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1222 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1223 if (DEBUG_VISBILITY) Slog.v(
1224 TAG, "ensureActivitiesVisible behind " + top
1225 + " configChanges=0x" + Integer.toHexString(configChanges));
1226
1227 // If the top activity is not fullscreen, then we need to
1228 // make sure any activities under it are now visible.
1229 final int count = mHistory.size();
1230 int i = count-1;
1231 while (mHistory.get(i) != top) {
1232 i--;
1233 }
1234 ActivityRecord r;
1235 boolean behindFullscreen = false;
1236 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001237 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001238 if (DEBUG_VISBILITY) Slog.v(
1239 TAG, "Make visible? " + r + " finishing=" + r.finishing
1240 + " state=" + r.state);
1241 if (r.finishing) {
1242 continue;
1243 }
1244
1245 final boolean doThisProcess = onlyThisProcess == null
1246 || onlyThisProcess.equals(r.processName);
1247
1248 // First: if this is not the current activity being started, make
1249 // sure it matches the current configuration.
1250 if (r != starting && doThisProcess) {
1251 ensureActivityConfigurationLocked(r, 0);
1252 }
1253
1254 if (r.app == null || r.app.thread == null) {
1255 if (onlyThisProcess == null
1256 || onlyThisProcess.equals(r.processName)) {
1257 // This activity needs to be visible, but isn't even
1258 // running... get it started, but don't resume it
1259 // at this point.
1260 if (DEBUG_VISBILITY) Slog.v(
1261 TAG, "Start and freeze screen for " + r);
1262 if (r != starting) {
1263 r.startFreezingScreenLocked(r.app, configChanges);
1264 }
1265 if (!r.visible) {
1266 if (DEBUG_VISBILITY) Slog.v(
1267 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001268 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001269 }
1270 if (r != starting) {
1271 startSpecificActivityLocked(r, false, false);
1272 }
1273 }
1274
1275 } else if (r.visible) {
1276 // If this activity is already visible, then there is nothing
1277 // else to do here.
1278 if (DEBUG_VISBILITY) Slog.v(
1279 TAG, "Skipping: already visible at " + r);
1280 r.stopFreezingScreenLocked(false);
1281
1282 } else if (onlyThisProcess == null) {
1283 // This activity is not currently visible, but is running.
1284 // Tell it to become visible.
1285 r.visible = true;
1286 if (r.state != ActivityState.RESUMED && r != starting) {
1287 // If this activity is paused, tell it
1288 // to now show its window.
1289 if (DEBUG_VISBILITY) Slog.v(
1290 TAG, "Making visible and scheduling visibility: " + r);
1291 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001292 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001293 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001294 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001295 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001296 r.stopFreezingScreenLocked(false);
1297 } catch (Exception e) {
1298 // Just skip on any failure; we'll make it
1299 // visible when it next restarts.
1300 Slog.w(TAG, "Exception thrown making visibile: "
1301 + r.intent.getComponent(), e);
1302 }
1303 }
1304 }
1305
1306 // Aggregate current change flags.
1307 configChanges |= r.configChangeFlags;
1308
1309 if (r.fullscreen) {
1310 // At this point, nothing else needs to be shown
1311 if (DEBUG_VISBILITY) Slog.v(
1312 TAG, "Stopping: fullscreen at " + r);
1313 behindFullscreen = true;
1314 i--;
1315 break;
1316 }
1317 }
1318
1319 // Now for any activities that aren't visible to the user, make
1320 // sure they no longer are keeping the screen frozen.
1321 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001322 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001323 if (DEBUG_VISBILITY) Slog.v(
1324 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1325 + " state=" + r.state
1326 + " behindFullscreen=" + behindFullscreen);
1327 if (!r.finishing) {
1328 if (behindFullscreen) {
1329 if (r.visible) {
1330 if (DEBUG_VISBILITY) Slog.v(
1331 TAG, "Making invisible: " + r);
1332 r.visible = false;
1333 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001334 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001335 if ((r.state == ActivityState.STOPPING
1336 || r.state == ActivityState.STOPPED)
1337 && r.app != null && r.app.thread != null) {
1338 if (DEBUG_VISBILITY) Slog.v(
1339 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001340 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001341 }
1342 } catch (Exception e) {
1343 // Just skip on any failure; we'll make it
1344 // visible when it next restarts.
1345 Slog.w(TAG, "Exception thrown making hidden: "
1346 + r.intent.getComponent(), e);
1347 }
1348 } else {
1349 if (DEBUG_VISBILITY) Slog.v(
1350 TAG, "Already invisible: " + r);
1351 }
1352 } else if (r.fullscreen) {
1353 if (DEBUG_VISBILITY) Slog.v(
1354 TAG, "Now behindFullscreen: " + r);
1355 behindFullscreen = true;
1356 }
1357 }
1358 i--;
1359 }
1360 }
1361
1362 /**
1363 * Version of ensureActivitiesVisible that can easily be called anywhere.
1364 */
1365 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1366 int configChanges) {
1367 ActivityRecord r = topRunningActivityLocked(null);
1368 if (r != null) {
1369 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1370 }
1371 }
1372
1373 /**
1374 * Ensure that the top activity in the stack is resumed.
1375 *
1376 * @param prev The previously resumed activity, for when in the process
1377 * of pausing; can be null to call from elsewhere.
1378 *
1379 * @return Returns true if something is being resumed, or false if
1380 * nothing happened.
1381 */
1382 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001383 return resumeTopActivityLocked(prev, null);
1384 }
1385
1386 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001387 // Find the first activity that is not finishing.
1388 ActivityRecord next = topRunningActivityLocked(null);
1389
1390 // Remember how we'll process this pause/resume situation, and ensure
1391 // that the state is reset however we wind up proceeding.
1392 final boolean userLeaving = mUserLeaving;
1393 mUserLeaving = false;
1394
1395 if (next == null) {
1396 // There are no more activities! Let's just start up the
1397 // Launcher...
1398 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001399 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001400 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001401 }
1402 }
1403
1404 next.delayedResume = false;
1405
1406 // If the top activity is the resumed one, nothing to do.
1407 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1408 // Make sure we have executed any pending transitions, since there
1409 // should be nothing left to do at this point.
1410 mService.mWindowManager.executeAppTransition();
1411 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001412 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001413 return false;
1414 }
1415
1416 // If we are sleeping, and there is no resumed activity, and the top
1417 // activity is paused, well that is the state we want.
1418 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001419 && mLastPausedActivity == next
1420 && (next.state == ActivityState.PAUSED
1421 || next.state == ActivityState.STOPPED
1422 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001423 // Make sure we have executed any pending transitions, since there
1424 // should be nothing left to do at this point.
1425 mService.mWindowManager.executeAppTransition();
1426 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001427 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001428 return false;
1429 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001430
1431 // Make sure that the user who owns this activity is started. If not,
1432 // we will just leave it as is because someone should be bringing
1433 // another user's activities to the top of the stack.
1434 if (mService.mStartedUsers.get(next.userId) == null) {
1435 Slog.w(TAG, "Skipping resume of top activity " + next
1436 + ": user " + next.userId + " is stopped");
1437 return false;
1438 }
1439
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001440 // The activity may be waiting for stop, but that is no longer
1441 // appropriate for it.
1442 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001443 mGoingToSleepActivities.remove(next);
1444 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001445 mWaitingVisibleActivities.remove(next);
1446
Dianne Hackborn84375872012-06-01 19:03:50 -07001447 next.updateOptionsLocked(options);
1448
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001449 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1450
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001451 // If we are currently pausing an activity, then don't do anything
1452 // until that is done.
1453 if (mPausingActivity != null) {
1454 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: pausing=" + mPausingActivity);
1455 return false;
1456 }
1457
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001458 // Okay we are now going to start a switch, to 'next'. We may first
1459 // have to pause the current activity, but this is an important point
1460 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001461 // XXX "App Redirected" dialog is getting too many false positives
1462 // at this point, so turn off for now.
1463 if (false) {
1464 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1465 long now = SystemClock.uptimeMillis();
1466 final boolean inTime = mLastStartedActivity.startTime != 0
1467 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1468 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1469 final int nextUid = next.info.applicationInfo.uid;
1470 if (inTime && lastUid != nextUid
1471 && lastUid != next.launchedFromUid
1472 && mService.checkPermission(
1473 android.Manifest.permission.STOP_APP_SWITCHES,
1474 -1, next.launchedFromUid)
1475 != PackageManager.PERMISSION_GRANTED) {
1476 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1477 } else {
1478 next.startTime = now;
1479 mLastStartedActivity = next;
1480 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001481 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001482 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001483 mLastStartedActivity = next;
1484 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001485 }
1486
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001487 // We need to start pausing the current activity so the top one
1488 // can be resumed...
1489 if (mResumedActivity != null) {
1490 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
1491 startPausingLocked(userLeaving, false);
1492 return true;
1493 }
1494
Christopher Tated3f175c2012-06-14 14:16:54 -07001495 // If the most recent activity was noHistory but was only stopped rather
1496 // than stopped+finished because the device went to sleep, we need to make
1497 // sure to finish it as we're making a new activity topmost.
1498 final ActivityRecord last = mLastPausedActivity;
1499 if (mService.mSleeping && last != null && !last.finishing) {
1500 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1501 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1502 if (DEBUG_STATES) {
1503 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1504 }
1505 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001506 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001507 }
1508 }
1509
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001510 if (prev != null && prev != next) {
1511 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1512 prev.waitingVisible = true;
1513 mWaitingVisibleActivities.add(prev);
1514 if (DEBUG_SWITCH) Slog.v(
1515 TAG, "Resuming top, waiting visible to hide: " + prev);
1516 } else {
1517 // The next activity is already visible, so hide the previous
1518 // activity's windows right now so we can show the new one ASAP.
1519 // We only do this if the previous is finishing, which should mean
1520 // it is on top of the one being resumed so hiding it quickly
1521 // is good. Otherwise, we want to do the normal route of allowing
1522 // the resumed activity to be shown so we can decide if the
1523 // previous should actually be hidden depending on whether the
1524 // new one is found to be full-screen or not.
1525 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001526 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001527 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1528 + prev + ", waitingVisible="
1529 + (prev != null ? prev.waitingVisible : null)
1530 + ", nowVisible=" + next.nowVisible);
1531 } else {
1532 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1533 + prev + ", waitingVisible="
1534 + (prev != null ? prev.waitingVisible : null)
1535 + ", nowVisible=" + next.nowVisible);
1536 }
1537 }
1538 }
1539
Dianne Hackborne7f97212011-02-24 14:40:20 -08001540 // Launching this app's activity, make sure the app is no longer
1541 // considered stopped.
1542 try {
1543 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001544 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001545 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001546 } catch (IllegalArgumentException e) {
1547 Slog.w(TAG, "Failed trying to unstop package "
1548 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001549 }
1550
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001551 // We are starting up the next activity, so tell the window manager
1552 // that the previous one will be hidden soon. This way it can know
1553 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001554 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001555 if (prev != null) {
1556 if (prev.finishing) {
1557 if (DEBUG_TRANSITION) Slog.v(TAG,
1558 "Prepare close transition: prev=" + prev);
1559 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001560 mService.mWindowManager.prepareAppTransition(
1561 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001562 } else {
1563 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1564 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001565 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001566 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001567 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1568 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001569 } else {
1570 if (DEBUG_TRANSITION) Slog.v(TAG,
1571 "Prepare open transition: prev=" + prev);
1572 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001573 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001574 mService.mWindowManager.prepareAppTransition(
1575 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001576 } else {
1577 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1578 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001579 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001580 }
1581 }
1582 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001583 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1584 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001585 }
1586 } else if (mHistory.size() > 1) {
1587 if (DEBUG_TRANSITION) Slog.v(TAG,
1588 "Prepare open transition: no previous");
1589 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001590 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001591 mService.mWindowManager.prepareAppTransition(
1592 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001593 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001594 mService.mWindowManager.prepareAppTransition(
1595 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001596 }
1597 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001598 if (!noAnim) {
1599 next.applyOptionsLocked();
1600 } else {
1601 next.clearOptionsLocked();
1602 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001603
1604 if (next.app != null && next.app.thread != null) {
1605 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1606
1607 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001608 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001609
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001610 // schedule launch ticks to collect information about slow apps.
1611 next.startLaunchTickingLocked();
1612
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001613 ActivityRecord lastResumedActivity = mResumedActivity;
1614 ActivityState lastState = next.state;
1615
1616 mService.updateCpuStats();
1617
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001618 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001619 next.state = ActivityState.RESUMED;
1620 mResumedActivity = next;
1621 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001622 if (mMainStack) {
1623 mService.addRecentTaskLocked(next.task);
1624 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001625 mService.updateLruProcessLocked(next.app, true, true);
1626 updateLRUListLocked(next);
1627
1628 // Have the window manager re-evaluate the orientation of
1629 // the screen based on the new activity order.
1630 boolean updated = false;
1631 if (mMainStack) {
1632 synchronized (mService) {
1633 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1634 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001635 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001636 if (config != null) {
1637 next.frozenBeforeDestroy = true;
1638 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001639 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001640 }
1641 }
1642 if (!updated) {
1643 // The configuration update wasn't able to keep the existing
1644 // instance of the activity, and instead started a new one.
1645 // We should be all done, but let's just make sure our activity
1646 // is still at the top and schedule another run if something
1647 // weird happened.
1648 ActivityRecord nextNext = topRunningActivityLocked(null);
1649 if (DEBUG_SWITCH) Slog.i(TAG,
1650 "Activity config changed during resume: " + next
1651 + ", new next: " + nextNext);
1652 if (nextNext != next) {
1653 // Do over!
1654 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1655 }
1656 if (mMainStack) {
1657 mService.setFocusedActivityLocked(next);
1658 }
1659 ensureActivitiesVisibleLocked(null, 0);
1660 mService.mWindowManager.executeAppTransition();
1661 mNoAnimActivities.clear();
1662 return true;
1663 }
1664
1665 try {
1666 // Deliver all pending results.
1667 ArrayList a = next.results;
1668 if (a != null) {
1669 final int N = a.size();
1670 if (!next.finishing && N > 0) {
1671 if (DEBUG_RESULTS) Slog.v(
1672 TAG, "Delivering results to " + next
1673 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001674 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001675 }
1676 }
1677
1678 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001679 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001680 }
1681
1682 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
1683 System.identityHashCode(next),
1684 next.task.taskId, next.shortComponentName);
1685
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001686 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001687 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001688 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001689 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001690 mService.isNextTransitionForward());
1691
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001692 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001693
1694 } catch (Exception e) {
1695 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001696 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1697 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001698 next.state = lastState;
1699 mResumedActivity = lastResumedActivity;
1700 Slog.i(TAG, "Restarting because process died: " + next);
1701 if (!next.hasBeenLaunched) {
1702 next.hasBeenLaunched = true;
1703 } else {
1704 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1705 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001706 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001707 mService.compatibilityInfoForPackageLocked(
1708 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001709 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001710 next.labelRes, next.icon, next.windowFlags,
1711 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001712 }
1713 }
1714 startSpecificActivityLocked(next, true, false);
1715 return true;
1716 }
1717
1718 // From this point on, if something goes wrong there is no way
1719 // to recover the activity.
1720 try {
1721 next.visible = true;
1722 completeResumeLocked(next);
1723 } catch (Exception e) {
1724 // If any exception gets thrown, toss away this
1725 // activity and try the next one.
1726 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001727 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001728 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 return true;
1730 }
1731
1732 // Didn't need to use the icicle, and it is now out of date.
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001733 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; didn't need icicle of: " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001734 next.icicle = null;
1735 next.haveState = false;
1736 next.stopped = false;
1737
1738 } else {
1739 // Whoops, need to restart this activity!
1740 if (!next.hasBeenLaunched) {
1741 next.hasBeenLaunched = true;
1742 } else {
1743 if (SHOW_APP_STARTING_PREVIEW) {
1744 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001745 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001746 mService.compatibilityInfoForPackageLocked(
1747 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001748 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001749 next.labelRes, next.icon, next.windowFlags,
1750 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001751 }
1752 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1753 }
1754 startSpecificActivityLocked(next, true, true);
1755 }
1756
1757 return true;
1758 }
1759
1760 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001761 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001762 final int NH = mHistory.size();
1763
1764 int addPos = -1;
1765
1766 if (!newTask) {
1767 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001768 boolean startIt = true;
1769 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001770 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001771 if (p.finishing) {
1772 continue;
1773 }
1774 if (p.task == r.task) {
1775 // Here it is! Now, if this is not yet visible to the
1776 // user, then just add it without starting; it will
1777 // get started when the user navigates back to it.
1778 addPos = i+1;
1779 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001780 if (DEBUG_ADD_REMOVE) {
1781 RuntimeException here = new RuntimeException("here");
1782 here.fillInStackTrace();
1783 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1784 here);
1785 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001787 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001788 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001789 r.info.screenOrientation, r.fullscreen);
1790 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001791 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001792 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001793 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001794 return;
1795 }
1796 break;
1797 }
1798 if (p.fullscreen) {
1799 startIt = false;
1800 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001801 }
1802 }
1803
1804 // Place a new activity at top of stack, so it is next to interact
1805 // with the user.
1806 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001807 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001808 }
1809
1810 // If we are not placing the new activity frontmost, we do not want
1811 // to deliver the onUserLeaving callback to the actual frontmost
1812 // activity
1813 if (addPos < NH) {
1814 mUserLeaving = false;
1815 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1816 }
1817
1818 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001819 if (DEBUG_ADD_REMOVE) {
1820 RuntimeException here = new RuntimeException("here");
1821 here.fillInStackTrace();
1822 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1823 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001824 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001825 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001826 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 if (NH > 0) {
1828 // We want to show the starting preview window if we are
1829 // switching to a new task, or the next activity's process is
1830 // not currently running.
1831 boolean showStartingIcon = newTask;
1832 ProcessRecord proc = r.app;
1833 if (proc == null) {
1834 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1835 }
1836 if (proc == null || proc.thread == null) {
1837 showStartingIcon = true;
1838 }
1839 if (DEBUG_TRANSITION) Slog.v(TAG,
1840 "Prepare open transition: starting " + r);
1841 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001842 mService.mWindowManager.prepareAppTransition(
1843 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001845 } else {
1846 mService.mWindowManager.prepareAppTransition(newTask
1847 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001848 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001849 mNoAnimActivities.remove(r);
1850 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001851 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001852 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001853 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001854 boolean doShow = true;
1855 if (newTask) {
1856 // Even though this activity is starting fresh, we still need
1857 // to reset it to make sure we apply affinities to move any
1858 // existing activities from other tasks in to it.
1859 // If the caller has requested that the target task be
1860 // reset, then do so.
1861 if ((r.intent.getFlags()
1862 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1863 resetTaskIfNeededLocked(r, r);
1864 doShow = topRunningNonDelayedActivityLocked(null) == r;
1865 }
1866 }
1867 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1868 // Figure out if we are transitioning from another activity that is
1869 // "has the same starting icon" as the next one. This allows the
1870 // window manager to keep the previous window it had previously
1871 // created, if it still had one.
1872 ActivityRecord prev = mResumedActivity;
1873 if (prev != null) {
1874 // We don't want to reuse the previous starting preview if:
1875 // (1) The current activity is in a different task.
1876 if (prev.task != r.task) prev = null;
1877 // (2) The current activity is already displayed.
1878 else if (prev.nowVisible) prev = null;
1879 }
1880 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001881 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001882 mService.compatibilityInfoForPackageLocked(
1883 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001884 r.labelRes, r.icon, r.windowFlags,
1885 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001886 }
1887 } else {
1888 // If this is the first activity, don't do any fancy animations,
1889 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001890 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001891 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001892 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001893 }
1894 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001895 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001896 }
1897
1898 if (doResume) {
1899 resumeTopActivityLocked(null);
1900 }
1901 }
1902
Dianne Hackbornbe707852011-11-11 14:32:10 -08001903 final void validateAppTokensLocked() {
1904 mValidateAppTokens.clear();
1905 mValidateAppTokens.ensureCapacity(mHistory.size());
1906 for (int i=0; i<mHistory.size(); i++) {
1907 mValidateAppTokens.add(mHistory.get(i).appToken);
1908 }
1909 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1910 }
1911
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001912 /**
1913 * Perform a reset of the given task, if needed as part of launching it.
1914 * Returns the new HistoryRecord at the top of the task.
1915 */
1916 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1917 ActivityRecord newActivity) {
1918 boolean forceReset = (newActivity.info.flags
1919 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001920 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1921 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001922 if ((newActivity.info.flags
1923 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1924 forceReset = true;
1925 }
1926 }
1927
1928 final TaskRecord task = taskTop.task;
1929
1930 // We are going to move through the history list so that we can look
1931 // at each activity 'target' with 'below' either the interesting
1932 // activity immediately below it in the stack or null.
1933 ActivityRecord target = null;
1934 int targetI = 0;
1935 int taskTopI = -1;
1936 int replyChainEnd = -1;
1937 int lastReparentPos = -1;
1938 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001939 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001940
1941 if (below != null && below.finishing) {
1942 continue;
1943 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001944 // Don't check any lower in the stack if we're crossing a user boundary.
1945 if (below != null && below.userId != taskTop.userId) {
1946 break;
1947 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001948 if (target == null) {
1949 target = below;
1950 targetI = i;
1951 // If we were in the middle of a reply chain before this
1952 // task, it doesn't appear like the root of the chain wants
1953 // anything interesting, so drop it.
1954 replyChainEnd = -1;
1955 continue;
1956 }
1957
1958 final int flags = target.info.flags;
1959
1960 final boolean finishOnTaskLaunch =
1961 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1962 final boolean allowTaskReparenting =
1963 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1964
1965 if (target.task == task) {
1966 // We are inside of the task being reset... we'll either
1967 // finish this activity, push it out for another task,
1968 // or leave it as-is. We only do this
1969 // for activities that are not the root of the task (since
1970 // if we finish the root, we may no longer have the task!).
1971 if (taskTopI < 0) {
1972 taskTopI = targetI;
1973 }
1974 if (below != null && below.task == task) {
1975 final boolean clearWhenTaskReset =
1976 (target.intent.getFlags()
1977 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1978 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1979 // If this activity is sending a reply to a previous
1980 // activity, we can't do anything with it now until
1981 // we reach the start of the reply chain.
1982 // XXX note that we are assuming the result is always
1983 // to the previous activity, which is almost always
1984 // the case but we really shouldn't count on.
1985 if (replyChainEnd < 0) {
1986 replyChainEnd = targetI;
1987 }
1988 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
1989 && target.taskAffinity != null
1990 && !target.taskAffinity.equals(task.affinity)) {
1991 // If this activity has an affinity for another
1992 // task, then we need to move it out of here. We will
1993 // move it as far out of the way as possible, to the
1994 // bottom of the activity stack. This also keeps it
1995 // correctly ordered with any activities we previously
1996 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001997 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001998 if (target.taskAffinity != null
1999 && target.taskAffinity.equals(p.task.affinity)) {
2000 // If the activity currently at the bottom has the
2001 // same task affinity as the one we are moving,
2002 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002003 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002004 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2005 + " out to bottom task " + p.task);
2006 } else {
2007 mService.mCurTask++;
2008 if (mService.mCurTask <= 0) {
2009 mService.mCurTask = 1;
2010 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002011 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2012 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002013 target.task.affinityIntent = target.intent;
2014 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2015 + " out to new task " + target.task);
2016 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002017 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002018 if (replyChainEnd < 0) {
2019 replyChainEnd = targetI;
2020 }
2021 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002022 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002023 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002024 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002025 if (p.finishing) {
2026 continue;
2027 }
2028 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2029 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002030 p.setTask(target.task, curThumbHolder, false);
2031 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002032 if (DEBUG_ADD_REMOVE) {
2033 RuntimeException here = new RuntimeException("here");
2034 here.fillInStackTrace();
2035 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2036 + dstPos, here);
2037 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002038 mHistory.remove(srcPos);
2039 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002040 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2041 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002042 dstPos++;
2043 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002044 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002045 }
2046 i++;
2047 }
2048 if (taskTop == p) {
2049 taskTop = below;
2050 }
2051 if (taskTopI == replyChainEnd) {
2052 taskTopI = -1;
2053 }
2054 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002055 } else if (forceReset || finishOnTaskLaunch
2056 || clearWhenTaskReset) {
2057 // If the activity should just be removed -- either
2058 // because it asks for it, or the task should be
2059 // cleared -- then finish it and anything that is
2060 // part of its reply chain.
2061 if (clearWhenTaskReset) {
2062 // In this case, we want to finish this activity
2063 // and everything above it, so be sneaky and pretend
2064 // like these are all in the reply chain.
2065 replyChainEnd = targetI+1;
2066 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002067 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002068 replyChainEnd)).task == task) {
2069 replyChainEnd++;
2070 }
2071 replyChainEnd--;
2072 } else if (replyChainEnd < 0) {
2073 replyChainEnd = targetI;
2074 }
2075 ActivityRecord p = null;
2076 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002077 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002078 if (p.finishing) {
2079 continue;
2080 }
2081 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002082 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083 replyChainEnd--;
2084 srcPos--;
2085 }
2086 }
2087 if (taskTop == p) {
2088 taskTop = below;
2089 }
2090 if (taskTopI == replyChainEnd) {
2091 taskTopI = -1;
2092 }
2093 replyChainEnd = -1;
2094 } else {
2095 // If we were in the middle of a chain, well the
2096 // activity that started it all doesn't want anything
2097 // special, so leave it all as-is.
2098 replyChainEnd = -1;
2099 }
2100 } else {
2101 // Reached the bottom of the task -- any reply chain
2102 // should be left as-is.
2103 replyChainEnd = -1;
2104 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002105
2106 } else if (target.resultTo != null && (below == null
2107 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002108 // If this activity is sending a reply to a previous
2109 // activity, we can't do anything with it now until
2110 // we reach the start of the reply chain.
2111 // XXX note that we are assuming the result is always
2112 // to the previous activity, which is almost always
2113 // the case but we really shouldn't count on.
2114 if (replyChainEnd < 0) {
2115 replyChainEnd = targetI;
2116 }
2117
2118 } else if (taskTopI >= 0 && allowTaskReparenting
2119 && task.affinity != null
2120 && task.affinity.equals(target.taskAffinity)) {
2121 // We are inside of another task... if this activity has
2122 // an affinity for our task, then either remove it if we are
2123 // clearing or move it over to our task. Note that
2124 // we currently punt on the case where we are resetting a
2125 // task that is not at the top but who has activities above
2126 // with an affinity to it... this is really not a normal
2127 // case, and we will need to later pull that task to the front
2128 // and usually at that point we will do the reset and pick
2129 // up those remaining activities. (This only happens if
2130 // someone starts an activity in a new task from an activity
2131 // in a task that is not currently on top.)
2132 if (forceReset || finishOnTaskLaunch) {
2133 if (replyChainEnd < 0) {
2134 replyChainEnd = targetI;
2135 }
2136 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002137 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2138 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002139 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002140 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 if (p.finishing) {
2142 continue;
2143 }
2144 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002145 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002146 taskTopI--;
2147 lastReparentPos--;
2148 replyChainEnd--;
2149 srcPos--;
2150 }
2151 }
2152 replyChainEnd = -1;
2153 } else {
2154 if (replyChainEnd < 0) {
2155 replyChainEnd = targetI;
2156 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002157 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2158 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002159 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002160 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002161 if (p.finishing) {
2162 continue;
2163 }
2164 if (lastReparentPos < 0) {
2165 lastReparentPos = taskTopI;
2166 taskTop = p;
2167 } else {
2168 lastReparentPos--;
2169 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002170 if (DEBUG_ADD_REMOVE) {
2171 RuntimeException here = new RuntimeException("here");
2172 here.fillInStackTrace();
2173 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2174 + lastReparentPos, here);
2175 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002176 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002177 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002178 mHistory.add(lastReparentPos, p);
2179 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002180 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002181 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002182 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2183 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002184 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002185 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002186 }
2187 }
2188 replyChainEnd = -1;
2189
2190 // Now we've moved it in to place... but what if this is
2191 // a singleTop activity and we have put it on top of another
2192 // instance of the same activity? Then we drop the instance
2193 // below so it remains singleTop.
2194 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2195 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002196 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002197 if (p.finishing) {
2198 continue;
2199 }
2200 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2201 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002202 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002203 taskTopI--;
2204 lastReparentPos--;
2205 }
2206 }
2207 }
2208 }
2209 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002210
2211 } else if (below != null && below.task != target.task) {
2212 // We hit the botton of a task; the reply chain can't
2213 // pass through it.
2214 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002215 }
2216
2217 target = below;
2218 targetI = i;
2219 }
2220
2221 return taskTop;
2222 }
2223
2224 /**
2225 * Perform clear operation as requested by
2226 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2227 * stack to the given task, then look for
2228 * an instance of that activity in the stack and, if found, finish all
2229 * activities on top of it and return the instance.
2230 *
2231 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002232 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002233 * or null if none was found.
2234 */
2235 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002236 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002237 int i = mHistory.size();
2238
2239 // First find the requested task.
2240 while (i > 0) {
2241 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002242 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002243 if (r.task.taskId == taskId) {
2244 i++;
2245 break;
2246 }
2247 }
2248
2249 // Now clear it.
2250 while (i > 0) {
2251 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002252 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002253 if (r.finishing) {
2254 continue;
2255 }
2256 if (r.task.taskId != taskId) {
2257 return null;
2258 }
2259 if (r.realActivity.equals(newR.realActivity)) {
2260 // Here it is! Now finish everything in front...
2261 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002262 while (i < (mHistory.size()-1)) {
2263 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002264 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002265 if (r.task.taskId != taskId) {
2266 break;
2267 }
2268 if (r.finishing) {
2269 continue;
2270 }
2271 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002272 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002273 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002274 }
2275 }
2276
2277 // Finally, if this is a normal launch mode (that is, not
2278 // expecting onNewIntent()), then we will finish the current
2279 // instance of the activity so a new fresh one can be started.
2280 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2281 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2282 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002283 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002284 if (index >= 0) {
2285 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002286 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002287 }
2288 return null;
2289 }
2290 }
2291
2292 return ret;
2293 }
2294 }
2295
2296 return null;
2297 }
2298
2299 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002300 * Completely remove all activities associated with an existing
2301 * task starting at a specified index.
2302 */
2303 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002304 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002305 ActivityRecord r = mHistory.get(i);
2306 if (r.task.taskId != taskId) {
2307 // Whoops hit the end.
2308 return;
2309 }
2310 if (r.finishing) {
2311 i++;
2312 continue;
2313 }
2314 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002315 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002316 i++;
2317 }
2318 }
2319 }
2320
2321 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002322 * Completely remove all activities associated with an existing task.
2323 */
2324 private final void performClearTaskLocked(int taskId) {
2325 int i = mHistory.size();
2326
2327 // First find the requested task.
2328 while (i > 0) {
2329 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002330 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002331 if (r.task.taskId == taskId) {
2332 i++;
2333 break;
2334 }
2335 }
2336
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002337 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002338 while (i > 0) {
2339 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002340 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002341 if (r.finishing) {
2342 continue;
2343 }
2344 if (r.task.taskId != taskId) {
2345 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002346 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002347 return;
2348 }
2349 }
2350 }
2351
2352 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002353 * Find the activity in the history stack within the given task. Returns
2354 * the index within the history at which it's found, or < 0 if not found.
2355 */
2356 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2357 int i = mHistory.size();
2358 while (i > 0) {
2359 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002360 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002361 if (candidate.finishing) {
2362 continue;
2363 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002364 if (candidate.task.taskId != task) {
2365 break;
2366 }
2367 if (candidate.realActivity.equals(r.realActivity)) {
2368 return i;
2369 }
2370 }
2371
2372 return -1;
2373 }
2374
2375 /**
2376 * Reorder the history stack so that the activity at the given index is
2377 * brought to the front.
2378 */
2379 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002380 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002381 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002382 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002383 if (DEBUG_ADD_REMOVE) {
2384 RuntimeException here = new RuntimeException("here");
2385 here.fillInStackTrace();
2386 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2387 + top, here);
2388 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002389 mHistory.add(top, newTop);
2390 oldTop.frontOfTask = false;
2391 newTop.frontOfTask = true;
2392 return newTop;
2393 }
2394
2395 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002396 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002397 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002398 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002399 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002400
Dianne Hackborna4972e92012-03-14 10:38:05 -07002401 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002402
2403 ProcessRecord callerApp = null;
2404 if (caller != null) {
2405 callerApp = mService.getRecordForAppLocked(caller);
2406 if (callerApp != null) {
2407 callingPid = callerApp.pid;
2408 callingUid = callerApp.info.uid;
2409 } else {
2410 Slog.w(TAG, "Unable to find app for caller " + caller
2411 + " (pid=" + callingPid + ") when starting: "
2412 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002413 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002414 }
2415 }
2416
Dianne Hackborna4972e92012-03-14 10:38:05 -07002417 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002418 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn21c241e2012-03-08 13:57:23 -08002419 Slog.i(TAG, "START {" + intent.toShortString(true, true, true, false)
Amith Yamasania4a54e22012-04-16 15:44:19 -07002420 + " u=" + userId + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002421 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002422
2423 ActivityRecord sourceRecord = null;
2424 ActivityRecord resultRecord = null;
2425 if (resultTo != null) {
2426 int index = indexOfTokenLocked(resultTo);
2427 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002428 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002430 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002431 if (requestCode >= 0 && !sourceRecord.finishing) {
2432 resultRecord = sourceRecord;
2433 }
2434 }
2435 }
2436
2437 int launchFlags = intent.getFlags();
2438
2439 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2440 && sourceRecord != null) {
2441 // Transfer the result target from the source activity to the new
2442 // one being started, including any failures.
2443 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002444 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002445 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002446 }
2447 resultRecord = sourceRecord.resultTo;
2448 resultWho = sourceRecord.resultWho;
2449 requestCode = sourceRecord.requestCode;
2450 sourceRecord.resultTo = null;
2451 if (resultRecord != null) {
2452 resultRecord.removeResultsLocked(
2453 sourceRecord, resultWho, requestCode);
2454 }
2455 }
2456
Dianne Hackborna4972e92012-03-14 10:38:05 -07002457 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002458 // We couldn't find a class that can handle the given Intent.
2459 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002460 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002461 }
2462
Dianne Hackborna4972e92012-03-14 10:38:05 -07002463 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002464 // We couldn't find the specific class specified in the Intent.
2465 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002466 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002467 }
2468
Dianne Hackborna4972e92012-03-14 10:38:05 -07002469 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002470 if (resultRecord != null) {
2471 sendActivityResultLocked(-1,
2472 resultRecord, resultWho, requestCode,
2473 Activity.RESULT_CANCELED, null);
2474 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002475 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002476 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002477 return err;
2478 }
2479
Jeff Sharkey35be7562012-04-18 19:16:15 -07002480 final int startAnyPerm = mService.checkPermission(
2481 START_ANY_ACTIVITY, callingPid, callingUid);
2482 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002483 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002484 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002485 if (resultRecord != null) {
2486 sendActivityResultLocked(-1,
2487 resultRecord, resultWho, requestCode,
2488 Activity.RESULT_CANCELED, null);
2489 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002490 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002491 String msg;
2492 if (!aInfo.exported) {
2493 msg = "Permission Denial: starting " + intent.toString()
2494 + " from " + callerApp + " (pid=" + callingPid
2495 + ", uid=" + callingUid + ")"
2496 + " not exported from uid " + aInfo.applicationInfo.uid;
2497 } else {
2498 msg = "Permission Denial: starting " + intent.toString()
2499 + " from " + callerApp + " (pid=" + callingPid
2500 + ", uid=" + callingUid + ")"
2501 + " requires " + aInfo.permission;
2502 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002503 Slog.w(TAG, msg);
2504 throw new SecurityException(msg);
2505 }
2506
2507 if (mMainStack) {
2508 if (mService.mController != null) {
2509 boolean abort = false;
2510 try {
2511 // The Intent we give to the watcher has the extra data
2512 // stripped off, since it can contain private information.
2513 Intent watchIntent = intent.cloneFilter();
2514 abort = !mService.mController.activityStarting(watchIntent,
2515 aInfo.applicationInfo.packageName);
2516 } catch (RemoteException e) {
2517 mService.mController = null;
2518 }
2519
2520 if (abort) {
2521 if (resultRecord != null) {
2522 sendActivityResultLocked(-1,
2523 resultRecord, resultWho, requestCode,
2524 Activity.RESULT_CANCELED, null);
2525 }
2526 // We pretend to the caller that it was really started, but
2527 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002528 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002529 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002530 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002531 }
2532 }
2533 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002534
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002535 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2536 intent, resolvedType, aInfo, mService.mConfiguration,
2537 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002538 if (outActivity != null) {
2539 outActivity[0] = r;
2540 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002541
2542 if (mMainStack) {
2543 if (mResumedActivity == null
2544 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2545 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2546 PendingActivityLaunch pal = new PendingActivityLaunch();
2547 pal.r = r;
2548 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002549 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002550 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002551 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002552 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002553 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002554 }
2555 }
2556
2557 if (mService.mDidAppSwitch) {
2558 // This is the second allowed switch since we stopped switches,
2559 // so now just generally allow switches. Use case: user presses
2560 // home (switches disabled, switch to home, mDidAppSwitch now true);
2561 // user taps a home icon (coming from home so allowed, we hit here
2562 // and now allow anyone to switch again).
2563 mService.mAppSwitchesAllowedTime = 0;
2564 } else {
2565 mService.mDidAppSwitch = true;
2566 }
2567
2568 mService.doPendingActivityLaunchesLocked(false);
2569 }
2570
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002571 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002572 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002573 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002574 // Someone asked to have the keyguard dismissed on the next
2575 // activity start, but we are not actually doing an activity
2576 // switch... just dismiss the keyguard now, because we
2577 // probably want to see whatever is behind it.
2578 mDismissKeyguardOnNextActivity = false;
2579 mService.mWindowManager.dismissKeyguard();
2580 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002581 Slog.i(TAG, "DONE STARTING!");
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002582 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002583 }
2584
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002585 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2586 if ((launchFlags &
2587 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2588 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2589 // Caller wants to appear on home activity, so before starting
2590 // their own activity we will bring home to the front.
2591 moveHomeToFrontLocked();
2592 }
2593 }
2594
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002595 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002596 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2597 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 final Intent intent = r.intent;
2599 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002600 final int userId = r.userId;
2601
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002602 int launchFlags = intent.getFlags();
2603
2604 // We'll invoke onUserLeaving before onPause only if the launching
2605 // activity did not explicitly state that this is an automated launch.
2606 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2607 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2608 "startActivity() => mUserLeaving=" + mUserLeaving);
2609
2610 // If the caller has asked not to resume at this point, we make note
2611 // of this in the record so that we can skip it when trying to find
2612 // the top running activity.
2613 if (!doResume) {
2614 r.delayedResume = true;
2615 }
2616
2617 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2618 != 0 ? r : null;
2619
2620 // If the onlyIfNeeded flag is set, then we can do this if the activity
2621 // being launched is the same as the one making the call... or, as
2622 // a special case, if we do not know the caller then we count the
2623 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002624 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002625 ActivityRecord checkedCaller = sourceRecord;
2626 if (checkedCaller == null) {
2627 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2628 }
2629 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2630 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002631 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002632 }
2633 }
2634
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 if (sourceRecord == null) {
2636 // This activity is not being started from another... in this
2637 // case we -always- start a new task.
2638 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2639 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2640 + intent);
2641 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2642 }
2643 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2644 // The original activity who is starting us is running as a single
2645 // instance... this new activity it is starting must go on its
2646 // own task.
2647 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2648 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2649 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2650 // The activity being started is a single instance... it always
2651 // gets launched into its own task.
2652 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2653 }
2654
2655 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2656 // For whatever reason this activity is being launched into a new
2657 // task... yet the caller has requested a result back. Well, that
2658 // is pretty messed up, so instead immediately send back a cancel
2659 // and let the new task continue launched as normal without a
2660 // dependency on its originator.
2661 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2662 sendActivityResultLocked(-1,
2663 r.resultTo, r.resultWho, r.requestCode,
2664 Activity.RESULT_CANCELED, null);
2665 r.resultTo = null;
2666 }
2667
2668 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002669 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002670 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002671 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2672 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2673 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2674 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2675 // If bring to front is requested, and no result is requested, and
2676 // we can find a task that was started with this same
2677 // component, then instead of launching bring that one to the front.
2678 if (r.resultTo == null) {
2679 // See if there is a task to bring to the front. If this is
2680 // a SINGLE_INSTANCE activity, there can be one and only one
2681 // instance of it in the history, and it is always in its own
2682 // unique task, so we do a special search.
2683 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2684 ? findTaskLocked(intent, r.info)
2685 : findActivityLocked(intent, r.info);
2686 if (taskTop != null) {
2687 if (taskTop.task.intent == null) {
2688 // This task was started because of movement of
2689 // the activity based on affinity... now that we
2690 // are actually launching it, we can assign the
2691 // base intent.
2692 taskTop.task.setIntent(intent, r.info);
2693 }
2694 // If the target task is not in the front, then we need
2695 // to bring it to the front... except... well, with
2696 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2697 // to have the same behavior as if a new instance was
2698 // being started, which means not bringing it to the front
2699 // if the caller is not itself in the front.
2700 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002701 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002702 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2703 boolean callerAtFront = sourceRecord == null
2704 || curTop.task == sourceRecord.task;
2705 if (callerAtFront) {
2706 // We really do want to push this one into the
2707 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002708 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002709 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002710 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002711 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002712 }
2713 }
2714 // If the caller has requested that the target task be
2715 // reset, then do so.
2716 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2717 taskTop = resetTaskIfNeededLocked(taskTop, r);
2718 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002719 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002720 // We don't need to start a new activity, and
2721 // the client said not to do anything if that
2722 // is the case, so this is it! And for paranoia, make
2723 // sure we have correctly resumed the top activity.
2724 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002725 resumeTopActivityLocked(null, options);
2726 } else {
2727 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002728 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002729 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002730 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002731 if ((launchFlags &
2732 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2733 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2734 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002735 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002736 // not be too hard...
2737 reuseTask = taskTop.task;
2738 performClearTaskLocked(taskTop.task.taskId);
2739 reuseTask.setIntent(r.intent, r.info);
2740 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002741 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2742 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2743 // In this situation we want to remove all activities
2744 // from the task up to the one being started. In most
2745 // cases this means we are resetting the task to its
2746 // initial state.
2747 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002748 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002749 if (top != null) {
2750 if (top.frontOfTask) {
2751 // Activity aliases may mean we use different
2752 // intents for the top activity, so make sure
2753 // the task now has the identity of the new
2754 // intent.
2755 top.task.setIntent(r.intent, r.info);
2756 }
2757 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002758 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002759 } else {
2760 // A special case: we need to
2761 // start the activity because it is not currently
2762 // running, and the caller has asked to clear the
2763 // current task to have this activity at the top.
2764 addingToTask = true;
2765 // Now pretend like this activity is being started
2766 // by the top of its task, so it is put in the
2767 // right place.
2768 sourceRecord = taskTop;
2769 }
2770 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2771 // In this case the top activity on the task is the
2772 // same as the one being launched, so we take that
2773 // as a request to bring the task to the foreground.
2774 // If the top activity in the task is the root
2775 // activity, deliver this new intent to it if it
2776 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002777 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2778 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002779 && taskTop.realActivity.equals(r.realActivity)) {
2780 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2781 if (taskTop.frontOfTask) {
2782 taskTop.task.setIntent(r.intent, r.info);
2783 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002784 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2786 // In this case we are launching the root activity
2787 // of the task, but with a different intent. We
2788 // should start a new instance on top.
2789 addingToTask = true;
2790 sourceRecord = taskTop;
2791 }
2792 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2793 // In this case an activity is being launched in to an
2794 // existing task, without resetting that task. This
2795 // is typically the situation of launching an activity
2796 // from a notification or shortcut. We want to place
2797 // the new activity on top of the current task.
2798 addingToTask = true;
2799 sourceRecord = taskTop;
2800 } else if (!taskTop.task.rootWasReset) {
2801 // In this case we are launching in to an existing task
2802 // that has not yet been started from its front door.
2803 // The current task has been brought to the front.
2804 // Ideally, we'd probably like to place this new task
2805 // at the bottom of its stack, but that's a little hard
2806 // to do with the current organization of the code so
2807 // for now we'll just drop it.
2808 taskTop.task.setIntent(r.intent, r.info);
2809 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002810 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 // We didn't do anything... but it was needed (a.k.a., client
2812 // don't use that intent!) And for paranoia, make
2813 // sure we have correctly resumed the top activity.
2814 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002815 resumeTopActivityLocked(null, options);
2816 } else {
2817 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002818 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002819 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002820 }
2821 }
2822 }
2823 }
2824
2825 //String uri = r.intent.toURI();
2826 //Intent intent2 = new Intent(uri);
2827 //Slog.i(TAG, "Given intent: " + r.intent);
2828 //Slog.i(TAG, "URI is: " + uri);
2829 //Slog.i(TAG, "To intent: " + intent2);
2830
2831 if (r.packageName != null) {
2832 // If the activity being launched is the same as the one currently
2833 // at the top, then we need to check if it should only be launched
2834 // once.
2835 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2836 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002837 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002838 if (top.app != null && top.app.thread != null) {
2839 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2840 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2841 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2842 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2843 // For paranoia, make sure we have correctly
2844 // resumed the top activity.
2845 if (doResume) {
2846 resumeTopActivityLocked(null);
2847 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002848 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002849 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 // We don't need to start a new activity, and
2851 // the client said not to do anything if that
2852 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002853 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002854 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002855 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002856 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 }
2858 }
2859 }
2860 }
2861
2862 } else {
2863 if (r.resultTo != null) {
2864 sendActivityResultLocked(-1,
2865 r.resultTo, r.resultWho, r.requestCode,
2866 Activity.RESULT_CANCELED, null);
2867 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002868 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002869 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002870 }
2871
2872 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002873 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002874
2875 // Should this be considered a new task?
2876 if (r.resultTo == null && !addingToTask
2877 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002878 if (reuseTask == null) {
2879 // todo: should do better management of integers.
2880 mService.mCurTask++;
2881 if (mService.mCurTask <= 0) {
2882 mService.mCurTask = 1;
2883 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002884 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002885 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2886 + " in new task " + r.task);
2887 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002888 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002890 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002891 if (!movedHome) {
2892 moveHomeToFrontFromLaunchLocked(launchFlags);
2893 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002894
2895 } else if (sourceRecord != null) {
2896 if (!addingToTask &&
2897 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2898 // In this case, we are adding the activity to an existing
2899 // task, but the caller has asked to clear that task if the
2900 // activity is already running.
2901 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002902 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002903 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002904 if (top != null) {
2905 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002906 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002907 // For paranoia, make sure we have correctly
2908 // resumed the top activity.
2909 if (doResume) {
2910 resumeTopActivityLocked(null);
2911 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002912 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002913 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002914 }
2915 } else if (!addingToTask &&
2916 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2917 // In this case, we are launching an activity in our own task
2918 // that may already be running somewhere in the history, and
2919 // we want to shuffle it to the front of the stack if so.
2920 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2921 if (where >= 0) {
2922 ActivityRecord top = moveActivityToFrontLocked(where);
2923 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002924 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002925 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 if (doResume) {
2927 resumeTopActivityLocked(null);
2928 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002929 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002930 }
2931 }
2932 // An existing activity is starting this new activity, so we want
2933 // to keep the new one in the same task as the one that is starting
2934 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002935 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002936 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2937 + " in existing task " + r.task);
2938
2939 } else {
2940 // This not being started from an existing activity, and not part
2941 // of a new task... just put it in the top task, though these days
2942 // this case should never happen.
2943 final int N = mHistory.size();
2944 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002945 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002946 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002947 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002948 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002949 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2950 + " in new guessed " + r.task);
2951 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002952
Dianne Hackborn39792d22010-08-19 18:01:52 -07002953 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002954 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002955
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002956 if (newTask) {
2957 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.task.taskId);
2958 }
2959 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002960 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002961 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002962 }
2963
Dianne Hackborna4972e92012-03-14 10:38:05 -07002964 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002965 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002966 // Collect information about the target of the Intent.
2967 ActivityInfo aInfo;
2968 try {
2969 ResolveInfo rInfo =
2970 AppGlobals.getPackageManager().resolveIntent(
2971 intent, resolvedType,
2972 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002973 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002974 aInfo = rInfo != null ? rInfo.activityInfo : null;
2975 } catch (RemoteException e) {
2976 aInfo = null;
2977 }
2978
2979 if (aInfo != null) {
2980 // Store the found target back into the intent, because now that
2981 // we have it we never want to do this again. For example, if the
2982 // user navigates back to this point in the history, we should
2983 // always restart the exact same activity.
2984 intent.setComponent(new ComponentName(
2985 aInfo.applicationInfo.packageName, aInfo.name));
2986
2987 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07002988 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002989 if (!aInfo.processName.equals("system")) {
2990 mService.setDebugApp(aInfo.processName, true, false);
2991 }
2992 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07002993
Dianne Hackborna4972e92012-03-14 10:38:05 -07002994 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08002995 if (!aInfo.processName.equals("system")) {
2996 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
2997 }
2998 }
2999
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003000 if (profileFile != null) {
3001 if (!aInfo.processName.equals("system")) {
3002 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003003 profileFile, profileFd,
3004 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003005 }
3006 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003007 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003008 return aInfo;
3009 }
3010
3011 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003012 Intent intent, String resolvedType, IBinder resultTo,
3013 String resultWho, int requestCode, int startFlags, String profileFile,
3014 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3015 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003016 // Refuse possible leaked file descriptors
3017 if (intent != null && intent.hasFileDescriptors()) {
3018 throw new IllegalArgumentException("File descriptors passed in Intent");
3019 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003020 boolean componentSpecified = intent.getComponent() != null;
3021
3022 // Don't modify the client's object!
3023 intent = new Intent(intent);
3024
3025 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003026 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003027 profileFile, profileFd, userId);
Amith Yamasania10d1aa2012-08-21 09:49:53 -07003028 if (aInfo != null && (aInfo.flags & ActivityInfo.FLAG_MULTIPROCESS) == 0
3029 && mService.isSingleton(aInfo.processName, aInfo.applicationInfo, null, 0)) {
Amith Yamasania4a54e22012-04-16 15:44:19 -07003030 userId = 0;
3031 }
Amith Yamasani742a6712011-05-04 14:49:28 -07003032 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003033
3034 synchronized (mService) {
3035 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003036 if (callingUid >= 0) {
3037 callingPid = -1;
3038 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003039 callingPid = Binder.getCallingPid();
3040 callingUid = Binder.getCallingUid();
3041 } else {
3042 callingPid = callingUid = -1;
3043 }
3044
3045 mConfigWillChange = config != null
3046 && mService.mConfiguration.diff(config) != 0;
3047 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3048 "Starting activity when config will change = " + mConfigWillChange);
3049
3050 final long origId = Binder.clearCallingIdentity();
3051
3052 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003053 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003054 // This may be a heavy-weight process! Check to see if we already
3055 // have another, different heavy-weight process running.
3056 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3057 if (mService.mHeavyWeightProcess != null &&
3058 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3059 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3060 int realCallingPid = callingPid;
3061 int realCallingUid = callingUid;
3062 if (caller != null) {
3063 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3064 if (callerApp != null) {
3065 realCallingPid = callerApp.pid;
3066 realCallingUid = callerApp.info.uid;
3067 } else {
3068 Slog.w(TAG, "Unable to find app for caller " + caller
3069 + " (pid=" + realCallingPid + ") when starting: "
3070 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003071 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003072 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003073 }
3074 }
3075
3076 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003077 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003078 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003079 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003080 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003081
3082 Intent newIntent = new Intent();
3083 if (requestCode >= 0) {
3084 // Caller is requesting a result.
3085 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3086 }
3087 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3088 new IntentSender(target));
3089 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3090 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3091 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3092 hist.packageName);
3093 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3094 hist.task.taskId);
3095 }
3096 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3097 aInfo.packageName);
3098 newIntent.setFlags(intent.getFlags());
3099 newIntent.setClassName("android",
3100 HeavyWeightSwitcherActivity.class.getName());
3101 intent = newIntent;
3102 resolvedType = null;
3103 caller = null;
3104 callingUid = Binder.getCallingUid();
3105 callingPid = Binder.getCallingPid();
3106 componentSpecified = true;
3107 try {
3108 ResolveInfo rInfo =
3109 AppGlobals.getPackageManager().resolveIntent(
3110 intent, null,
3111 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003112 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003113 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003114 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003115 } catch (RemoteException e) {
3116 aInfo = null;
3117 }
3118 }
3119 }
3120 }
3121
3122 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003123 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3124 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003125
3126 if (mConfigWillChange && mMainStack) {
3127 // If the caller also wants to switch to a new configuration,
3128 // do so now. This allows a clean switch, as we are waiting
3129 // for the current activity to pause (so we will not destroy
3130 // it), and have not yet started the next activity.
3131 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3132 "updateConfiguration()");
3133 mConfigWillChange = false;
3134 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3135 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003136 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003137 }
3138
3139 Binder.restoreCallingIdentity(origId);
3140
3141 if (outResult != null) {
3142 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003143 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003144 mWaitingActivityLaunched.add(outResult);
3145 do {
3146 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003147 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003148 } catch (InterruptedException e) {
3149 }
3150 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003151 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003152 ActivityRecord r = this.topRunningActivityLocked(null);
3153 if (r.nowVisible) {
3154 outResult.timeout = false;
3155 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3156 outResult.totalTime = 0;
3157 outResult.thisTime = 0;
3158 } else {
3159 outResult.thisTime = SystemClock.uptimeMillis();
3160 mWaitingActivityVisible.add(outResult);
3161 do {
3162 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003163 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003164 } catch (InterruptedException e) {
3165 }
3166 } while (!outResult.timeout && outResult.who == null);
3167 }
3168 }
3169 }
3170
3171 return res;
3172 }
3173 }
3174
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003175 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003176 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3177 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003178 if (intents == null) {
3179 throw new NullPointerException("intents is null");
3180 }
3181 if (resolvedTypes == null) {
3182 throw new NullPointerException("resolvedTypes is null");
3183 }
3184 if (intents.length != resolvedTypes.length) {
3185 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3186 }
3187
3188 ActivityRecord[] outActivity = new ActivityRecord[1];
3189
3190 int callingPid;
3191 if (callingUid >= 0) {
3192 callingPid = -1;
3193 } else if (caller == null) {
3194 callingPid = Binder.getCallingPid();
3195 callingUid = Binder.getCallingUid();
3196 } else {
3197 callingPid = callingUid = -1;
3198 }
3199 final long origId = Binder.clearCallingIdentity();
3200 try {
3201 synchronized (mService) {
3202
3203 for (int i=0; i<intents.length; i++) {
3204 Intent intent = intents[i];
3205 if (intent == null) {
3206 continue;
3207 }
3208
3209 // Refuse possible leaked file descriptors
3210 if (intent != null && intent.hasFileDescriptors()) {
3211 throw new IllegalArgumentException("File descriptors passed in Intent");
3212 }
3213
3214 boolean componentSpecified = intent.getComponent() != null;
3215
3216 // Don't modify the client's object!
3217 intent = new Intent(intent);
3218
3219 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003220 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003221 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003222 // TODO: New, check if this is correct
3223 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003224
3225 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3226 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3227 throw new IllegalArgumentException(
3228 "FLAG_CANT_SAVE_STATE not supported here");
3229 }
3230
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003231 Bundle theseOptions;
3232 if (options != null && i == intents.length-1) {
3233 theseOptions = options;
3234 } else {
3235 theseOptions = null;
3236 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003237 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003238 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003239 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003240 if (res < 0) {
3241 return res;
3242 }
3243
Dianne Hackbornbe707852011-11-11 14:32:10 -08003244 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003245 }
3246 }
3247 } finally {
3248 Binder.restoreCallingIdentity(origId);
3249 }
3250
Dianne Hackborna4972e92012-03-14 10:38:05 -07003251 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003252 }
3253
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003254 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3255 long thisTime, long totalTime) {
3256 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3257 WaitResult w = mWaitingActivityLaunched.get(i);
3258 w.timeout = timeout;
3259 if (r != null) {
3260 w.who = new ComponentName(r.info.packageName, r.info.name);
3261 }
3262 w.thisTime = thisTime;
3263 w.totalTime = totalTime;
3264 }
3265 mService.notifyAll();
3266 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003267
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003268 void reportActivityVisibleLocked(ActivityRecord r) {
3269 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3270 WaitResult w = mWaitingActivityVisible.get(i);
3271 w.timeout = false;
3272 if (r != null) {
3273 w.who = new ComponentName(r.info.packageName, r.info.name);
3274 }
3275 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3276 w.thisTime = w.totalTime;
3277 }
3278 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003279
3280 if (mDismissKeyguardOnNextActivity) {
3281 mDismissKeyguardOnNextActivity = false;
3282 mService.mWindowManager.dismissKeyguard();
3283 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003284 }
3285
3286 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3287 String resultWho, int requestCode, int resultCode, Intent data) {
3288
3289 if (callingUid > 0) {
3290 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003291 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003292 }
3293
3294 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3295 + " : who=" + resultWho + " req=" + requestCode
3296 + " res=" + resultCode + " data=" + data);
3297 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3298 try {
3299 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3300 list.add(new ResultInfo(resultWho, requestCode,
3301 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003302 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003303 return;
3304 } catch (Exception e) {
3305 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3306 }
3307 }
3308
3309 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3310 }
3311
3312 private final void stopActivityLocked(ActivityRecord r) {
3313 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3314 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3315 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3316 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003317 if (!mService.mSleeping) {
3318 if (DEBUG_STATES) {
3319 Slog.d(TAG, "no-history finish of " + r);
3320 }
3321 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003322 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003323 } else {
3324 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3325 + " on stop because we're just sleeping");
3326 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003327 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003328 }
3329
3330 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003331 if (mMainStack) {
3332 if (mService.mFocusedActivity == r) {
3333 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3334 }
3335 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003336 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003337 try {
3338 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003339 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3340 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003341 r.state = ActivityState.STOPPING;
3342 if (DEBUG_VISBILITY) Slog.v(
3343 TAG, "Stopping visible=" + r.visible + " for " + r);
3344 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003345 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003346 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003347 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003348 if (mService.isSleeping()) {
3349 r.setSleeping(true);
3350 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003351 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3352 msg.obj = r;
3353 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003354 } catch (Exception e) {
3355 // Maybe just ignore exceptions here... if the process
3356 // has crashed, our death notification will clean things
3357 // up.
3358 Slog.w(TAG, "Exception thrown during pause", e);
3359 // Just in case, assume it to be stopped.
3360 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003361 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003362 r.state = ActivityState.STOPPED;
3363 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003364 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003365 }
3366 }
3367 }
3368 }
3369
3370 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3371 boolean remove) {
3372 int N = mStoppingActivities.size();
3373 if (N <= 0) return null;
3374
3375 ArrayList<ActivityRecord> stops = null;
3376
3377 final boolean nowVisible = mResumedActivity != null
3378 && mResumedActivity.nowVisible
3379 && !mResumedActivity.waitingVisible;
3380 for (int i=0; i<N; i++) {
3381 ActivityRecord s = mStoppingActivities.get(i);
3382 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3383 + nowVisible + " waitingVisible=" + s.waitingVisible
3384 + " finishing=" + s.finishing);
3385 if (s.waitingVisible && nowVisible) {
3386 mWaitingVisibleActivities.remove(s);
3387 s.waitingVisible = false;
3388 if (s.finishing) {
3389 // If this activity is finishing, it is sitting on top of
3390 // everyone else but we now know it is no longer needed...
3391 // so get rid of it. Otherwise, we need to go through the
3392 // normal flow and hide it once we determine that it is
3393 // hidden by the activities in front of it.
3394 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003395 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003396 }
3397 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003398 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003399 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3400 if (stops == null) {
3401 stops = new ArrayList<ActivityRecord>();
3402 }
3403 stops.add(s);
3404 mStoppingActivities.remove(i);
3405 N--;
3406 i--;
3407 }
3408 }
3409
3410 return stops;
3411 }
3412
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003413 final void scheduleIdleLocked() {
3414 Message msg = Message.obtain();
3415 msg.what = IDLE_NOW_MSG;
3416 mHandler.sendMessage(msg);
3417 }
3418
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003419 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003420 Configuration config) {
3421 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3422
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003423 ActivityRecord res = null;
3424
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003425 ArrayList<ActivityRecord> stops = null;
3426 ArrayList<ActivityRecord> finishes = null;
3427 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003428 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003429 int NS = 0;
3430 int NF = 0;
3431 int NT = 0;
3432 IApplicationThread sendThumbnail = null;
3433 boolean booting = false;
3434 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003435 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003436
3437 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003438 ActivityRecord r = ActivityRecord.forToken(token);
3439 if (r != null) {
3440 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003441 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003442 }
3443
3444 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003445 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003446 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003447 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003448
3449 if (fromTimeout) {
3450 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3451 }
3452
3453 // This is a hack to semi-deal with a race condition
3454 // in the client where it can be constructed with a
3455 // newer configuration from when we asked it to launch.
3456 // We'll update with whatever configuration it now says
3457 // it used to launch.
3458 if (config != null) {
3459 r.configuration = config;
3460 }
3461
3462 // No longer need to keep the device awake.
3463 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3464 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3465 mLaunchingActivity.release();
3466 }
3467
3468 // We are now idle. If someone is waiting for a thumbnail from
3469 // us, we can now deliver.
3470 r.idle = true;
3471 mService.scheduleAppGcsLocked();
3472 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3473 sendThumbnail = r.app.thread;
3474 r.thumbnailNeeded = false;
3475 }
3476
3477 // If this activity is fullscreen, set up to hide those under it.
3478
3479 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3480 ensureActivitiesVisibleLocked(null, 0);
3481
3482 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3483 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003484 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003485 mService.mBooted = true;
3486 enableScreen = true;
3487 }
3488 }
3489
3490 } else if (fromTimeout) {
3491 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3492 }
3493
3494 // Atomically retrieve all of the other things to do.
3495 stops = processStoppingActivitiesLocked(true);
3496 NS = stops != null ? stops.size() : 0;
3497 if ((NF=mFinishingActivities.size()) > 0) {
3498 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3499 mFinishingActivities.clear();
3500 }
3501 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3502 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3503 mService.mCancelledThumbnails.clear();
3504 }
3505
3506 if (mMainStack) {
3507 booting = mService.mBooting;
3508 mService.mBooting = false;
3509 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003510 if (mStartingUsers.size() > 0) {
3511 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3512 mStartingUsers.clear();
3513 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003514 }
3515
3516 int i;
3517
3518 // Send thumbnail if requested.
3519 if (sendThumbnail != null) {
3520 try {
3521 sendThumbnail.requestThumbnail(token);
3522 } catch (Exception e) {
3523 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3524 mService.sendPendingThumbnail(null, token, null, null, true);
3525 }
3526 }
3527
3528 // Stop any activities that are scheduled to do so but have been
3529 // waiting for the next one to start.
3530 for (i=0; i<NS; i++) {
3531 ActivityRecord r = (ActivityRecord)stops.get(i);
3532 synchronized (mService) {
3533 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003534 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003535 } else {
3536 stopActivityLocked(r);
3537 }
3538 }
3539 }
3540
3541 // Finish any activities that are scheduled to do so but have been
3542 // waiting for the next one to start.
3543 for (i=0; i<NF; i++) {
3544 ActivityRecord r = (ActivityRecord)finishes.get(i);
3545 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003546 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003547 }
3548 }
3549
3550 // Report back to any thumbnail receivers.
3551 for (i=0; i<NT; i++) {
3552 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3553 mService.sendPendingThumbnail(r, null, null, null, true);
3554 }
3555
3556 if (booting) {
3557 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003558 } else if (startingUsers != null) {
3559 for (i=0; i<startingUsers.size(); i++) {
3560 mService.finishUserSwitch(startingUsers.get(i));
3561 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003562 }
3563
3564 mService.trimApplications();
3565 //dump();
3566 //mWindowManager.dump();
3567
3568 if (enableScreen) {
3569 mService.enableScreenAfterBoot();
3570 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003571
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003572 if (activityRemoved) {
3573 resumeTopActivityLocked(null);
3574 }
3575
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003576 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003577 }
3578
3579 /**
3580 * @return Returns true if the activity is being finished, false if for
3581 * some reason it is being left as-is.
3582 */
3583 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003584 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003585 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003586 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003587 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003588 + ", result=" + resultCode + ", data=" + resultData
3589 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 if (index < 0) {
3591 return false;
3592 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003593 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003594
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003595 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003596 return true;
3597 }
3598
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003599 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3600 ActivityRecord self = isInStackLocked(token);
3601 if (self == null) {
3602 return;
3603 }
3604
3605 int i;
3606 for (i=mHistory.size()-1; i>=0; i--) {
3607 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3608 if (r.resultTo == self && r.requestCode == requestCode) {
3609 if ((r.resultWho == null && resultWho == null) ||
3610 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3611 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003612 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003613 }
3614 }
3615 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003616 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003617 }
3618
3619 final boolean finishActivityAffinityLocked(IBinder token) {
3620 int index = indexOfTokenLocked(token);
3621 if (DEBUG_RESULTS) Slog.v(
3622 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3623 if (index < 0) {
3624 return false;
3625 }
3626 ActivityRecord r = mHistory.get(index);
3627
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003628 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003629 ActivityRecord cur = mHistory.get(index);
3630 if (cur.task != r.task) {
3631 break;
3632 }
3633 if (cur.taskAffinity == null && r.taskAffinity != null) {
3634 break;
3635 }
3636 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3637 break;
3638 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003639 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3640 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003641 index--;
3642 }
3643 return true;
3644 }
3645
Dianne Hackborn5c607432012-02-28 14:44:19 -08003646 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3647 // send the result
3648 ActivityRecord resultTo = r.resultTo;
3649 if (resultTo != null) {
3650 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3651 + " who=" + r.resultWho + " req=" + r.requestCode
3652 + " res=" + resultCode + " data=" + resultData);
3653 if (r.info.applicationInfo.uid > 0) {
3654 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3655 resultTo.packageName, resultData,
3656 resultTo.getUriPermissionsLocked());
3657 }
3658 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3659 resultData);
3660 r.resultTo = null;
3661 }
3662 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3663
3664 // Make sure this HistoryRecord is not holding on to other resources,
3665 // because clients have remote IPC references to this object so we
3666 // can't assume that will go away and want to avoid circular IPC refs.
3667 r.results = null;
3668 r.pendingResults = null;
3669 r.newIntents = null;
3670 r.icicle = null;
3671 }
3672
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003673 /**
3674 * @return Returns true if this activity has been removed from the history
3675 * list, or false if it is still in the list and will be removed later.
3676 */
3677 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003678 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3679 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003680 }
3681
3682 /**
3683 * @return Returns true if this activity has been removed from the history
3684 * list, or false if it is still in the list and will be removed later.
3685 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003686 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3687 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003688 if (r.finishing) {
3689 Slog.w(TAG, "Duplicate finish request for " + r);
3690 return false;
3691 }
3692
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003693 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003694 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
3695 System.identityHashCode(r),
3696 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003697 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003698 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003699 if (next.task == r.task) {
3700 if (r.frontOfTask) {
3701 // The next activity is now the front of the task.
3702 next.frontOfTask = true;
3703 }
3704 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3705 // If the caller asked that this activity (and all above it)
3706 // be cleared when the task is reset, don't lose that information,
3707 // but propagate it up to the next activity.
3708 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3709 }
3710 }
3711 }
3712
3713 r.pauseKeyDispatchingLocked();
3714 if (mMainStack) {
3715 if (mService.mFocusedActivity == r) {
3716 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3717 }
3718 }
3719
Dianne Hackborn5c607432012-02-28 14:44:19 -08003720 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003721
3722 if (mService.mPendingThumbnails.size() > 0) {
3723 // There are clients waiting to receive thumbnails so, in case
3724 // this is an activity that someone is waiting for, add it
3725 // to the pending list so we can correctly update the clients.
3726 mService.mCancelledThumbnails.add(r);
3727 }
3728
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003729 if (immediate) {
3730 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003731 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003732 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003733 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003734 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003735 if (DEBUG_TRANSITION) Slog.v(TAG,
3736 "Prepare close transition: finishing " + r);
3737 mService.mWindowManager.prepareAppTransition(endTask
3738 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003739 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003740
3741 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003742 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003743
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003744 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003745 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3746 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3747 startPausingLocked(false, false);
3748 }
3749
3750 } else if (r.state != ActivityState.PAUSING) {
3751 // If the activity is PAUSING, we will complete the finish once
3752 // it is done pausing; else we can just directly finish it here.
3753 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3754 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003755 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 } else {
3757 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3758 }
3759
3760 return false;
3761 }
3762
3763 private static final int FINISH_IMMEDIATELY = 0;
3764 private static final int FINISH_AFTER_PAUSE = 1;
3765 private static final int FINISH_AFTER_VISIBLE = 2;
3766
3767 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003768 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003769 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770 if (index < 0) {
3771 return null;
3772 }
3773
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003774 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003775 }
3776
3777 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003778 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003779 // First things first: if this activity is currently visible,
3780 // and the resumed activity is not yet visible, then hold off on
3781 // finishing until the resumed one becomes visible.
3782 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3783 if (!mStoppingActivities.contains(r)) {
3784 mStoppingActivities.add(r);
3785 if (mStoppingActivities.size() > 3) {
3786 // If we already have a few activities waiting to stop,
3787 // then give up on things going idle and start clearing
3788 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003789 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003790 } else {
3791 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003792 }
3793 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003794 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3795 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003796 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003797 if (oomAdj) {
3798 mService.updateOomAdjLocked();
3799 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003800 return r;
3801 }
3802
3803 // make sure the record is cleaned out of other places.
3804 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003805 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003806 mWaitingVisibleActivities.remove(r);
3807 if (mResumedActivity == r) {
3808 mResumedActivity = null;
3809 }
3810 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003811 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003812 r.state = ActivityState.FINISHING;
3813
3814 if (mode == FINISH_IMMEDIATELY
3815 || prevState == ActivityState.STOPPED
3816 || prevState == ActivityState.INITIALIZING) {
3817 // If this activity is already stopped, we can just finish
3818 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003819 boolean activityRemoved = destroyActivityLocked(r, true,
3820 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003821 if (activityRemoved) {
3822 resumeTopActivityLocked(null);
3823 }
3824 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003825 } else {
3826 // Need to go through the full pause cycle to get this
3827 // activity into the stopped state and then finish it.
3828 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3829 mFinishingActivities.add(r);
3830 resumeTopActivityLocked(null);
3831 }
3832 return r;
3833 }
3834
3835 /**
3836 * Perform the common clean-up of an activity record. This is called both
3837 * as part of destroyActivityLocked() (when destroying the client-side
3838 * representation) and cleaning things up as a result of its hosting
3839 * processing going away, in which case there is no remaining client-side
3840 * state to destroy so only the cleanup here is needed.
3841 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003842 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3843 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003844 if (mResumedActivity == r) {
3845 mResumedActivity = null;
3846 }
3847 if (mService.mFocusedActivity == r) {
3848 mService.mFocusedActivity = null;
3849 }
3850
3851 r.configDestroy = false;
3852 r.frozenBeforeDestroy = false;
3853
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003854 if (setState) {
3855 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3856 r.state = ActivityState.DESTROYED;
3857 }
3858
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003859 // Make sure this record is no longer in the pending finishes list.
3860 // This could happen, for example, if we are trimming activities
3861 // down to the max limit while they are still waiting to finish.
3862 mFinishingActivities.remove(r);
3863 mWaitingVisibleActivities.remove(r);
3864
3865 // Remove any pending results.
3866 if (r.finishing && r.pendingResults != null) {
3867 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3868 PendingIntentRecord rec = apr.get();
3869 if (rec != null) {
3870 mService.cancelIntentSenderLocked(rec, false);
3871 }
3872 }
3873 r.pendingResults = null;
3874 }
3875
3876 if (cleanServices) {
3877 cleanUpActivityServicesLocked(r);
3878 }
3879
3880 if (mService.mPendingThumbnails.size() > 0) {
3881 // There are clients waiting to receive thumbnails so, in case
3882 // this is an activity that someone is waiting for, add it
3883 // to the pending list so we can correctly update the clients.
3884 mService.mCancelledThumbnails.add(r);
3885 }
3886
3887 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003888 removeTimeoutsForActivityLocked(r);
3889 }
3890
3891 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003892 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003893 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003894 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003895 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003896 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003897 }
3898
Dianne Hackborn5c607432012-02-28 14:44:19 -08003899 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003900 if (r.state != ActivityState.DESTROYED) {
Dianne Hackborn5c607432012-02-28 14:44:19 -08003901 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003902 r.makeFinishing();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003903 if (DEBUG_ADD_REMOVE) {
3904 RuntimeException here = new RuntimeException("here");
3905 here.fillInStackTrace();
3906 Slog.i(TAG, "Removing activity " + r + " from stack");
3907 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 mHistory.remove(r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003909 r.takeFromHistory();
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003910 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3911 + " (removed from history)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003912 r.state = ActivityState.DESTROYED;
Dianne Hackbornbe707852011-11-11 14:32:10 -08003913 mService.mWindowManager.removeAppToken(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003914 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003915 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003916 }
3917 cleanUpActivityServicesLocked(r);
3918 r.removeUriPermissionsLocked();
3919 }
3920 }
3921
3922 /**
3923 * Perform clean-up of service connections in an activity record.
3924 */
3925 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3926 // Throw away any services that have been bound by this activity.
3927 if (r.connections != null) {
3928 Iterator<ConnectionRecord> it = r.connections.iterator();
3929 while (it.hasNext()) {
3930 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003931 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003932 }
3933 r.connections = null;
3934 }
3935 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003936
3937 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
3938 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3939 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
3940 mHandler.sendMessage(msg);
3941 }
3942
Dianne Hackborn28695e02011-11-02 21:59:51 -07003943 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003944 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003945 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003946 for (int i=mHistory.size()-1; i>=0; i--) {
3947 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003948 if (r.finishing) {
3949 continue;
3950 }
3951 if (r.fullscreen) {
3952 lastIsOpaque = true;
3953 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003954 if (owner != null && r.app != owner) {
3955 continue;
3956 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003957 if (!lastIsOpaque) {
3958 continue;
3959 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003960 // We can destroy this one if we have its icicle saved and
3961 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003962 if (r.app != null && r != mResumedActivity && r != mPausingActivity
3963 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003964 && r.state != ActivityState.DESTROYING
3965 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003966 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3967 + " resumed=" + mResumedActivity
3968 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003969 if (destroyActivityLocked(r, true, oomAdj, reason)) {
3970 activityRemoved = true;
3971 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003972 }
3973 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003974 if (activityRemoved) {
3975 resumeTopActivityLocked(null);
3976 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003977 }
3978
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003979 /**
3980 * Destroy the current CLIENT SIDE instance of an activity. This may be
3981 * called both when actually finishing an activity, or when performing
3982 * a configuration switch where we destroy the current client-side object
3983 * but then create a new client-side object for this same HistoryRecord.
3984 */
3985 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07003986 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003987 if (DEBUG_SWITCH) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003988 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003989 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
3990 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
3991 System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07003992 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003993
3994 boolean removedFromHistory = false;
3995
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003996 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003997
3998 final boolean hadApp = r.app != null;
3999
4000 if (hadApp) {
4001 if (removeFromApp) {
4002 int idx = r.app.activities.indexOf(r);
4003 if (idx >= 0) {
4004 r.app.activities.remove(idx);
4005 }
4006 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4007 mService.mHeavyWeightProcess = null;
4008 mService.mHandler.sendEmptyMessage(
4009 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4010 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004011 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004012 // No longer have activities, so update oom adj.
4013 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004014 }
4015 }
4016
4017 boolean skipDestroy = false;
4018
4019 try {
4020 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004021 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004022 r.configChangeFlags);
4023 } catch (Exception e) {
4024 // We can just ignore exceptions here... if the process
4025 // has crashed, our death notification will clean things
4026 // up.
4027 //Slog.w(TAG, "Exception thrown during finish", e);
4028 if (r.finishing) {
4029 removeActivityFromHistoryLocked(r);
4030 removedFromHistory = true;
4031 skipDestroy = true;
4032 }
4033 }
4034
4035 r.app = null;
4036 r.nowVisible = false;
4037
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004038 // If the activity is finishing, we need to wait on removing it
4039 // from the list to give it a chance to do its cleanup. During
4040 // that time it may make calls back with its token so we need to
4041 // be able to find it on the list and so we don't want to remove
4042 // it from the list yet. Otherwise, we can just immediately put
4043 // it in the destroyed state since we are not removing it from the
4044 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004045 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004046 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4047 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004048 r.state = ActivityState.DESTROYING;
4049 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4050 msg.obj = r;
4051 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4052 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004053 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4054 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004055 r.state = ActivityState.DESTROYED;
4056 }
4057 } else {
4058 // remove this record from the history.
4059 if (r.finishing) {
4060 removeActivityFromHistoryLocked(r);
4061 removedFromHistory = true;
4062 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004063 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4064 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004065 r.state = ActivityState.DESTROYED;
4066 }
4067 }
4068
4069 r.configChangeFlags = 0;
4070
4071 if (!mLRUActivities.remove(r) && hadApp) {
4072 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4073 }
4074
4075 return removedFromHistory;
4076 }
4077
4078 final void activityDestroyed(IBinder token) {
4079 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004080 final long origId = Binder.clearCallingIdentity();
4081 try {
4082 ActivityRecord r = ActivityRecord.forToken(token);
4083 if (r != null) {
4084 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004085 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004086
4087 int index = indexOfActivityLocked(r);
4088 if (index >= 0) {
4089 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004090 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004091 removeActivityFromHistoryLocked(r);
4092 }
4093 }
4094 resumeTopActivityLocked(null);
4095 } finally {
4096 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004097 }
4098 }
4099 }
4100
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004101 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004102 int i = list.size();
4103 if (localLOGV) Slog.v(
4104 TAG, "Removing app " + app + " from list " + list
4105 + " with " + i + " entries");
4106 while (i > 0) {
4107 i--;
4108 ActivityRecord r = (ActivityRecord)list.get(i);
4109 if (localLOGV) Slog.v(
4110 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4111 if (r.app == app) {
4112 if (localLOGV) Slog.v(TAG, "Removing this entry!");
4113 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004114 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004115 }
4116 }
4117 }
4118
4119 void removeHistoryRecordsForAppLocked(ProcessRecord app) {
4120 removeHistoryRecordsForAppLocked(mLRUActivities, app);
4121 removeHistoryRecordsForAppLocked(mStoppingActivities, app);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004122 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004123 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app);
4124 removeHistoryRecordsForAppLocked(mFinishingActivities, app);
4125 }
4126
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004127 /**
4128 * Move the current home activity's task (if one exists) to the front
4129 * of the stack.
4130 */
4131 final void moveHomeToFrontLocked() {
4132 TaskRecord homeTask = null;
4133 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004134 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004135 if (hr.isHomeActivity) {
4136 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004137 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004138 }
4139 }
4140 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004141 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004142 }
4143 }
4144
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004145 final void updateTransitLocked(int transit, Bundle options) {
4146 if (options != null) {
4147 ActivityRecord r = topRunningActivityLocked(null);
4148 if (r != null && r.state != ActivityState.RESUMED) {
4149 r.updateOptionsLocked(options);
4150 } else {
4151 ActivityOptions.abort(options);
4152 }
4153 }
4154 mService.mWindowManager.prepareAppTransition(transit, false);
4155 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004156
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004157 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004158 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4159
4160 final int task = tr.taskId;
4161 int top = mHistory.size()-1;
4162
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004163 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004164 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004165 if (reason != null &&
4166 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4167 ActivityOptions.abort(options);
4168 } else {
4169 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4170 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004171 return;
4172 }
4173
Dianne Hackbornbe707852011-11-11 14:32:10 -08004174 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004175
4176 // Applying the affinities may have removed entries from the history,
4177 // so get the size again.
4178 top = mHistory.size()-1;
4179 int pos = top;
4180
4181 // Shift all activities with this task up to the top
4182 // of the stack, keeping them in the same internal order.
4183 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004184 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004185 if (localLOGV) Slog.v(
4186 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004187 if (r.task.taskId == task) {
4188 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004189 if (DEBUG_ADD_REMOVE) {
4190 RuntimeException here = new RuntimeException("here");
4191 here.fillInStackTrace();
4192 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4193 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004194 mHistory.remove(pos);
4195 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004196 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004197 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004198 }
4199 pos--;
4200 }
4201
4202 if (DEBUG_TRANSITION) Slog.v(TAG,
4203 "Prepare to front transition: task=" + tr);
4204 if (reason != null &&
4205 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004206 mService.mWindowManager.prepareAppTransition(
4207 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004208 ActivityRecord r = topRunningActivityLocked(null);
4209 if (r != null) {
4210 mNoAnimActivities.add(r);
4211 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004212 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004213 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004214 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004215 }
4216
4217 mService.mWindowManager.moveAppTokensToTop(moved);
4218 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004219 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004220 }
4221
4222 finishTaskMoveLocked(task);
4223 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, task);
4224 }
4225
4226 private final void finishTaskMoveLocked(int task) {
4227 resumeTopActivityLocked(null);
4228 }
4229
4230 /**
4231 * Worker method for rearranging history stack. Implements the function of moving all
4232 * activities for a specific task (gathering them if disjoint) into a single group at the
4233 * bottom of the stack.
4234 *
4235 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4236 * to premeptively cancel the move.
4237 *
4238 * @param task The taskId to collect and move to the bottom.
4239 * @return Returns true if the move completed, false if not.
4240 */
4241 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4242 Slog.i(TAG, "moveTaskToBack: " + task);
4243
4244 // If we have a watcher, preflight the move before committing to it. First check
4245 // for *other* available tasks, but if none are available, then try again allowing the
4246 // current task to be selected.
4247 if (mMainStack && mService.mController != null) {
4248 ActivityRecord next = topRunningActivityLocked(null, task);
4249 if (next == null) {
4250 next = topRunningActivityLocked(null, 0);
4251 }
4252 if (next != null) {
4253 // ask watcher if this is allowed
4254 boolean moveOK = true;
4255 try {
4256 moveOK = mService.mController.activityResuming(next.packageName);
4257 } catch (RemoteException e) {
4258 mService.mController = null;
4259 }
4260 if (!moveOK) {
4261 return false;
4262 }
4263 }
4264 }
4265
Dianne Hackbornbe707852011-11-11 14:32:10 -08004266 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004267
4268 if (DEBUG_TRANSITION) Slog.v(TAG,
4269 "Prepare to back transition: task=" + task);
4270
4271 final int N = mHistory.size();
4272 int bottom = 0;
4273 int pos = 0;
4274
4275 // Shift all activities with this task down to the bottom
4276 // of the stack, keeping them in the same internal order.
4277 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004278 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004279 if (localLOGV) Slog.v(
4280 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4281 if (r.task.taskId == task) {
4282 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004283 if (DEBUG_ADD_REMOVE) {
4284 RuntimeException here = new RuntimeException("here");
4285 here.fillInStackTrace();
4286 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4287 + bottom, here);
4288 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004289 mHistory.remove(pos);
4290 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004291 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004292 bottom++;
4293 }
4294 pos++;
4295 }
4296
4297 if (reason != null &&
4298 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004299 mService.mWindowManager.prepareAppTransition(
4300 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004301 ActivityRecord r = topRunningActivityLocked(null);
4302 if (r != null) {
4303 mNoAnimActivities.add(r);
4304 }
4305 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004306 mService.mWindowManager.prepareAppTransition(
4307 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004308 }
4309 mService.mWindowManager.moveAppTokensToBottom(moved);
4310 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004311 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004312 }
4313
4314 finishTaskMoveLocked(task);
4315 return true;
4316 }
4317
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004318 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4319 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4320 ActivityRecord resumed = mResumedActivity;
4321 if (resumed != null && resumed.thumbHolder == tr) {
4322 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
4323 } else {
4324 info.mainThumbnail = tr.lastThumbnail;
4325 }
4326 return info;
4327 }
4328
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004329 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4330 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004331 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4332 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004333 if (taskRequired) {
4334 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4335 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004336 return null;
4337 }
4338
4339 if (subTaskIndex < 0) {
4340 // Just remove the entire task.
4341 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4342 return info.root;
4343 }
4344
4345 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004346 if (taskRequired) {
4347 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4348 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004349 return null;
4350 }
4351
4352 // Remove all of this task's activies starting at the sub task.
4353 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4354 performClearTaskAtIndexLocked(taskId, subtask.index);
4355 return subtask.activity;
4356 }
4357
4358 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
4359 ActivityRecord resumed = mResumedActivity;
4360 final TaskAccessInfo thumbs = new TaskAccessInfo();
4361 // How many different sub-thumbnails?
4362 final int NA = mHistory.size();
4363 int j = 0;
4364 ThumbnailHolder holder = null;
4365 while (j < NA) {
4366 ActivityRecord ar = mHistory.get(j);
4367 if (!ar.finishing && ar.task.taskId == taskId) {
4368 holder = ar.thumbHolder;
4369 break;
4370 }
4371 j++;
4372 }
4373
4374 if (j >= NA) {
4375 return thumbs;
4376 }
4377
4378 thumbs.root = mHistory.get(j);
4379 thumbs.rootIndex = j;
4380
4381 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4382 thumbs.subtasks = subtasks;
4383 ActivityRecord lastActivity = null;
4384 while (j < NA) {
4385 ActivityRecord ar = mHistory.get(j);
4386 j++;
4387 if (ar.finishing) {
4388 continue;
4389 }
4390 if (ar.task.taskId != taskId) {
4391 break;
4392 }
4393 lastActivity = ar;
4394 if (ar.thumbHolder != holder && holder != null) {
4395 thumbs.numSubThumbbails++;
4396 holder = ar.thumbHolder;
4397 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
4398 sub.thumbnail = holder.lastThumbnail;
4399 sub.activity = ar;
4400 sub.index = j-1;
4401 subtasks.add(sub);
4402 }
4403 }
4404 if (lastActivity != null && subtasks.size() > 0) {
4405 if (resumed == lastActivity) {
4406 TaskAccessInfo.SubTask sub = subtasks.get(subtasks.size()-1);
4407 sub.thumbnail = lastActivity.stack.screenshotActivities(lastActivity);
4408 }
4409 }
4410 if (thumbs.numSubThumbbails > 0) {
4411 thumbs.retriever = new IThumbnailRetriever.Stub() {
4412 public Bitmap getThumbnail(int index) {
4413 if (index < 0 || index >= thumbs.subtasks.size()) {
4414 return null;
4415 }
4416 return thumbs.subtasks.get(index).thumbnail;
4417 }
4418 };
4419 }
4420 return thumbs;
4421 }
4422
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004423 private final void logStartActivity(int tag, ActivityRecord r,
4424 TaskRecord task) {
4425 EventLog.writeEvent(tag,
4426 System.identityHashCode(r), task.taskId,
4427 r.shortComponentName, r.intent.getAction(),
4428 r.intent.getType(), r.intent.getDataString(),
4429 r.intent.getFlags());
4430 }
4431
4432 /**
4433 * Make sure the given activity matches the current configuration. Returns
4434 * false if the activity had to be destroyed. Returns true if the
4435 * configuration is the same, or the activity will remain running as-is
4436 * for whatever reason. Ensures the HistoryRecord is updated with the
4437 * correct configuration and all other bookkeeping is handled.
4438 */
4439 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4440 int globalChanges) {
4441 if (mConfigWillChange) {
4442 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4443 "Skipping config check (will change): " + r);
4444 return true;
4445 }
4446
4447 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4448 "Ensuring correct configuration: " + r);
4449
4450 // Short circuit: if the two configurations are the exact same
4451 // object (the common case), then there is nothing to do.
4452 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004453 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004454 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4455 "Configuration unchanged in " + r);
4456 return true;
4457 }
4458
4459 // We don't worry about activities that are finishing.
4460 if (r.finishing) {
4461 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4462 "Configuration doesn't matter in finishing " + r);
4463 r.stopFreezingScreenLocked(false);
4464 return true;
4465 }
4466
4467 // Okay we now are going to make this activity have the new config.
4468 // But then we need to figure out how it needs to deal with that.
4469 Configuration oldConfig = r.configuration;
4470 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004471
4472 // Determine what has changed. May be nothing, if this is a config
4473 // that has come back from the app after going idle. In that case
4474 // we just want to leave the official config object now in the
4475 // activity and do nothing else.
4476 final int changes = oldConfig.diff(newConfig);
4477 if (changes == 0 && !r.forceNewConfig) {
4478 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4479 "Configuration no differences in " + r);
4480 return true;
4481 }
4482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004483 // If the activity isn't currently running, just leave the new
4484 // configuration and it will pick that up next time it starts.
4485 if (r.app == null || r.app.thread == null) {
4486 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4487 "Configuration doesn't matter not running " + r);
4488 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004489 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004490 return true;
4491 }
4492
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004493 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004494 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4495 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4496 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004497 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004498 + ", newConfig=" + newConfig);
4499 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004500 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004501 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4502 r.configChangeFlags |= changes;
4503 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004504 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004505 if (r.app == null || r.app.thread == null) {
4506 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004507 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004508 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004509 } else if (r.state == ActivityState.PAUSING) {
4510 // A little annoying: we are waiting for this activity to
4511 // finish pausing. Let's not do anything now, but just
4512 // flag that it needs to be restarted when done pausing.
4513 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004514 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004515 r.configDestroy = true;
4516 return true;
4517 } else if (r.state == ActivityState.RESUMED) {
4518 // Try to optimize this case: the configuration is changing
4519 // and we need to restart the top, resumed activity.
4520 // Instead of doing the normal handshaking, just say
4521 // "restart!".
4522 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004523 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004524 relaunchActivityLocked(r, r.configChangeFlags, true);
4525 r.configChangeFlags = 0;
4526 } else {
4527 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004528 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004529 relaunchActivityLocked(r, r.configChangeFlags, false);
4530 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004531 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004532
4533 // All done... tell the caller we weren't able to keep this
4534 // activity around.
4535 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004536 }
4537
4538 // Default case: the activity can handle this new configuration, so
4539 // hand it over. Note that we don't need to give it the new
4540 // configuration, since we always send configuration changes to all
4541 // process when they happen so it can just use whatever configuration
4542 // it last got.
4543 if (r.app != null && r.app.thread != null) {
4544 try {
4545 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004546 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004547 } catch (RemoteException e) {
4548 // If process died, whatever.
4549 }
4550 }
4551 r.stopFreezingScreenLocked(false);
4552
4553 return true;
4554 }
4555
4556 private final boolean relaunchActivityLocked(ActivityRecord r,
4557 int changes, boolean andResume) {
4558 List<ResultInfo> results = null;
4559 List<Intent> newIntents = null;
4560 if (andResume) {
4561 results = r.results;
4562 newIntents = r.newIntents;
4563 }
4564 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4565 + " with results=" + results + " newIntents=" + newIntents
4566 + " andResume=" + andResume);
4567 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
4568 : EventLogTags.AM_RELAUNCH_ACTIVITY, System.identityHashCode(r),
4569 r.task.taskId, r.shortComponentName);
4570
4571 r.startFreezingScreenLocked(r.app, 0);
4572
4573 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004574 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4575 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4576 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004577 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004578 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004579 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004580 // Note: don't need to call pauseIfSleepingLocked() here, because
4581 // the caller will only pass in 'andResume' if this activity is
4582 // currently resumed, which implies we aren't sleeping.
4583 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004584 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004585 }
4586
4587 if (andResume) {
4588 r.results = null;
4589 r.newIntents = null;
4590 if (mMainStack) {
4591 mService.reportResumedActivityLocked(r);
4592 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004593 r.state = ActivityState.RESUMED;
4594 } else {
4595 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4596 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004597 }
4598
4599 return true;
4600 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004601
4602 public void dismissKeyguardOnNextActivityLocked() {
4603 mDismissKeyguardOnNextActivity = true;
4604 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004605}