blob: 4bcb339b14796a6121a3467eaed028777c161e8c [file] [log] [blame]
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001/*
2 * Copyright (C) 2010 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.am;
18
Jeff Sharkey35be7562012-04-18 19:16:15 -070019import static android.Manifest.permission.START_ANY_ACTIVITY;
20import static android.content.pm.PackageManager.PERMISSION_GRANTED;
21
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070022import com.android.internal.app.HeavyWeightSwitcherActivity;
23import com.android.internal.os.BatteryStatsImpl;
24import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
25
26import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070027import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070028import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029import android.app.AppGlobals;
30import android.app.IActivityManager;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070031import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070032import android.app.IApplicationThread;
33import android.app.PendingIntent;
34import android.app.ResultInfo;
35import android.app.IActivityManager.WaitResult;
36import android.content.ComponentName;
37import android.content.Context;
38import android.content.IIntentSender;
39import android.content.Intent;
40import android.content.IntentSender;
41import android.content.pm.ActivityInfo;
42import android.content.pm.ApplicationInfo;
43import android.content.pm.PackageManager;
44import android.content.pm.ResolveInfo;
45import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080046import android.content.res.Resources;
47import android.graphics.Bitmap;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070048import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070049import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070050import android.os.Handler;
51import android.os.IBinder;
52import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070053import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070054import android.os.PowerManager;
55import android.os.RemoteException;
56import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070057import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070058import android.util.EventLog;
59import android.util.Log;
60import android.util.Slog;
Craig Mautner59c00972012-07-30 12:10:24 -070061import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070062import android.view.WindowManagerPolicy;
63
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070064import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070065import java.lang.ref.WeakReference;
66import java.util.ArrayList;
67import java.util.Iterator;
68import java.util.List;
69
70/**
71 * State and management of a single stack of activities.
72 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070073final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070074 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070075 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
77 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
78 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
79 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
80 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
81 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
82 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
83 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
Dianne Hackborncc5a0552012-10-01 16:32:39 -070084 static final boolean DEBUG_CLEANUP = ActivityManagerService.DEBUG_CLEANUP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070085
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 }
Craig Mautner5962b122012-10-05 14:45:52 -0700423
424 private boolean okToShow(ActivityRecord r) {
425 return r.userId == mCurrentUser
426 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
427 }
428
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700429 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
430 int i = mHistory.size()-1;
431 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700432 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700433 if (!r.finishing && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700434 return r;
435 }
436 i--;
437 }
438 return null;
439 }
440
441 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
442 int i = mHistory.size()-1;
443 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700444 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700445 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700446 return r;
447 }
448 i--;
449 }
450 return null;
451 }
452
453 /**
454 * This is a simplified version of topRunningActivityLocked that provides a number of
455 * optional skip-over modes. It is intended for use with the ActivityController hook only.
456 *
457 * @param token If non-null, any history records matching this token will be skipped.
458 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
459 *
460 * @return Returns the HistoryRecord of the next activity on the stack.
461 */
462 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
463 int i = mHistory.size()-1;
464 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700465 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700466 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700467 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
Craig Mautner5962b122012-10-05 14:45:52 -0700468 && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700469 return r;
470 }
471 i--;
472 }
473 return null;
474 }
475
476 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800477 return mHistory.indexOf(ActivityRecord.forToken(token));
478 }
479
480 final int indexOfActivityLocked(ActivityRecord r) {
481 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700482 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700483
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700484 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800485 ActivityRecord r = ActivityRecord.forToken(token);
486 if (mHistory.contains(r)) {
487 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700488 }
489 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700490 }
491
492 private final boolean updateLRUListLocked(ActivityRecord r) {
493 final boolean hadit = mLRUActivities.remove(r);
494 mLRUActivities.add(r);
495 return hadit;
496 }
497
498 /**
499 * Returns the top activity in any existing task matching the given
500 * Intent. Returns null if no such task is found.
501 */
502 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
503 ComponentName cls = intent.getComponent();
504 if (info.targetActivity != null) {
505 cls = new ComponentName(info.packageName, info.targetActivity);
506 }
507
508 TaskRecord cp = null;
509
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700510 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700511 final int N = mHistory.size();
512 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700513 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700514 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700515 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
516 cp = r.task;
517 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
518 // + "/aff=" + r.task.affinity + " to new cls="
519 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
520 if (r.task.affinity != null) {
521 if (r.task.affinity.equals(info.taskAffinity)) {
522 //Slog.i(TAG, "Found matching affinity!");
523 return r;
524 }
525 } else if (r.task.intent != null
526 && r.task.intent.getComponent().equals(cls)) {
527 //Slog.i(TAG, "Found matching class!");
528 //dump();
529 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
530 return r;
531 } else if (r.task.affinityIntent != null
532 && r.task.affinityIntent.getComponent().equals(cls)) {
533 //Slog.i(TAG, "Found matching class!");
534 //dump();
535 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
536 return r;
537 }
538 }
539 }
540
541 return null;
542 }
543
544 /**
545 * Returns the first activity (starting from the top of the stack) that
546 * is the same as the given activity. Returns null if no such activity
547 * is found.
548 */
549 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
550 ComponentName cls = intent.getComponent();
551 if (info.targetActivity != null) {
552 cls = new ComponentName(info.packageName, info.targetActivity);
553 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700554 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700555
556 final int N = mHistory.size();
557 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700558 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700559 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700560 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700561 //Slog.i(TAG, "Found matching class!");
562 //dump();
563 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
564 return r;
565 }
566 }
567 }
568
569 return null;
570 }
571
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700572 final void showAskCompatModeDialogLocked(ActivityRecord r) {
573 Message msg = Message.obtain();
574 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
575 msg.obj = r.task.askedCompatMode ? null : r;
576 mService.mHandler.sendMessage(msg);
577 }
578
Amith Yamasani742a6712011-05-04 14:49:28 -0700579 /*
580 * Move the activities around in the stack to bring a user to the foreground.
581 * @return whether there are any activities for the specified user.
582 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700583 final boolean switchUserLocked(int userId, UserStartedState uss) {
584 mCurrentUser = userId;
585 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700586
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700587 // Only one activity? Nothing to do...
588 if (mHistory.size() < 2)
589 return false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700590
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700591 boolean haveActivities = false;
592 // Check if the top activity is from the new user.
593 ActivityRecord top = mHistory.get(mHistory.size() - 1);
594 if (top.userId == userId) return true;
595 // Otherwise, move the user's activities to the top.
596 int N = mHistory.size();
597 int i = 0;
598 while (i < N) {
599 ActivityRecord r = mHistory.get(i);
600 if (r.userId == userId) {
601 ActivityRecord moveToTop = mHistory.remove(i);
602 mHistory.add(moveToTop);
603 // No need to check the top one now
604 N--;
605 haveActivities = true;
606 } else {
607 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700608 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700609 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700610 // Transition from the old top to the new top
611 resumeTopActivityLocked(top);
612 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700613 }
614
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700615 final boolean realStartActivityLocked(ActivityRecord r,
616 ProcessRecord app, boolean andResume, boolean checkConfig)
617 throws RemoteException {
618
619 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800620 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700621
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700622 // schedule launch ticks to collect information about slow apps.
623 r.startLaunchTickingLocked();
624
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700625 // Have the window manager re-evaluate the orientation of
626 // the screen based on the new activity order. Note that
627 // as a result of this, it can call back into the activity
628 // manager with a new orientation. We don't care about that,
629 // because the activity is not currently running so we are
630 // just restarting it anyway.
631 if (checkConfig) {
632 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
633 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800634 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800635 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700636 }
637
638 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700639 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700640
641 if (localLOGV) Slog.v(TAG, "Launching: " + r);
642
643 int idx = app.activities.indexOf(r);
644 if (idx < 0) {
645 app.activities.add(r);
646 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700647 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700648
649 try {
650 if (app.thread == null) {
651 throw new RemoteException();
652 }
653 List<ResultInfo> results = null;
654 List<Intent> newIntents = null;
655 if (andResume) {
656 results = r.results;
657 newIntents = r.newIntents;
658 }
659 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
660 + " icicle=" + r.icicle
661 + " with results=" + results + " newIntents=" + newIntents
662 + " andResume=" + andResume);
663 if (andResume) {
664 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700665 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700666 r.task.taskId, r.shortComponentName);
667 }
668 if (r.isHomeActivity) {
669 mService.mHomeProcess = app;
670 }
671 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800672 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400673 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700674 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700675 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700676 String profileFile = null;
677 ParcelFileDescriptor profileFd = null;
678 boolean profileAutoStop = false;
679 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
680 if (mService.mProfileProc == null || mService.mProfileProc == app) {
681 mService.mProfileProc = app;
682 profileFile = mService.mProfileFile;
683 profileFd = mService.mProfileFd;
684 profileAutoStop = mService.mAutoStopProfiler;
685 }
686 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700687 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700688 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700689 if (profileFd != null) {
690 try {
691 profileFd = profileFd.dup();
692 } catch (IOException e) {
693 profileFd = null;
694 }
695 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800696 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800697 System.identityHashCode(r), r.info,
698 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700699 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700700 mService.isNextTransitionForward(), profileFile, profileFd,
701 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700702
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700703 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700704 // This may be a heavy-weight process! Note that the package
705 // manager will ensure that only activity can run in the main
706 // process of the .apk, which is the only thing that will be
707 // considered heavy-weight.
708 if (app.processName.equals(app.info.packageName)) {
709 if (mService.mHeavyWeightProcess != null
710 && mService.mHeavyWeightProcess != app) {
711 Log.w(TAG, "Starting new heavy weight process " + app
712 + " when already running "
713 + mService.mHeavyWeightProcess);
714 }
715 mService.mHeavyWeightProcess = app;
716 Message msg = mService.mHandler.obtainMessage(
717 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
718 msg.obj = r;
719 mService.mHandler.sendMessage(msg);
720 }
721 }
722
723 } catch (RemoteException e) {
724 if (r.launchFailed) {
725 // This is the second time we failed -- finish activity
726 // and give up.
727 Slog.e(TAG, "Second failure launching "
728 + r.intent.getComponent().flattenToShortString()
729 + ", giving up", e);
730 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800731 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700732 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700733 return false;
734 }
735
736 // This is the first time we failed -- restart process and
737 // retry.
738 app.activities.remove(r);
739 throw e;
740 }
741
742 r.launchFailed = false;
743 if (updateLRUListLocked(r)) {
744 Slog.w(TAG, "Activity " + r
745 + " being launched, but already in LRU list");
746 }
747
748 if (andResume) {
749 // As part of the process of launching, ActivityThread also performs
750 // a resume.
751 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700752 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
753 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700754 r.stopped = false;
755 mResumedActivity = r;
756 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800757 if (mMainStack) {
758 mService.addRecentTaskLocked(r.task);
759 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700760 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800761 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700762 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700763 } else {
764 // This activity is not starting in the resumed state... which
765 // should look like we asked it to pause+stop (but remain visible),
766 // and it has done so and reported back the current icicle and
767 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700768 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
769 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700770 r.state = ActivityState.STOPPED;
771 r.stopped = true;
772 }
773
774 // Launch the new version setup screen if needed. We do this -after-
775 // launching the initial activity (that is, home), so that it can have
776 // a chance to initialize itself while in the background, making the
777 // switch back to it faster and look better.
778 if (mMainStack) {
779 mService.startSetupActivityLocked();
780 }
781
782 return true;
783 }
784
785 private final void startSpecificActivityLocked(ActivityRecord r,
786 boolean andResume, boolean checkConfig) {
787 // Is this activity's application already running?
788 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
789 r.info.applicationInfo.uid);
790
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700791 if (r.launchTime == 0) {
792 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700793 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700794 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700795 }
796 } else if (mInitialStartTime == 0) {
797 mInitialStartTime = SystemClock.uptimeMillis();
798 }
799
800 if (app != null && app.thread != null) {
801 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700802 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700803 realStartActivityLocked(r, app, andResume, checkConfig);
804 return;
805 } catch (RemoteException e) {
806 Slog.w(TAG, "Exception when starting activity "
807 + r.intent.getComponent().flattenToShortString(), e);
808 }
809
810 // If a dead object exception was thrown -- fall through to
811 // restart the application.
812 }
813
814 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800815 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700816 }
817
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800818 void stopIfSleepingLocked() {
819 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700820 if (!mGoingToSleep.isHeld()) {
821 mGoingToSleep.acquire();
822 if (mLaunchingActivity.isHeld()) {
823 mLaunchingActivity.release();
824 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
825 }
826 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800827 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
828 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
829 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
830 checkReadyForSleepLocked();
831 }
832 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700833
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800834 void awakeFromSleepingLocked() {
835 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
836 mSleepTimeout = false;
837 if (mGoingToSleep.isHeld()) {
838 mGoingToSleep.release();
839 }
840 // Ensure activities are no longer sleeping.
841 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700842 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800843 r.setSleeping(false);
844 }
845 mGoingToSleepActivities.clear();
846 }
847
848 void activitySleptLocked(ActivityRecord r) {
849 mGoingToSleepActivities.remove(r);
850 checkReadyForSleepLocked();
851 }
852
853 void checkReadyForSleepLocked() {
854 if (!mService.isSleeping()) {
855 // Do not care.
856 return;
857 }
858
859 if (!mSleepTimeout) {
860 if (mResumedActivity != null) {
861 // Still have something resumed; can't sleep until it is paused.
862 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700863 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
864 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800865 return;
866 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800867 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800868 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800869 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800870 return;
871 }
872
873 if (mStoppingActivities.size() > 0) {
874 // Still need to tell some activities to stop; can't sleep yet.
875 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
876 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700877 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800878 return;
879 }
880
881 ensureActivitiesVisibleLocked(null, 0);
882
883 // Make sure any stopped but visible activities are now sleeping.
884 // This ensures that the activity's onStop() is called.
885 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700886 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800887 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
888 r.setSleeping(true);
889 }
890 }
891
892 if (mGoingToSleepActivities.size() > 0) {
893 // Still need to tell some activities to sleep; can't sleep yet.
894 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
895 + mGoingToSleepActivities.size() + " activities");
896 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700897 }
898 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800899
900 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
901
902 if (mGoingToSleep.isHeld()) {
903 mGoingToSleep.release();
904 }
905 if (mService.mShuttingDown) {
906 mService.notifyAll();
907 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700908 }
Craig Mautner59c00972012-07-30 12:10:24 -0700909
Dianne Hackbornd2835932010-12-13 16:28:46 -0800910 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800911 if (who.noDisplay) {
912 return null;
913 }
914
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800915 Resources res = mService.mContext.getResources();
916 int w = mThumbnailWidth;
917 int h = mThumbnailHeight;
918 if (w < 0) {
919 mThumbnailWidth = w =
920 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
921 mThumbnailHeight = h =
922 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
923 }
924
925 if (w > 0) {
Craig Mautner59c00972012-07-30 12:10:24 -0700926 return mService.mWindowManager.screenshotApplications(who.appToken,
927 Display.DEFAULT_DISPLAY, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800928 }
929 return null;
930 }
931
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700932 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800933 if (mPausingActivity != null) {
934 RuntimeException e = new RuntimeException();
935 Slog.e(TAG, "Trying to pause when pause is already pending for "
936 + mPausingActivity, e);
937 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700938 ActivityRecord prev = mResumedActivity;
939 if (prev == null) {
940 RuntimeException e = new RuntimeException();
941 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
942 resumeTopActivityLocked(null);
943 return;
944 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700945 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
946 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700947 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800948 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700949 mLastPausedActivity = prev;
950 prev.state = ActivityState.PAUSING;
951 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700952 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700953
954 mService.updateCpuStats();
955
956 if (prev.app != null && prev.app.thread != null) {
957 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
958 try {
959 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700960 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700961 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800962 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
963 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700964 if (mMainStack) {
965 mService.updateUsageStats(prev, false);
966 }
967 } catch (Exception e) {
968 // Ignore exception, if process died other code will cleanup.
969 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800970 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700971 mLastPausedActivity = null;
972 }
973 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800974 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700975 mLastPausedActivity = null;
976 }
977
978 // If we are not going to sleep, we want to ensure the device is
979 // awake until the next activity is started.
980 if (!mService.mSleeping && !mService.mShuttingDown) {
981 mLaunchingActivity.acquire();
982 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
983 // To be safe, don't allow the wake lock to be held for too long.
984 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
985 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
986 }
987 }
988
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800989
990 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700991 // Have the window manager pause its key dispatching until the new
992 // activity has started. If we're pausing the activity just because
993 // the screen is being turned off and the UI is sleeping, don't interrupt
994 // key dispatch; the same activity will pick it up again on wakeup.
995 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800996 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700997 } else {
998 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
999 }
1000
1001 // Schedule a pause timeout in case the app doesn't respond.
1002 // We don't give it much time because this directly impacts the
1003 // responsiveness seen by the user.
1004 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1005 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001006 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001007 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1008 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1009 } else {
1010 // This activity failed to schedule the
1011 // pause, so just treat it as being paused now.
1012 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001013 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001014 }
1015 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001016
1017 final void activityResumed(IBinder token) {
1018 ActivityRecord r = null;
1019
1020 synchronized (mService) {
1021 int index = indexOfTokenLocked(token);
1022 if (index >= 0) {
1023 r = mHistory.get(index);
1024 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1025 r.icicle = null;
1026 r.haveState = false;
1027 }
1028 }
1029 }
1030
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001031 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001032 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001033 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001034
1035 ActivityRecord r = null;
1036
1037 synchronized (mService) {
1038 int index = indexOfTokenLocked(token);
1039 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001040 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001041 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001042 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001043 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1044 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001045 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001046 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001047 } else {
1048 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001049 r.userId, System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001050 mPausingActivity != null
1051 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001052 }
1053 }
1054 }
1055 }
1056
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001057 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1058 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001059 if (r.state != ActivityState.STOPPING) {
1060 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1061 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1062 return;
1063 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001064 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001065 if (icicle != null) {
1066 // If icicle is null, this is happening due to a timeout, so we
1067 // haven't really saved the state.
1068 r.icicle = icicle;
1069 r.haveState = true;
1070 r.updateThumbnail(thumbnail, description);
1071 }
1072 if (!r.stopped) {
1073 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1074 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1075 r.stopped = true;
1076 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001077 if (r.finishing) {
1078 r.clearOptionsLocked();
1079 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001080 if (r.configDestroy) {
1081 destroyActivityLocked(r, true, false, "stop-config");
1082 resumeTopActivityLocked(null);
1083 } else {
1084 // Now that this process has stopped, we may want to consider
1085 // it to be the previous app to try to keep around in case
1086 // the user wants to return to it.
1087 ProcessRecord fgApp = null;
1088 if (mResumedActivity != null) {
1089 fgApp = mResumedActivity.app;
1090 } else if (mPausingActivity != null) {
1091 fgApp = mPausingActivity.app;
1092 }
1093 if (r.app != null && fgApp != null && r.app != fgApp
1094 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1095 && r.app != mService.mHomeProcess) {
1096 mService.mPreviousProcess = r.app;
1097 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1098 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001099 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001100 }
1101 }
1102 }
1103
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001104 private final void completePauseLocked() {
1105 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001106 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1107
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001108 if (prev != null) {
1109 if (prev.finishing) {
1110 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001111 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001112 } else if (prev.app != null) {
1113 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1114 if (prev.waitingVisible) {
1115 prev.waitingVisible = false;
1116 mWaitingVisibleActivities.remove(prev);
1117 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1118 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001119 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001120 if (prev.configDestroy) {
1121 // The previous is being paused because the configuration
1122 // is changing, which means it is actually stopping...
1123 // To juggle the fact that we are also starting a new
1124 // instance right now, we need to first completely stop
1125 // the current instance before starting the new one.
1126 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1127 destroyActivityLocked(prev, true, false, "pause-config");
1128 } else {
1129 mStoppingActivities.add(prev);
1130 if (mStoppingActivities.size() > 3) {
1131 // If we already have a few activities waiting to stop,
1132 // then give up on things going idle and start clearing
1133 // them out.
1134 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1135 scheduleIdleLocked();
1136 } else {
1137 checkReadyForSleepLocked();
1138 }
1139 }
1140 } else {
1141 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1142 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001143 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001144 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001145 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001146
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001147 if (!mService.isSleeping()) {
1148 resumeTopActivityLocked(prev);
1149 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001150 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001151 ActivityRecord top = topRunningActivityLocked(null);
1152 if (top == null || (prev != null && top != prev)) {
1153 // If there are no more activities available to run,
1154 // do resume anyway to start something. Also if the top
1155 // activity on the stack is not the just paused activity,
1156 // we need to go ahead and resume it to ensure we complete
1157 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001158 resumeTopActivityLocked(null);
1159 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001160 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001161
1162 if (prev != null) {
1163 prev.resumeKeyDispatchingLocked();
1164 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001165
1166 if (prev.app != null && prev.cpuTimeAtResume > 0
1167 && mService.mBatteryStatsService.isOnBattery()) {
1168 long diff = 0;
1169 synchronized (mService.mProcessStatsThread) {
1170 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1171 - prev.cpuTimeAtResume;
1172 }
1173 if (diff > 0) {
1174 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1175 synchronized (bsi) {
1176 BatteryStatsImpl.Uid.Proc ps =
1177 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1178 prev.info.packageName);
1179 if (ps != null) {
1180 ps.addForegroundTimeLocked(diff);
1181 }
1182 }
1183 }
1184 }
1185 prev.cpuTimeAtResume = 0; // reset it
1186 }
1187
1188 /**
1189 * Once we know that we have asked an application to put an activity in
1190 * the resumed state (either by launching it or explicitly telling it),
1191 * this function updates the rest of our state to match that fact.
1192 */
1193 private final void completeResumeLocked(ActivityRecord next) {
1194 next.idle = false;
1195 next.results = null;
1196 next.newIntents = null;
1197
1198 // schedule an idle timeout in case the app doesn't do it for us.
1199 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1200 msg.obj = next;
1201 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1202
1203 if (false) {
1204 // The activity was never told to pause, so just keep
1205 // things going as-is. To maintain our own state,
1206 // we need to emulate it coming back and saying it is
1207 // idle.
1208 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1209 msg.obj = next;
1210 mHandler.sendMessage(msg);
1211 }
1212
1213 if (mMainStack) {
1214 mService.reportResumedActivityLocked(next);
1215 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001216
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001217 if (mMainStack) {
1218 mService.setFocusedActivityLocked(next);
1219 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001220 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001221 ensureActivitiesVisibleLocked(null, 0);
1222 mService.mWindowManager.executeAppTransition();
1223 mNoAnimActivities.clear();
1224
1225 // Mark the point when the activity is resuming
1226 // TODO: To be more accurate, the mark should be before the onCreate,
1227 // not after the onResume. But for subsequent starts, onResume is fine.
1228 if (next.app != null) {
1229 synchronized (mService.mProcessStatsThread) {
1230 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1231 }
1232 } else {
1233 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1234 }
1235 }
1236
1237 /**
1238 * Make sure that all activities that need to be visible (that is, they
1239 * currently can be seen by the user) actually are.
1240 */
1241 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1242 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1243 if (DEBUG_VISBILITY) Slog.v(
1244 TAG, "ensureActivitiesVisible behind " + top
1245 + " configChanges=0x" + Integer.toHexString(configChanges));
1246
1247 // If the top activity is not fullscreen, then we need to
1248 // make sure any activities under it are now visible.
1249 final int count = mHistory.size();
1250 int i = count-1;
1251 while (mHistory.get(i) != top) {
1252 i--;
1253 }
1254 ActivityRecord r;
1255 boolean behindFullscreen = false;
1256 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001257 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001258 if (DEBUG_VISBILITY) Slog.v(
1259 TAG, "Make visible? " + r + " finishing=" + r.finishing
1260 + " state=" + r.state);
1261 if (r.finishing) {
1262 continue;
1263 }
1264
1265 final boolean doThisProcess = onlyThisProcess == null
1266 || onlyThisProcess.equals(r.processName);
1267
1268 // First: if this is not the current activity being started, make
1269 // sure it matches the current configuration.
1270 if (r != starting && doThisProcess) {
1271 ensureActivityConfigurationLocked(r, 0);
1272 }
1273
1274 if (r.app == null || r.app.thread == null) {
1275 if (onlyThisProcess == null
1276 || onlyThisProcess.equals(r.processName)) {
1277 // This activity needs to be visible, but isn't even
1278 // running... get it started, but don't resume it
1279 // at this point.
1280 if (DEBUG_VISBILITY) Slog.v(
1281 TAG, "Start and freeze screen for " + r);
1282 if (r != starting) {
1283 r.startFreezingScreenLocked(r.app, configChanges);
1284 }
1285 if (!r.visible) {
1286 if (DEBUG_VISBILITY) Slog.v(
1287 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001288 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001289 }
1290 if (r != starting) {
1291 startSpecificActivityLocked(r, false, false);
1292 }
1293 }
1294
1295 } else if (r.visible) {
1296 // If this activity is already visible, then there is nothing
1297 // else to do here.
1298 if (DEBUG_VISBILITY) Slog.v(
1299 TAG, "Skipping: already visible at " + r);
1300 r.stopFreezingScreenLocked(false);
1301
1302 } else if (onlyThisProcess == null) {
1303 // This activity is not currently visible, but is running.
1304 // Tell it to become visible.
1305 r.visible = true;
1306 if (r.state != ActivityState.RESUMED && r != starting) {
1307 // If this activity is paused, tell it
1308 // to now show its window.
1309 if (DEBUG_VISBILITY) Slog.v(
1310 TAG, "Making visible and scheduling visibility: " + r);
1311 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001312 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001313 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001314 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001315 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001316 r.stopFreezingScreenLocked(false);
1317 } catch (Exception e) {
1318 // Just skip on any failure; we'll make it
1319 // visible when it next restarts.
1320 Slog.w(TAG, "Exception thrown making visibile: "
1321 + r.intent.getComponent(), e);
1322 }
1323 }
1324 }
1325
1326 // Aggregate current change flags.
1327 configChanges |= r.configChangeFlags;
1328
1329 if (r.fullscreen) {
1330 // At this point, nothing else needs to be shown
1331 if (DEBUG_VISBILITY) Slog.v(
1332 TAG, "Stopping: fullscreen at " + r);
1333 behindFullscreen = true;
1334 i--;
1335 break;
1336 }
1337 }
1338
1339 // Now for any activities that aren't visible to the user, make
1340 // sure they no longer are keeping the screen frozen.
1341 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001342 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001343 if (DEBUG_VISBILITY) Slog.v(
1344 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1345 + " state=" + r.state
1346 + " behindFullscreen=" + behindFullscreen);
1347 if (!r.finishing) {
1348 if (behindFullscreen) {
1349 if (r.visible) {
1350 if (DEBUG_VISBILITY) Slog.v(
1351 TAG, "Making invisible: " + r);
1352 r.visible = false;
1353 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001354 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001355 if ((r.state == ActivityState.STOPPING
1356 || r.state == ActivityState.STOPPED)
1357 && r.app != null && r.app.thread != null) {
1358 if (DEBUG_VISBILITY) Slog.v(
1359 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001360 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001361 }
1362 } catch (Exception e) {
1363 // Just skip on any failure; we'll make it
1364 // visible when it next restarts.
1365 Slog.w(TAG, "Exception thrown making hidden: "
1366 + r.intent.getComponent(), e);
1367 }
1368 } else {
1369 if (DEBUG_VISBILITY) Slog.v(
1370 TAG, "Already invisible: " + r);
1371 }
1372 } else if (r.fullscreen) {
1373 if (DEBUG_VISBILITY) Slog.v(
1374 TAG, "Now behindFullscreen: " + r);
1375 behindFullscreen = true;
1376 }
1377 }
1378 i--;
1379 }
1380 }
1381
1382 /**
1383 * Version of ensureActivitiesVisible that can easily be called anywhere.
1384 */
1385 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1386 int configChanges) {
1387 ActivityRecord r = topRunningActivityLocked(null);
1388 if (r != null) {
1389 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1390 }
1391 }
1392
1393 /**
1394 * Ensure that the top activity in the stack is resumed.
1395 *
1396 * @param prev The previously resumed activity, for when in the process
1397 * of pausing; can be null to call from elsewhere.
1398 *
1399 * @return Returns true if something is being resumed, or false if
1400 * nothing happened.
1401 */
1402 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001403 return resumeTopActivityLocked(prev, null);
1404 }
1405
1406 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001407 // Find the first activity that is not finishing.
1408 ActivityRecord next = topRunningActivityLocked(null);
1409
1410 // Remember how we'll process this pause/resume situation, and ensure
1411 // that the state is reset however we wind up proceeding.
1412 final boolean userLeaving = mUserLeaving;
1413 mUserLeaving = false;
1414
1415 if (next == null) {
1416 // There are no more activities! Let's just start up the
1417 // Launcher...
1418 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001419 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001420 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001421 }
1422 }
1423
1424 next.delayedResume = false;
1425
1426 // If the top activity is the resumed one, nothing to do.
1427 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1428 // Make sure we have executed any pending transitions, since there
1429 // should be nothing left to do at this point.
1430 mService.mWindowManager.executeAppTransition();
1431 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001432 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001433 return false;
1434 }
1435
1436 // If we are sleeping, and there is no resumed activity, and the top
1437 // activity is paused, well that is the state we want.
1438 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001439 && mLastPausedActivity == next
1440 && (next.state == ActivityState.PAUSED
1441 || next.state == ActivityState.STOPPED
1442 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001443 // Make sure we have executed any pending transitions, since there
1444 // should be nothing left to do at this point.
1445 mService.mWindowManager.executeAppTransition();
1446 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001447 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001448 return false;
1449 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001450
1451 // Make sure that the user who owns this activity is started. If not,
1452 // we will just leave it as is because someone should be bringing
1453 // another user's activities to the top of the stack.
1454 if (mService.mStartedUsers.get(next.userId) == null) {
1455 Slog.w(TAG, "Skipping resume of top activity " + next
1456 + ": user " + next.userId + " is stopped");
1457 return false;
1458 }
1459
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001460 // The activity may be waiting for stop, but that is no longer
1461 // appropriate for it.
1462 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001463 mGoingToSleepActivities.remove(next);
1464 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001465 mWaitingVisibleActivities.remove(next);
1466
Dianne Hackborn84375872012-06-01 19:03:50 -07001467 next.updateOptionsLocked(options);
1468
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001469 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1470
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001471 // If we are currently pausing an activity, then don't do anything
1472 // until that is done.
1473 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001474 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1475 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001476 return false;
1477 }
1478
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001479 // Okay we are now going to start a switch, to 'next'. We may first
1480 // have to pause the current activity, but this is an important point
1481 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001482 // XXX "App Redirected" dialog is getting too many false positives
1483 // at this point, so turn off for now.
1484 if (false) {
1485 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1486 long now = SystemClock.uptimeMillis();
1487 final boolean inTime = mLastStartedActivity.startTime != 0
1488 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1489 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1490 final int nextUid = next.info.applicationInfo.uid;
1491 if (inTime && lastUid != nextUid
1492 && lastUid != next.launchedFromUid
1493 && mService.checkPermission(
1494 android.Manifest.permission.STOP_APP_SWITCHES,
1495 -1, next.launchedFromUid)
1496 != PackageManager.PERMISSION_GRANTED) {
1497 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1498 } else {
1499 next.startTime = now;
1500 mLastStartedActivity = next;
1501 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001502 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001503 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001504 mLastStartedActivity = next;
1505 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001506 }
1507
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001508 // We need to start pausing the current activity so the top one
1509 // can be resumed...
1510 if (mResumedActivity != null) {
1511 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001512 // At this point we want to put the upcoming activity's process
1513 // at the top of the LRU list, since we know we will be needing it
1514 // very soon and it would be a waste to let it get killed if it
1515 // happens to be sitting towards the end.
1516 if (next.app != null && next.app.thread != null) {
1517 // No reason to do full oom adj update here; we'll let that
1518 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001519 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001520 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001521 startPausingLocked(userLeaving, false);
1522 return true;
1523 }
1524
Christopher Tated3f175c2012-06-14 14:16:54 -07001525 // If the most recent activity was noHistory but was only stopped rather
1526 // than stopped+finished because the device went to sleep, we need to make
1527 // sure to finish it as we're making a new activity topmost.
1528 final ActivityRecord last = mLastPausedActivity;
1529 if (mService.mSleeping && last != null && !last.finishing) {
1530 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1531 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1532 if (DEBUG_STATES) {
1533 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1534 }
1535 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001536 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001537 }
1538 }
1539
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001540 if (prev != null && prev != next) {
1541 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1542 prev.waitingVisible = true;
1543 mWaitingVisibleActivities.add(prev);
1544 if (DEBUG_SWITCH) Slog.v(
1545 TAG, "Resuming top, waiting visible to hide: " + prev);
1546 } else {
1547 // The next activity is already visible, so hide the previous
1548 // activity's windows right now so we can show the new one ASAP.
1549 // We only do this if the previous is finishing, which should mean
1550 // it is on top of the one being resumed so hiding it quickly
1551 // is good. Otherwise, we want to do the normal route of allowing
1552 // the resumed activity to be shown so we can decide if the
1553 // previous should actually be hidden depending on whether the
1554 // new one is found to be full-screen or not.
1555 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001556 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001557 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1558 + prev + ", waitingVisible="
1559 + (prev != null ? prev.waitingVisible : null)
1560 + ", nowVisible=" + next.nowVisible);
1561 } else {
1562 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1563 + prev + ", waitingVisible="
1564 + (prev != null ? prev.waitingVisible : null)
1565 + ", nowVisible=" + next.nowVisible);
1566 }
1567 }
1568 }
1569
Dianne Hackborne7f97212011-02-24 14:40:20 -08001570 // Launching this app's activity, make sure the app is no longer
1571 // considered stopped.
1572 try {
1573 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001574 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001575 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001576 } catch (IllegalArgumentException e) {
1577 Slog.w(TAG, "Failed trying to unstop package "
1578 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001579 }
1580
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 // We are starting up the next activity, so tell the window manager
1582 // that the previous one will be hidden soon. This way it can know
1583 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001584 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001585 if (prev != null) {
1586 if (prev.finishing) {
1587 if (DEBUG_TRANSITION) Slog.v(TAG,
1588 "Prepare close transition: prev=" + prev);
1589 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001590 mService.mWindowManager.prepareAppTransition(
1591 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001592 } else {
1593 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1594 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001595 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001596 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001597 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1598 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001599 } else {
1600 if (DEBUG_TRANSITION) Slog.v(TAG,
1601 "Prepare open transition: prev=" + prev);
1602 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001603 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001604 mService.mWindowManager.prepareAppTransition(
1605 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001606 } else {
1607 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1608 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001609 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001610 }
1611 }
1612 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001613 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1614 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001615 }
1616 } else if (mHistory.size() > 1) {
1617 if (DEBUG_TRANSITION) Slog.v(TAG,
1618 "Prepare open transition: no previous");
1619 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001620 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001621 mService.mWindowManager.prepareAppTransition(
1622 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001623 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001624 mService.mWindowManager.prepareAppTransition(
1625 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001626 }
1627 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001628 if (!noAnim) {
1629 next.applyOptionsLocked();
1630 } else {
1631 next.clearOptionsLocked();
1632 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001633
1634 if (next.app != null && next.app.thread != null) {
1635 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1636
1637 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001638 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001639
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001640 // schedule launch ticks to collect information about slow apps.
1641 next.startLaunchTickingLocked();
1642
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001643 ActivityRecord lastResumedActivity = mResumedActivity;
1644 ActivityState lastState = next.state;
1645
1646 mService.updateCpuStats();
1647
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001648 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001649 next.state = ActivityState.RESUMED;
1650 mResumedActivity = next;
1651 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001652 if (mMainStack) {
1653 mService.addRecentTaskLocked(next.task);
1654 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001655 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001656 updateLRUListLocked(next);
1657
1658 // Have the window manager re-evaluate the orientation of
1659 // the screen based on the new activity order.
1660 boolean updated = false;
1661 if (mMainStack) {
1662 synchronized (mService) {
1663 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1664 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001665 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001666 if (config != null) {
1667 next.frozenBeforeDestroy = true;
1668 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001669 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001670 }
1671 }
1672 if (!updated) {
1673 // The configuration update wasn't able to keep the existing
1674 // instance of the activity, and instead started a new one.
1675 // We should be all done, but let's just make sure our activity
1676 // is still at the top and schedule another run if something
1677 // weird happened.
1678 ActivityRecord nextNext = topRunningActivityLocked(null);
1679 if (DEBUG_SWITCH) Slog.i(TAG,
1680 "Activity config changed during resume: " + next
1681 + ", new next: " + nextNext);
1682 if (nextNext != next) {
1683 // Do over!
1684 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1685 }
1686 if (mMainStack) {
1687 mService.setFocusedActivityLocked(next);
1688 }
1689 ensureActivitiesVisibleLocked(null, 0);
1690 mService.mWindowManager.executeAppTransition();
1691 mNoAnimActivities.clear();
1692 return true;
1693 }
1694
1695 try {
1696 // Deliver all pending results.
1697 ArrayList a = next.results;
1698 if (a != null) {
1699 final int N = a.size();
1700 if (!next.finishing && N > 0) {
1701 if (DEBUG_RESULTS) Slog.v(
1702 TAG, "Delivering results to " + next
1703 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001704 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001705 }
1706 }
1707
1708 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001709 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 }
1711
1712 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001713 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001714 next.task.taskId, next.shortComponentName);
1715
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001716 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001717 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001718 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001719 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001720 mService.isNextTransitionForward());
1721
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001722 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001723
1724 } catch (Exception e) {
1725 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001726 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1727 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001728 next.state = lastState;
1729 mResumedActivity = lastResumedActivity;
1730 Slog.i(TAG, "Restarting because process died: " + next);
1731 if (!next.hasBeenLaunched) {
1732 next.hasBeenLaunched = true;
1733 } else {
1734 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1735 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001736 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001737 mService.compatibilityInfoForPackageLocked(
1738 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001739 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001740 next.labelRes, next.icon, next.windowFlags,
1741 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001742 }
1743 }
1744 startSpecificActivityLocked(next, true, false);
1745 return true;
1746 }
1747
1748 // From this point on, if something goes wrong there is no way
1749 // to recover the activity.
1750 try {
1751 next.visible = true;
1752 completeResumeLocked(next);
1753 } catch (Exception e) {
1754 // If any exception gets thrown, toss away this
1755 // activity and try the next one.
1756 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001757 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001758 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001759 return true;
1760 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001761 next.stopped = false;
1762
1763 } else {
1764 // Whoops, need to restart this activity!
1765 if (!next.hasBeenLaunched) {
1766 next.hasBeenLaunched = true;
1767 } else {
1768 if (SHOW_APP_STARTING_PREVIEW) {
1769 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001770 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001771 mService.compatibilityInfoForPackageLocked(
1772 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001773 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001774 next.labelRes, next.icon, next.windowFlags,
1775 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001776 }
1777 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1778 }
1779 startSpecificActivityLocked(next, true, true);
1780 }
1781
1782 return true;
1783 }
1784
1785 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001786 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001787 final int NH = mHistory.size();
1788
1789 int addPos = -1;
1790
1791 if (!newTask) {
1792 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 boolean startIt = true;
1794 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001795 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001796 if (p.finishing) {
1797 continue;
1798 }
1799 if (p.task == r.task) {
1800 // Here it is! Now, if this is not yet visible to the
1801 // user, then just add it without starting; it will
1802 // get started when the user navigates back to it.
1803 addPos = i+1;
1804 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001805 if (DEBUG_ADD_REMOVE) {
1806 RuntimeException here = new RuntimeException("here");
1807 here.fillInStackTrace();
1808 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1809 here);
1810 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001812 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001813 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07001814 r.info.screenOrientation, r.fullscreen,
1815 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001816 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001817 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001818 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001819 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 return;
1821 }
1822 break;
1823 }
1824 if (p.fullscreen) {
1825 startIt = false;
1826 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001827 }
1828 }
1829
1830 // Place a new activity at top of stack, so it is next to interact
1831 // with the user.
1832 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001833 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001834 }
1835
1836 // If we are not placing the new activity frontmost, we do not want
1837 // to deliver the onUserLeaving callback to the actual frontmost
1838 // activity
1839 if (addPos < NH) {
1840 mUserLeaving = false;
1841 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1842 }
1843
1844 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001845 if (DEBUG_ADD_REMOVE) {
1846 RuntimeException here = new RuntimeException("here");
1847 here.fillInStackTrace();
1848 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1849 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001850 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001851 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001852 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001853 if (NH > 0) {
1854 // We want to show the starting preview window if we are
1855 // switching to a new task, or the next activity's process is
1856 // not currently running.
1857 boolean showStartingIcon = newTask;
1858 ProcessRecord proc = r.app;
1859 if (proc == null) {
1860 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1861 }
1862 if (proc == null || proc.thread == null) {
1863 showStartingIcon = true;
1864 }
1865 if (DEBUG_TRANSITION) Slog.v(TAG,
1866 "Prepare open transition: starting " + r);
1867 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001868 mService.mWindowManager.prepareAppTransition(
1869 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001870 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001871 } else {
1872 mService.mWindowManager.prepareAppTransition(newTask
1873 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001874 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001875 mNoAnimActivities.remove(r);
1876 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001877 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001878 mService.mWindowManager.addAppToken(
Craig Mautner5962b122012-10-05 14:45:52 -07001879 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
1880 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001881 boolean doShow = true;
1882 if (newTask) {
1883 // Even though this activity is starting fresh, we still need
1884 // to reset it to make sure we apply affinities to move any
1885 // existing activities from other tasks in to it.
1886 // If the caller has requested that the target task be
1887 // reset, then do so.
1888 if ((r.intent.getFlags()
1889 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1890 resetTaskIfNeededLocked(r, r);
1891 doShow = topRunningNonDelayedActivityLocked(null) == r;
1892 }
1893 }
1894 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1895 // Figure out if we are transitioning from another activity that is
1896 // "has the same starting icon" as the next one. This allows the
1897 // window manager to keep the previous window it had previously
1898 // created, if it still had one.
1899 ActivityRecord prev = mResumedActivity;
1900 if (prev != null) {
1901 // We don't want to reuse the previous starting preview if:
1902 // (1) The current activity is in a different task.
1903 if (prev.task != r.task) prev = null;
1904 // (2) The current activity is already displayed.
1905 else if (prev.nowVisible) prev = null;
1906 }
1907 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001908 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001909 mService.compatibilityInfoForPackageLocked(
1910 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001911 r.labelRes, r.icon, r.windowFlags,
1912 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 }
1914 } else {
1915 // If this is the first activity, don't do any fancy animations,
1916 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001917 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07001918 r.info.screenOrientation, r.fullscreen,
1919 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001920 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 }
1922 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001923 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001924 }
1925
1926 if (doResume) {
1927 resumeTopActivityLocked(null);
1928 }
1929 }
1930
Dianne Hackbornbe707852011-11-11 14:32:10 -08001931 final void validateAppTokensLocked() {
1932 mValidateAppTokens.clear();
1933 mValidateAppTokens.ensureCapacity(mHistory.size());
1934 for (int i=0; i<mHistory.size(); i++) {
1935 mValidateAppTokens.add(mHistory.get(i).appToken);
1936 }
1937 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1938 }
1939
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001940 /**
1941 * Perform a reset of the given task, if needed as part of launching it.
1942 * Returns the new HistoryRecord at the top of the task.
1943 */
1944 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1945 ActivityRecord newActivity) {
1946 boolean forceReset = (newActivity.info.flags
1947 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001948 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1949 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001950 if ((newActivity.info.flags
1951 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1952 forceReset = true;
1953 }
1954 }
1955
1956 final TaskRecord task = taskTop.task;
1957
1958 // We are going to move through the history list so that we can look
1959 // at each activity 'target' with 'below' either the interesting
1960 // activity immediately below it in the stack or null.
1961 ActivityRecord target = null;
1962 int targetI = 0;
1963 int taskTopI = -1;
1964 int replyChainEnd = -1;
1965 int lastReparentPos = -1;
1966 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001967 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001968
1969 if (below != null && below.finishing) {
1970 continue;
1971 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001972 // Don't check any lower in the stack if we're crossing a user boundary.
1973 if (below != null && below.userId != taskTop.userId) {
1974 break;
1975 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001976 if (target == null) {
1977 target = below;
1978 targetI = i;
1979 // If we were in the middle of a reply chain before this
1980 // task, it doesn't appear like the root of the chain wants
1981 // anything interesting, so drop it.
1982 replyChainEnd = -1;
1983 continue;
1984 }
1985
1986 final int flags = target.info.flags;
1987
1988 final boolean finishOnTaskLaunch =
1989 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1990 final boolean allowTaskReparenting =
1991 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1992
1993 if (target.task == task) {
1994 // We are inside of the task being reset... we'll either
1995 // finish this activity, push it out for another task,
1996 // or leave it as-is. We only do this
1997 // for activities that are not the root of the task (since
1998 // if we finish the root, we may no longer have the task!).
1999 if (taskTopI < 0) {
2000 taskTopI = targetI;
2001 }
2002 if (below != null && below.task == task) {
2003 final boolean clearWhenTaskReset =
2004 (target.intent.getFlags()
2005 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2006 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
2007 // If this activity is sending a reply to a previous
2008 // activity, we can't do anything with it now until
2009 // we reach the start of the reply chain.
2010 // XXX note that we are assuming the result is always
2011 // to the previous activity, which is almost always
2012 // the case but we really shouldn't count on.
2013 if (replyChainEnd < 0) {
2014 replyChainEnd = targetI;
2015 }
2016 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2017 && target.taskAffinity != null
2018 && !target.taskAffinity.equals(task.affinity)) {
2019 // If this activity has an affinity for another
2020 // task, then we need to move it out of here. We will
2021 // move it as far out of the way as possible, to the
2022 // bottom of the activity stack. This also keeps it
2023 // correctly ordered with any activities we previously
2024 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002025 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002026 if (target.taskAffinity != null
2027 && target.taskAffinity.equals(p.task.affinity)) {
2028 // If the activity currently at the bottom has the
2029 // same task affinity as the one we are moving,
2030 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002031 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002032 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2033 + " out to bottom task " + p.task);
2034 } else {
2035 mService.mCurTask++;
2036 if (mService.mCurTask <= 0) {
2037 mService.mCurTask = 1;
2038 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002039 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2040 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002041 target.task.affinityIntent = target.intent;
2042 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2043 + " out to new task " + target.task);
2044 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002045 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002046 if (replyChainEnd < 0) {
2047 replyChainEnd = targetI;
2048 }
2049 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002050 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002051 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002052 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002053 if (p.finishing) {
2054 continue;
2055 }
2056 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2057 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002058 p.setTask(target.task, curThumbHolder, false);
2059 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002060 if (DEBUG_ADD_REMOVE) {
2061 RuntimeException here = new RuntimeException("here");
2062 here.fillInStackTrace();
2063 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2064 + dstPos, here);
2065 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002066 mHistory.remove(srcPos);
2067 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002068 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2069 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002070 dstPos++;
2071 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002072 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002073 }
2074 i++;
2075 }
2076 if (taskTop == p) {
2077 taskTop = below;
2078 }
2079 if (taskTopI == replyChainEnd) {
2080 taskTopI = -1;
2081 }
2082 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002083 } else if (forceReset || finishOnTaskLaunch
2084 || clearWhenTaskReset) {
2085 // If the activity should just be removed -- either
2086 // because it asks for it, or the task should be
2087 // cleared -- then finish it and anything that is
2088 // part of its reply chain.
2089 if (clearWhenTaskReset) {
2090 // In this case, we want to finish this activity
2091 // and everything above it, so be sneaky and pretend
2092 // like these are all in the reply chain.
2093 replyChainEnd = targetI+1;
2094 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002095 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002096 replyChainEnd)).task == task) {
2097 replyChainEnd++;
2098 }
2099 replyChainEnd--;
2100 } else if (replyChainEnd < 0) {
2101 replyChainEnd = targetI;
2102 }
2103 ActivityRecord p = null;
2104 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002105 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002106 if (p.finishing) {
2107 continue;
2108 }
2109 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002110 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002111 replyChainEnd--;
2112 srcPos--;
2113 }
2114 }
2115 if (taskTop == p) {
2116 taskTop = below;
2117 }
2118 if (taskTopI == replyChainEnd) {
2119 taskTopI = -1;
2120 }
2121 replyChainEnd = -1;
2122 } else {
2123 // If we were in the middle of a chain, well the
2124 // activity that started it all doesn't want anything
2125 // special, so leave it all as-is.
2126 replyChainEnd = -1;
2127 }
2128 } else {
2129 // Reached the bottom of the task -- any reply chain
2130 // should be left as-is.
2131 replyChainEnd = -1;
2132 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002133
2134 } else if (target.resultTo != null && (below == null
2135 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002136 // If this activity is sending a reply to a previous
2137 // activity, we can't do anything with it now until
2138 // we reach the start of the reply chain.
2139 // XXX note that we are assuming the result is always
2140 // to the previous activity, which is almost always
2141 // the case but we really shouldn't count on.
2142 if (replyChainEnd < 0) {
2143 replyChainEnd = targetI;
2144 }
2145
2146 } else if (taskTopI >= 0 && allowTaskReparenting
2147 && task.affinity != null
2148 && task.affinity.equals(target.taskAffinity)) {
2149 // We are inside of another task... if this activity has
2150 // an affinity for our task, then either remove it if we are
2151 // clearing or move it over to our task. Note that
2152 // we currently punt on the case where we are resetting a
2153 // task that is not at the top but who has activities above
2154 // with an affinity to it... this is really not a normal
2155 // case, and we will need to later pull that task to the front
2156 // and usually at that point we will do the reset and pick
2157 // up those remaining activities. (This only happens if
2158 // someone starts an activity in a new task from an activity
2159 // in a task that is not currently on top.)
2160 if (forceReset || finishOnTaskLaunch) {
2161 if (replyChainEnd < 0) {
2162 replyChainEnd = targetI;
2163 }
2164 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002165 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2166 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002167 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002168 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002169 if (p.finishing) {
2170 continue;
2171 }
2172 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002173 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002174 taskTopI--;
2175 lastReparentPos--;
2176 replyChainEnd--;
2177 srcPos--;
2178 }
2179 }
2180 replyChainEnd = -1;
2181 } else {
2182 if (replyChainEnd < 0) {
2183 replyChainEnd = targetI;
2184 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002185 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2186 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002187 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002188 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002189 if (p.finishing) {
2190 continue;
2191 }
2192 if (lastReparentPos < 0) {
2193 lastReparentPos = taskTopI;
2194 taskTop = p;
2195 } else {
2196 lastReparentPos--;
2197 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002198 if (DEBUG_ADD_REMOVE) {
2199 RuntimeException here = new RuntimeException("here");
2200 here.fillInStackTrace();
2201 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2202 + lastReparentPos, here);
2203 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002204 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002205 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002206 mHistory.add(lastReparentPos, p);
2207 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002208 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002209 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002210 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2211 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002212 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002213 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002214 }
2215 }
2216 replyChainEnd = -1;
2217
2218 // Now we've moved it in to place... but what if this is
2219 // a singleTop activity and we have put it on top of another
2220 // instance of the same activity? Then we drop the instance
2221 // below so it remains singleTop.
2222 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2223 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002224 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002225 if (p.finishing) {
2226 continue;
2227 }
2228 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2229 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002230 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002231 taskTopI--;
2232 lastReparentPos--;
2233 }
2234 }
2235 }
2236 }
2237 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002238
2239 } else if (below != null && below.task != target.task) {
2240 // We hit the botton of a task; the reply chain can't
2241 // pass through it.
2242 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002243 }
2244
2245 target = below;
2246 targetI = i;
2247 }
2248
2249 return taskTop;
2250 }
2251
2252 /**
2253 * Perform clear operation as requested by
2254 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2255 * stack to the given task, then look for
2256 * an instance of that activity in the stack and, if found, finish all
2257 * activities on top of it and return the instance.
2258 *
2259 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002260 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002261 * or null if none was found.
2262 */
2263 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002264 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002265 int i = mHistory.size();
2266
2267 // First find the requested task.
2268 while (i > 0) {
2269 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002270 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002271 if (r.task.taskId == taskId) {
2272 i++;
2273 break;
2274 }
2275 }
2276
2277 // Now clear it.
2278 while (i > 0) {
2279 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002280 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002281 if (r.finishing) {
2282 continue;
2283 }
2284 if (r.task.taskId != taskId) {
2285 return null;
2286 }
2287 if (r.realActivity.equals(newR.realActivity)) {
2288 // Here it is! Now finish everything in front...
2289 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002290 while (i < (mHistory.size()-1)) {
2291 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002292 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002293 if (r.task.taskId != taskId) {
2294 break;
2295 }
2296 if (r.finishing) {
2297 continue;
2298 }
2299 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002300 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002301 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002302 }
2303 }
2304
2305 // Finally, if this is a normal launch mode (that is, not
2306 // expecting onNewIntent()), then we will finish the current
2307 // instance of the activity so a new fresh one can be started.
2308 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2309 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2310 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002311 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002312 if (index >= 0) {
2313 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002314 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002315 }
2316 return null;
2317 }
2318 }
2319
2320 return ret;
2321 }
2322 }
2323
2324 return null;
2325 }
2326
2327 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002328 * Completely remove all activities associated with an existing
2329 * task starting at a specified index.
2330 */
2331 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002332 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002333 ActivityRecord r = mHistory.get(i);
2334 if (r.task.taskId != taskId) {
2335 // Whoops hit the end.
2336 return;
2337 }
2338 if (r.finishing) {
2339 i++;
2340 continue;
2341 }
2342 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002343 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002344 i++;
2345 }
2346 }
2347 }
2348
2349 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002350 * Completely remove all activities associated with an existing task.
2351 */
2352 private final void performClearTaskLocked(int taskId) {
2353 int i = mHistory.size();
2354
2355 // First find the requested task.
2356 while (i > 0) {
2357 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002358 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002359 if (r.task.taskId == taskId) {
2360 i++;
2361 break;
2362 }
2363 }
2364
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002365 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002366 while (i > 0) {
2367 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002368 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002369 if (r.finishing) {
2370 continue;
2371 }
2372 if (r.task.taskId != taskId) {
2373 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002374 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002375 return;
2376 }
2377 }
2378 }
2379
2380 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002381 * Find the activity in the history stack within the given task. Returns
2382 * the index within the history at which it's found, or < 0 if not found.
2383 */
2384 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2385 int i = mHistory.size();
2386 while (i > 0) {
2387 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002388 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002389 if (candidate.finishing) {
2390 continue;
2391 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002392 if (candidate.task.taskId != task) {
2393 break;
2394 }
2395 if (candidate.realActivity.equals(r.realActivity)) {
2396 return i;
2397 }
2398 }
2399
2400 return -1;
2401 }
2402
2403 /**
2404 * Reorder the history stack so that the activity at the given index is
2405 * brought to the front.
2406 */
2407 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002408 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002409 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002410 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002411 if (DEBUG_ADD_REMOVE) {
2412 RuntimeException here = new RuntimeException("here");
2413 here.fillInStackTrace();
2414 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2415 + top, here);
2416 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002417 mHistory.add(top, newTop);
2418 oldTop.frontOfTask = false;
2419 newTop.frontOfTask = true;
2420 return newTop;
2421 }
2422
2423 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002424 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002425 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002426 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002427 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002428
Dianne Hackborna4972e92012-03-14 10:38:05 -07002429 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002430
2431 ProcessRecord callerApp = null;
2432 if (caller != null) {
2433 callerApp = mService.getRecordForAppLocked(caller);
2434 if (callerApp != null) {
2435 callingPid = callerApp.pid;
2436 callingUid = callerApp.info.uid;
2437 } else {
2438 Slog.w(TAG, "Unable to find app for caller " + caller
2439 + " (pid=" + callingPid + ") when starting: "
2440 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002441 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002442 }
2443 }
2444
Dianne Hackborna4972e92012-03-14 10:38:05 -07002445 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002446 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002447 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2448 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002449 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002450
2451 ActivityRecord sourceRecord = null;
2452 ActivityRecord resultRecord = null;
2453 if (resultTo != null) {
2454 int index = indexOfTokenLocked(resultTo);
2455 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002456 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002457 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002458 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002459 if (requestCode >= 0 && !sourceRecord.finishing) {
2460 resultRecord = sourceRecord;
2461 }
2462 }
2463 }
2464
2465 int launchFlags = intent.getFlags();
2466
2467 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2468 && sourceRecord != null) {
2469 // Transfer the result target from the source activity to the new
2470 // one being started, including any failures.
2471 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002472 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002473 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002474 }
2475 resultRecord = sourceRecord.resultTo;
2476 resultWho = sourceRecord.resultWho;
2477 requestCode = sourceRecord.requestCode;
2478 sourceRecord.resultTo = null;
2479 if (resultRecord != null) {
2480 resultRecord.removeResultsLocked(
2481 sourceRecord, resultWho, requestCode);
2482 }
2483 }
2484
Dianne Hackborna4972e92012-03-14 10:38:05 -07002485 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002486 // We couldn't find a class that can handle the given Intent.
2487 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002488 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002489 }
2490
Dianne Hackborna4972e92012-03-14 10:38:05 -07002491 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002492 // We couldn't find the specific class specified in the Intent.
2493 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002494 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002495 }
2496
Dianne Hackborna4972e92012-03-14 10:38:05 -07002497 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002498 if (resultRecord != null) {
2499 sendActivityResultLocked(-1,
2500 resultRecord, resultWho, requestCode,
2501 Activity.RESULT_CANCELED, null);
2502 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002503 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002504 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002505 return err;
2506 }
2507
Jeff Sharkey35be7562012-04-18 19:16:15 -07002508 final int startAnyPerm = mService.checkPermission(
2509 START_ANY_ACTIVITY, callingPid, callingUid);
2510 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002511 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002512 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 if (resultRecord != null) {
2514 sendActivityResultLocked(-1,
2515 resultRecord, resultWho, requestCode,
2516 Activity.RESULT_CANCELED, null);
2517 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002518 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002519 String msg;
2520 if (!aInfo.exported) {
2521 msg = "Permission Denial: starting " + intent.toString()
2522 + " from " + callerApp + " (pid=" + callingPid
2523 + ", uid=" + callingUid + ")"
2524 + " not exported from uid " + aInfo.applicationInfo.uid;
2525 } else {
2526 msg = "Permission Denial: starting " + intent.toString()
2527 + " from " + callerApp + " (pid=" + callingPid
2528 + ", uid=" + callingUid + ")"
2529 + " requires " + aInfo.permission;
2530 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002531 Slog.w(TAG, msg);
2532 throw new SecurityException(msg);
2533 }
2534
2535 if (mMainStack) {
2536 if (mService.mController != null) {
2537 boolean abort = false;
2538 try {
2539 // The Intent we give to the watcher has the extra data
2540 // stripped off, since it can contain private information.
2541 Intent watchIntent = intent.cloneFilter();
2542 abort = !mService.mController.activityStarting(watchIntent,
2543 aInfo.applicationInfo.packageName);
2544 } catch (RemoteException e) {
2545 mService.mController = null;
2546 }
2547
2548 if (abort) {
2549 if (resultRecord != null) {
2550 sendActivityResultLocked(-1,
2551 resultRecord, resultWho, requestCode,
2552 Activity.RESULT_CANCELED, null);
2553 }
2554 // We pretend to the caller that it was really started, but
2555 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002556 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002557 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002558 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002559 }
2560 }
2561 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002562
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002563 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2564 intent, resolvedType, aInfo, mService.mConfiguration,
2565 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002566 if (outActivity != null) {
2567 outActivity[0] = r;
2568 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002569
2570 if (mMainStack) {
2571 if (mResumedActivity == null
2572 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2573 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2574 PendingActivityLaunch pal = new PendingActivityLaunch();
2575 pal.r = r;
2576 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002577 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002579 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002580 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002581 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002582 }
2583 }
2584
2585 if (mService.mDidAppSwitch) {
2586 // This is the second allowed switch since we stopped switches,
2587 // so now just generally allow switches. Use case: user presses
2588 // home (switches disabled, switch to home, mDidAppSwitch now true);
2589 // user taps a home icon (coming from home so allowed, we hit here
2590 // and now allow anyone to switch again).
2591 mService.mAppSwitchesAllowedTime = 0;
2592 } else {
2593 mService.mDidAppSwitch = true;
2594 }
2595
2596 mService.doPendingActivityLaunchesLocked(false);
2597 }
2598
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002599 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002600 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002601 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002602 // Someone asked to have the keyguard dismissed on the next
2603 // activity start, but we are not actually doing an activity
2604 // switch... just dismiss the keyguard now, because we
2605 // probably want to see whatever is behind it.
2606 mDismissKeyguardOnNextActivity = false;
2607 mService.mWindowManager.dismissKeyguard();
2608 }
2609 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002610 }
2611
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002612 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2613 if ((launchFlags &
2614 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2615 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2616 // Caller wants to appear on home activity, so before starting
2617 // their own activity we will bring home to the front.
2618 moveHomeToFrontLocked();
2619 }
2620 }
2621
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002622 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002623 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2624 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002625 final Intent intent = r.intent;
2626 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002627
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002628 int launchFlags = intent.getFlags();
2629
2630 // We'll invoke onUserLeaving before onPause only if the launching
2631 // activity did not explicitly state that this is an automated launch.
2632 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2633 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2634 "startActivity() => mUserLeaving=" + mUserLeaving);
2635
2636 // If the caller has asked not to resume at this point, we make note
2637 // of this in the record so that we can skip it when trying to find
2638 // the top running activity.
2639 if (!doResume) {
2640 r.delayedResume = true;
2641 }
2642
2643 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2644 != 0 ? r : null;
2645
2646 // If the onlyIfNeeded flag is set, then we can do this if the activity
2647 // being launched is the same as the one making the call... or, as
2648 // a special case, if we do not know the caller then we count the
2649 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002650 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002651 ActivityRecord checkedCaller = sourceRecord;
2652 if (checkedCaller == null) {
2653 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2654 }
2655 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2656 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002657 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002658 }
2659 }
2660
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002661 if (sourceRecord == null) {
2662 // This activity is not being started from another... in this
2663 // case we -always- start a new task.
2664 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2665 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2666 + intent);
2667 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2668 }
2669 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2670 // The original activity who is starting us is running as a single
2671 // instance... this new activity it is starting must go on its
2672 // own task.
2673 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2674 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2675 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2676 // The activity being started is a single instance... it always
2677 // gets launched into its own task.
2678 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2679 }
2680
2681 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2682 // For whatever reason this activity is being launched into a new
2683 // task... yet the caller has requested a result back. Well, that
2684 // is pretty messed up, so instead immediately send back a cancel
2685 // and let the new task continue launched as normal without a
2686 // dependency on its originator.
2687 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2688 sendActivityResultLocked(-1,
2689 r.resultTo, r.resultWho, r.requestCode,
2690 Activity.RESULT_CANCELED, null);
2691 r.resultTo = null;
2692 }
2693
2694 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002695 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002696 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002697 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2698 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2699 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2700 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2701 // If bring to front is requested, and no result is requested, and
2702 // we can find a task that was started with this same
2703 // component, then instead of launching bring that one to the front.
2704 if (r.resultTo == null) {
2705 // See if there is a task to bring to the front. If this is
2706 // a SINGLE_INSTANCE activity, there can be one and only one
2707 // instance of it in the history, and it is always in its own
2708 // unique task, so we do a special search.
2709 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2710 ? findTaskLocked(intent, r.info)
2711 : findActivityLocked(intent, r.info);
2712 if (taskTop != null) {
2713 if (taskTop.task.intent == null) {
2714 // This task was started because of movement of
2715 // the activity based on affinity... now that we
2716 // are actually launching it, we can assign the
2717 // base intent.
2718 taskTop.task.setIntent(intent, r.info);
2719 }
2720 // If the target task is not in the front, then we need
2721 // to bring it to the front... except... well, with
2722 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2723 // to have the same behavior as if a new instance was
2724 // being started, which means not bringing it to the front
2725 // if the caller is not itself in the front.
2726 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002727 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002728 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2729 boolean callerAtFront = sourceRecord == null
2730 || curTop.task == sourceRecord.task;
2731 if (callerAtFront) {
2732 // We really do want to push this one into the
2733 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002734 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002735 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002736 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002737 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002738 }
2739 }
2740 // If the caller has requested that the target task be
2741 // reset, then do so.
2742 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2743 taskTop = resetTaskIfNeededLocked(taskTop, r);
2744 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002745 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002746 // We don't need to start a new activity, and
2747 // the client said not to do anything if that
2748 // is the case, so this is it! And for paranoia, make
2749 // sure we have correctly resumed the top activity.
2750 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002751 resumeTopActivityLocked(null, options);
2752 } else {
2753 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002754 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002755 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002756 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002757 if ((launchFlags &
2758 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2759 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2760 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002761 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002762 // not be too hard...
2763 reuseTask = taskTop.task;
2764 performClearTaskLocked(taskTop.task.taskId);
2765 reuseTask.setIntent(r.intent, r.info);
2766 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002767 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2768 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2769 // In this situation we want to remove all activities
2770 // from the task up to the one being started. In most
2771 // cases this means we are resetting the task to its
2772 // initial state.
2773 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002774 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002775 if (top != null) {
2776 if (top.frontOfTask) {
2777 // Activity aliases may mean we use different
2778 // intents for the top activity, so make sure
2779 // the task now has the identity of the new
2780 // intent.
2781 top.task.setIntent(r.intent, r.info);
2782 }
2783 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002784 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002785 } else {
2786 // A special case: we need to
2787 // start the activity because it is not currently
2788 // running, and the caller has asked to clear the
2789 // current task to have this activity at the top.
2790 addingToTask = true;
2791 // Now pretend like this activity is being started
2792 // by the top of its task, so it is put in the
2793 // right place.
2794 sourceRecord = taskTop;
2795 }
2796 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2797 // In this case the top activity on the task is the
2798 // same as the one being launched, so we take that
2799 // as a request to bring the task to the foreground.
2800 // If the top activity in the task is the root
2801 // activity, deliver this new intent to it if it
2802 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002803 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2804 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002805 && taskTop.realActivity.equals(r.realActivity)) {
2806 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2807 if (taskTop.frontOfTask) {
2808 taskTop.task.setIntent(r.intent, r.info);
2809 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002810 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002811 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2812 // In this case we are launching the root activity
2813 // of the task, but with a different intent. We
2814 // should start a new instance on top.
2815 addingToTask = true;
2816 sourceRecord = taskTop;
2817 }
2818 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2819 // In this case an activity is being launched in to an
2820 // existing task, without resetting that task. This
2821 // is typically the situation of launching an activity
2822 // from a notification or shortcut. We want to place
2823 // the new activity on top of the current task.
2824 addingToTask = true;
2825 sourceRecord = taskTop;
2826 } else if (!taskTop.task.rootWasReset) {
2827 // In this case we are launching in to an existing task
2828 // that has not yet been started from its front door.
2829 // The current task has been brought to the front.
2830 // Ideally, we'd probably like to place this new task
2831 // at the bottom of its stack, but that's a little hard
2832 // to do with the current organization of the code so
2833 // for now we'll just drop it.
2834 taskTop.task.setIntent(r.intent, r.info);
2835 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002836 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 // We didn't do anything... but it was needed (a.k.a., client
2838 // don't use that intent!) And for paranoia, make
2839 // sure we have correctly resumed the top activity.
2840 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002841 resumeTopActivityLocked(null, options);
2842 } else {
2843 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002844 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002845 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002846 }
2847 }
2848 }
2849 }
2850
2851 //String uri = r.intent.toURI();
2852 //Intent intent2 = new Intent(uri);
2853 //Slog.i(TAG, "Given intent: " + r.intent);
2854 //Slog.i(TAG, "URI is: " + uri);
2855 //Slog.i(TAG, "To intent: " + intent2);
2856
2857 if (r.packageName != null) {
2858 // If the activity being launched is the same as the one currently
2859 // at the top, then we need to check if it should only be launched
2860 // once.
2861 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2862 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002863 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002864 if (top.app != null && top.app.thread != null) {
2865 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2866 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2867 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2868 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2869 // For paranoia, make sure we have correctly
2870 // resumed the top activity.
2871 if (doResume) {
2872 resumeTopActivityLocked(null);
2873 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002874 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002875 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002876 // We don't need to start a new activity, and
2877 // the client said not to do anything if that
2878 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002879 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002880 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002881 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002882 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002883 }
2884 }
2885 }
2886 }
2887
2888 } else {
2889 if (r.resultTo != null) {
2890 sendActivityResultLocked(-1,
2891 r.resultTo, r.resultWho, r.requestCode,
2892 Activity.RESULT_CANCELED, null);
2893 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002894 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002895 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002896 }
2897
2898 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002899 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002900
2901 // Should this be considered a new task?
2902 if (r.resultTo == null && !addingToTask
2903 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002904 if (reuseTask == null) {
2905 // todo: should do better management of integers.
2906 mService.mCurTask++;
2907 if (mService.mCurTask <= 0) {
2908 mService.mCurTask = 1;
2909 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002910 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002911 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2912 + " in new task " + r.task);
2913 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002914 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002915 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002916 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002917 if (!movedHome) {
2918 moveHomeToFrontFromLaunchLocked(launchFlags);
2919 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002920
2921 } else if (sourceRecord != null) {
2922 if (!addingToTask &&
2923 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2924 // In this case, we are adding the activity to an existing
2925 // task, but the caller has asked to clear that task if the
2926 // activity is already running.
2927 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002928 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002929 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002930 if (top != null) {
2931 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002932 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002933 // For paranoia, make sure we have correctly
2934 // resumed the top activity.
2935 if (doResume) {
2936 resumeTopActivityLocked(null);
2937 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002938 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002939 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002940 }
2941 } else if (!addingToTask &&
2942 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2943 // In this case, we are launching an activity in our own task
2944 // that may already be running somewhere in the history, and
2945 // we want to shuffle it to the front of the stack if so.
2946 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2947 if (where >= 0) {
2948 ActivityRecord top = moveActivityToFrontLocked(where);
2949 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002950 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002951 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002952 if (doResume) {
2953 resumeTopActivityLocked(null);
2954 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002955 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002956 }
2957 }
2958 // An existing activity is starting this new activity, so we want
2959 // to keep the new one in the same task as the one that is starting
2960 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002961 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002962 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2963 + " in existing task " + r.task);
2964
2965 } else {
2966 // This not being started from an existing activity, and not part
2967 // of a new task... just put it in the top task, though these days
2968 // this case should never happen.
2969 final int N = mHistory.size();
2970 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002971 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002972 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002973 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002974 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002975 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2976 + " in new guessed " + r.task);
2977 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002978
Dianne Hackborn39792d22010-08-19 18:01:52 -07002979 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002980 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002981
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002982 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002983 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002984 }
2985 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002986 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002987 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002988 }
2989
Dianne Hackborna4972e92012-03-14 10:38:05 -07002990 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002991 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002992 // Collect information about the target of the Intent.
2993 ActivityInfo aInfo;
2994 try {
2995 ResolveInfo rInfo =
2996 AppGlobals.getPackageManager().resolveIntent(
2997 intent, resolvedType,
2998 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002999 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003000 aInfo = rInfo != null ? rInfo.activityInfo : null;
3001 } catch (RemoteException e) {
3002 aInfo = null;
3003 }
3004
3005 if (aInfo != null) {
3006 // Store the found target back into the intent, because now that
3007 // we have it we never want to do this again. For example, if the
3008 // user navigates back to this point in the history, we should
3009 // always restart the exact same activity.
3010 intent.setComponent(new ComponentName(
3011 aInfo.applicationInfo.packageName, aInfo.name));
3012
3013 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003014 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003015 if (!aInfo.processName.equals("system")) {
3016 mService.setDebugApp(aInfo.processName, true, false);
3017 }
3018 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003019
Dianne Hackborna4972e92012-03-14 10:38:05 -07003020 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003021 if (!aInfo.processName.equals("system")) {
3022 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3023 }
3024 }
3025
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003026 if (profileFile != null) {
3027 if (!aInfo.processName.equals("system")) {
3028 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003029 profileFile, profileFd,
3030 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003031 }
3032 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003033 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003034 return aInfo;
3035 }
3036
3037 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003038 Intent intent, String resolvedType, IBinder resultTo,
3039 String resultWho, int requestCode, int startFlags, String profileFile,
3040 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3041 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003042 // Refuse possible leaked file descriptors
3043 if (intent != null && intent.hasFileDescriptors()) {
3044 throw new IllegalArgumentException("File descriptors passed in Intent");
3045 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003046 boolean componentSpecified = intent.getComponent() != null;
3047
3048 // Don't modify the client's object!
3049 intent = new Intent(intent);
3050
3051 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003052 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003053 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003054
3055 synchronized (mService) {
3056 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003057 if (callingUid >= 0) {
3058 callingPid = -1;
3059 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003060 callingPid = Binder.getCallingPid();
3061 callingUid = Binder.getCallingUid();
3062 } else {
3063 callingPid = callingUid = -1;
3064 }
3065
3066 mConfigWillChange = config != null
3067 && mService.mConfiguration.diff(config) != 0;
3068 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3069 "Starting activity when config will change = " + mConfigWillChange);
3070
3071 final long origId = Binder.clearCallingIdentity();
3072
3073 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003074 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003075 // This may be a heavy-weight process! Check to see if we already
3076 // have another, different heavy-weight process running.
3077 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3078 if (mService.mHeavyWeightProcess != null &&
3079 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3080 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3081 int realCallingPid = callingPid;
3082 int realCallingUid = callingUid;
3083 if (caller != null) {
3084 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3085 if (callerApp != null) {
3086 realCallingPid = callerApp.pid;
3087 realCallingUid = callerApp.info.uid;
3088 } else {
3089 Slog.w(TAG, "Unable to find app for caller " + caller
3090 + " (pid=" + realCallingPid + ") when starting: "
3091 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003092 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003093 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003094 }
3095 }
3096
3097 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003098 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003099 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003100 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003101 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003102
3103 Intent newIntent = new Intent();
3104 if (requestCode >= 0) {
3105 // Caller is requesting a result.
3106 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3107 }
3108 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3109 new IntentSender(target));
3110 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3111 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3112 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3113 hist.packageName);
3114 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3115 hist.task.taskId);
3116 }
3117 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3118 aInfo.packageName);
3119 newIntent.setFlags(intent.getFlags());
3120 newIntent.setClassName("android",
3121 HeavyWeightSwitcherActivity.class.getName());
3122 intent = newIntent;
3123 resolvedType = null;
3124 caller = null;
3125 callingUid = Binder.getCallingUid();
3126 callingPid = Binder.getCallingPid();
3127 componentSpecified = true;
3128 try {
3129 ResolveInfo rInfo =
3130 AppGlobals.getPackageManager().resolveIntent(
3131 intent, null,
3132 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003133 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003134 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003135 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003136 } catch (RemoteException e) {
3137 aInfo = null;
3138 }
3139 }
3140 }
3141 }
3142
3143 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003144 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3145 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003146
3147 if (mConfigWillChange && mMainStack) {
3148 // If the caller also wants to switch to a new configuration,
3149 // do so now. This allows a clean switch, as we are waiting
3150 // for the current activity to pause (so we will not destroy
3151 // it), and have not yet started the next activity.
3152 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3153 "updateConfiguration()");
3154 mConfigWillChange = false;
3155 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3156 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003157 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158 }
3159
3160 Binder.restoreCallingIdentity(origId);
3161
3162 if (outResult != null) {
3163 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003164 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003165 mWaitingActivityLaunched.add(outResult);
3166 do {
3167 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003168 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003169 } catch (InterruptedException e) {
3170 }
3171 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003172 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003173 ActivityRecord r = this.topRunningActivityLocked(null);
3174 if (r.nowVisible) {
3175 outResult.timeout = false;
3176 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3177 outResult.totalTime = 0;
3178 outResult.thisTime = 0;
3179 } else {
3180 outResult.thisTime = SystemClock.uptimeMillis();
3181 mWaitingActivityVisible.add(outResult);
3182 do {
3183 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003184 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003185 } catch (InterruptedException e) {
3186 }
3187 } while (!outResult.timeout && outResult.who == null);
3188 }
3189 }
3190 }
3191
3192 return res;
3193 }
3194 }
3195
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003196 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003197 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3198 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003199 if (intents == null) {
3200 throw new NullPointerException("intents is null");
3201 }
3202 if (resolvedTypes == null) {
3203 throw new NullPointerException("resolvedTypes is null");
3204 }
3205 if (intents.length != resolvedTypes.length) {
3206 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3207 }
3208
3209 ActivityRecord[] outActivity = new ActivityRecord[1];
3210
3211 int callingPid;
3212 if (callingUid >= 0) {
3213 callingPid = -1;
3214 } else if (caller == null) {
3215 callingPid = Binder.getCallingPid();
3216 callingUid = Binder.getCallingUid();
3217 } else {
3218 callingPid = callingUid = -1;
3219 }
3220 final long origId = Binder.clearCallingIdentity();
3221 try {
3222 synchronized (mService) {
3223
3224 for (int i=0; i<intents.length; i++) {
3225 Intent intent = intents[i];
3226 if (intent == null) {
3227 continue;
3228 }
3229
3230 // Refuse possible leaked file descriptors
3231 if (intent != null && intent.hasFileDescriptors()) {
3232 throw new IllegalArgumentException("File descriptors passed in Intent");
3233 }
3234
3235 boolean componentSpecified = intent.getComponent() != null;
3236
3237 // Don't modify the client's object!
3238 intent = new Intent(intent);
3239
3240 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003241 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003242 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003243 // TODO: New, check if this is correct
3244 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003245
3246 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3247 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3248 throw new IllegalArgumentException(
3249 "FLAG_CANT_SAVE_STATE not supported here");
3250 }
3251
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003252 Bundle theseOptions;
3253 if (options != null && i == intents.length-1) {
3254 theseOptions = options;
3255 } else {
3256 theseOptions = null;
3257 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003258 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003259 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003260 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003261 if (res < 0) {
3262 return res;
3263 }
3264
Dianne Hackbornbe707852011-11-11 14:32:10 -08003265 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003266 }
3267 }
3268 } finally {
3269 Binder.restoreCallingIdentity(origId);
3270 }
3271
Dianne Hackborna4972e92012-03-14 10:38:05 -07003272 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003273 }
3274
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003275 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3276 long thisTime, long totalTime) {
3277 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3278 WaitResult w = mWaitingActivityLaunched.get(i);
3279 w.timeout = timeout;
3280 if (r != null) {
3281 w.who = new ComponentName(r.info.packageName, r.info.name);
3282 }
3283 w.thisTime = thisTime;
3284 w.totalTime = totalTime;
3285 }
3286 mService.notifyAll();
3287 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003288
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003289 void reportActivityVisibleLocked(ActivityRecord r) {
3290 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3291 WaitResult w = mWaitingActivityVisible.get(i);
3292 w.timeout = false;
3293 if (r != null) {
3294 w.who = new ComponentName(r.info.packageName, r.info.name);
3295 }
3296 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3297 w.thisTime = w.totalTime;
3298 }
3299 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003300
3301 if (mDismissKeyguardOnNextActivity) {
3302 mDismissKeyguardOnNextActivity = false;
3303 mService.mWindowManager.dismissKeyguard();
3304 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003305 }
3306
3307 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3308 String resultWho, int requestCode, int resultCode, Intent data) {
3309
3310 if (callingUid > 0) {
3311 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003312 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003313 }
3314
3315 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3316 + " : who=" + resultWho + " req=" + requestCode
3317 + " res=" + resultCode + " data=" + data);
3318 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3319 try {
3320 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3321 list.add(new ResultInfo(resultWho, requestCode,
3322 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003323 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003324 return;
3325 } catch (Exception e) {
3326 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3327 }
3328 }
3329
3330 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3331 }
3332
3333 private final void stopActivityLocked(ActivityRecord r) {
3334 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3335 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3336 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3337 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003338 if (!mService.mSleeping) {
3339 if (DEBUG_STATES) {
3340 Slog.d(TAG, "no-history finish of " + r);
3341 }
3342 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003343 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003344 } else {
3345 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3346 + " on stop because we're just sleeping");
3347 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003348 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003349 }
3350
3351 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003352 if (mMainStack) {
3353 if (mService.mFocusedActivity == r) {
3354 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3355 }
3356 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003357 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003358 try {
3359 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003360 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3361 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003362 r.state = ActivityState.STOPPING;
3363 if (DEBUG_VISBILITY) Slog.v(
3364 TAG, "Stopping visible=" + r.visible + " for " + r);
3365 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003366 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003367 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003368 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003369 if (mService.isSleeping()) {
3370 r.setSleeping(true);
3371 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003372 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3373 msg.obj = r;
3374 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003375 } catch (Exception e) {
3376 // Maybe just ignore exceptions here... if the process
3377 // has crashed, our death notification will clean things
3378 // up.
3379 Slog.w(TAG, "Exception thrown during pause", e);
3380 // Just in case, assume it to be stopped.
3381 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003382 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003383 r.state = ActivityState.STOPPED;
3384 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003385 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003386 }
3387 }
3388 }
3389 }
3390
3391 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3392 boolean remove) {
3393 int N = mStoppingActivities.size();
3394 if (N <= 0) return null;
3395
3396 ArrayList<ActivityRecord> stops = null;
3397
3398 final boolean nowVisible = mResumedActivity != null
3399 && mResumedActivity.nowVisible
3400 && !mResumedActivity.waitingVisible;
3401 for (int i=0; i<N; i++) {
3402 ActivityRecord s = mStoppingActivities.get(i);
3403 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3404 + nowVisible + " waitingVisible=" + s.waitingVisible
3405 + " finishing=" + s.finishing);
3406 if (s.waitingVisible && nowVisible) {
3407 mWaitingVisibleActivities.remove(s);
3408 s.waitingVisible = false;
3409 if (s.finishing) {
3410 // If this activity is finishing, it is sitting on top of
3411 // everyone else but we now know it is no longer needed...
3412 // so get rid of it. Otherwise, we need to go through the
3413 // normal flow and hide it once we determine that it is
3414 // hidden by the activities in front of it.
3415 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003416 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003417 }
3418 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003419 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003420 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3421 if (stops == null) {
3422 stops = new ArrayList<ActivityRecord>();
3423 }
3424 stops.add(s);
3425 mStoppingActivities.remove(i);
3426 N--;
3427 i--;
3428 }
3429 }
3430
3431 return stops;
3432 }
3433
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003434 final void scheduleIdleLocked() {
3435 Message msg = Message.obtain();
3436 msg.what = IDLE_NOW_MSG;
3437 mHandler.sendMessage(msg);
3438 }
3439
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003440 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003441 Configuration config) {
3442 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3443
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003444 ActivityRecord res = null;
3445
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003446 ArrayList<ActivityRecord> stops = null;
3447 ArrayList<ActivityRecord> finishes = null;
3448 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003449 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003450 int NS = 0;
3451 int NF = 0;
3452 int NT = 0;
3453 IApplicationThread sendThumbnail = null;
3454 boolean booting = false;
3455 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003456 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003457
3458 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003459 ActivityRecord r = ActivityRecord.forToken(token);
3460 if (r != null) {
3461 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003462 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003463 }
3464
3465 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003466 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003467 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003468 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003469
3470 if (fromTimeout) {
3471 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3472 }
3473
3474 // This is a hack to semi-deal with a race condition
3475 // in the client where it can be constructed with a
3476 // newer configuration from when we asked it to launch.
3477 // We'll update with whatever configuration it now says
3478 // it used to launch.
3479 if (config != null) {
3480 r.configuration = config;
3481 }
3482
3483 // No longer need to keep the device awake.
3484 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3485 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3486 mLaunchingActivity.release();
3487 }
3488
3489 // We are now idle. If someone is waiting for a thumbnail from
3490 // us, we can now deliver.
3491 r.idle = true;
3492 mService.scheduleAppGcsLocked();
3493 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3494 sendThumbnail = r.app.thread;
3495 r.thumbnailNeeded = false;
3496 }
3497
3498 // If this activity is fullscreen, set up to hide those under it.
3499
3500 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3501 ensureActivitiesVisibleLocked(null, 0);
3502
3503 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3504 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003505 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003506 mService.mBooted = true;
3507 enableScreen = true;
3508 }
3509 }
3510
3511 } else if (fromTimeout) {
3512 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3513 }
3514
3515 // Atomically retrieve all of the other things to do.
3516 stops = processStoppingActivitiesLocked(true);
3517 NS = stops != null ? stops.size() : 0;
3518 if ((NF=mFinishingActivities.size()) > 0) {
3519 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3520 mFinishingActivities.clear();
3521 }
3522 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3523 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3524 mService.mCancelledThumbnails.clear();
3525 }
3526
3527 if (mMainStack) {
3528 booting = mService.mBooting;
3529 mService.mBooting = false;
3530 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003531 if (mStartingUsers.size() > 0) {
3532 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3533 mStartingUsers.clear();
3534 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003535 }
3536
3537 int i;
3538
3539 // Send thumbnail if requested.
3540 if (sendThumbnail != null) {
3541 try {
3542 sendThumbnail.requestThumbnail(token);
3543 } catch (Exception e) {
3544 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3545 mService.sendPendingThumbnail(null, token, null, null, true);
3546 }
3547 }
3548
3549 // Stop any activities that are scheduled to do so but have been
3550 // waiting for the next one to start.
3551 for (i=0; i<NS; i++) {
3552 ActivityRecord r = (ActivityRecord)stops.get(i);
3553 synchronized (mService) {
3554 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003555 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003556 } else {
3557 stopActivityLocked(r);
3558 }
3559 }
3560 }
3561
3562 // Finish any activities that are scheduled to do so but have been
3563 // waiting for the next one to start.
3564 for (i=0; i<NF; i++) {
3565 ActivityRecord r = (ActivityRecord)finishes.get(i);
3566 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003567 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003568 }
3569 }
3570
3571 // Report back to any thumbnail receivers.
3572 for (i=0; i<NT; i++) {
3573 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3574 mService.sendPendingThumbnail(r, null, null, null, true);
3575 }
3576
3577 if (booting) {
3578 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003579 } else if (startingUsers != null) {
3580 for (i=0; i<startingUsers.size(); i++) {
3581 mService.finishUserSwitch(startingUsers.get(i));
3582 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003583 }
3584
3585 mService.trimApplications();
3586 //dump();
3587 //mWindowManager.dump();
3588
3589 if (enableScreen) {
3590 mService.enableScreenAfterBoot();
3591 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003592
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003593 if (activityRemoved) {
3594 resumeTopActivityLocked(null);
3595 }
3596
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003597 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003598 }
3599
3600 /**
3601 * @return Returns true if the activity is being finished, false if for
3602 * some reason it is being left as-is.
3603 */
3604 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003605 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003606 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003607 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003608 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003609 + ", result=" + resultCode + ", data=" + resultData
3610 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003611 if (index < 0) {
3612 return false;
3613 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003614 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003615
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003616 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003617 return true;
3618 }
3619
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003620 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3621 ActivityRecord self = isInStackLocked(token);
3622 if (self == null) {
3623 return;
3624 }
3625
3626 int i;
3627 for (i=mHistory.size()-1; i>=0; i--) {
3628 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3629 if (r.resultTo == self && r.requestCode == requestCode) {
3630 if ((r.resultWho == null && resultWho == null) ||
3631 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3632 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003633 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003634 }
3635 }
3636 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003637 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003638 }
3639
3640 final boolean finishActivityAffinityLocked(IBinder token) {
3641 int index = indexOfTokenLocked(token);
3642 if (DEBUG_RESULTS) Slog.v(
3643 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3644 if (index < 0) {
3645 return false;
3646 }
3647 ActivityRecord r = mHistory.get(index);
3648
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003649 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003650 ActivityRecord cur = mHistory.get(index);
3651 if (cur.task != r.task) {
3652 break;
3653 }
3654 if (cur.taskAffinity == null && r.taskAffinity != null) {
3655 break;
3656 }
3657 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3658 break;
3659 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003660 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3661 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003662 index--;
3663 }
3664 return true;
3665 }
3666
Dianne Hackborn5c607432012-02-28 14:44:19 -08003667 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3668 // send the result
3669 ActivityRecord resultTo = r.resultTo;
3670 if (resultTo != null) {
3671 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3672 + " who=" + r.resultWho + " req=" + r.requestCode
3673 + " res=" + resultCode + " data=" + resultData);
3674 if (r.info.applicationInfo.uid > 0) {
3675 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3676 resultTo.packageName, resultData,
3677 resultTo.getUriPermissionsLocked());
3678 }
3679 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3680 resultData);
3681 r.resultTo = null;
3682 }
3683 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3684
3685 // Make sure this HistoryRecord is not holding on to other resources,
3686 // because clients have remote IPC references to this object so we
3687 // can't assume that will go away and want to avoid circular IPC refs.
3688 r.results = null;
3689 r.pendingResults = null;
3690 r.newIntents = null;
3691 r.icicle = null;
3692 }
3693
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003694 /**
3695 * @return Returns true if this activity has been removed from the history
3696 * list, or false if it is still in the list and will be removed later.
3697 */
3698 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003699 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3700 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003701 }
3702
3703 /**
3704 * @return Returns true if this activity has been removed from the history
3705 * list, or false if it is still in the list and will be removed later.
3706 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003707 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3708 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003709 if (r.finishing) {
3710 Slog.w(TAG, "Duplicate finish request for " + r);
3711 return false;
3712 }
3713
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003714 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003715 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003716 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003717 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003718 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003719 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003720 if (next.task == r.task) {
3721 if (r.frontOfTask) {
3722 // The next activity is now the front of the task.
3723 next.frontOfTask = true;
3724 }
3725 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3726 // If the caller asked that this activity (and all above it)
3727 // be cleared when the task is reset, don't lose that information,
3728 // but propagate it up to the next activity.
3729 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3730 }
3731 }
3732 }
3733
3734 r.pauseKeyDispatchingLocked();
3735 if (mMainStack) {
3736 if (mService.mFocusedActivity == r) {
3737 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3738 }
3739 }
3740
Dianne Hackborn5c607432012-02-28 14:44:19 -08003741 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003742
3743 if (mService.mPendingThumbnails.size() > 0) {
3744 // There are clients waiting to receive thumbnails so, in case
3745 // this is an activity that someone is waiting for, add it
3746 // to the pending list so we can correctly update the clients.
3747 mService.mCancelledThumbnails.add(r);
3748 }
3749
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003750 if (immediate) {
3751 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003752 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003753 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003754 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003755 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003756 if (DEBUG_TRANSITION) Slog.v(TAG,
3757 "Prepare close transition: finishing " + r);
3758 mService.mWindowManager.prepareAppTransition(endTask
3759 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003760 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003761
3762 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003763 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003764
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003765 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003766 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3767 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3768 startPausingLocked(false, false);
3769 }
3770
3771 } else if (r.state != ActivityState.PAUSING) {
3772 // If the activity is PAUSING, we will complete the finish once
3773 // it is done pausing; else we can just directly finish it here.
3774 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3775 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003776 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003777 } else {
3778 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3779 }
3780
3781 return false;
3782 }
3783
3784 private static final int FINISH_IMMEDIATELY = 0;
3785 private static final int FINISH_AFTER_PAUSE = 1;
3786 private static final int FINISH_AFTER_VISIBLE = 2;
3787
3788 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003789 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003790 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003791 if (index < 0) {
3792 return null;
3793 }
3794
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003795 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003796 }
3797
3798 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003799 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003800 // First things first: if this activity is currently visible,
3801 // and the resumed activity is not yet visible, then hold off on
3802 // finishing until the resumed one becomes visible.
3803 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3804 if (!mStoppingActivities.contains(r)) {
3805 mStoppingActivities.add(r);
3806 if (mStoppingActivities.size() > 3) {
3807 // If we already have a few activities waiting to stop,
3808 // then give up on things going idle and start clearing
3809 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003810 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003811 } else {
3812 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003813 }
3814 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003815 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3816 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003817 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003818 if (oomAdj) {
3819 mService.updateOomAdjLocked();
3820 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003821 return r;
3822 }
3823
3824 // make sure the record is cleaned out of other places.
3825 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003826 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003827 mWaitingVisibleActivities.remove(r);
3828 if (mResumedActivity == r) {
3829 mResumedActivity = null;
3830 }
3831 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003832 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003833 r.state = ActivityState.FINISHING;
3834
3835 if (mode == FINISH_IMMEDIATELY
3836 || prevState == ActivityState.STOPPED
3837 || prevState == ActivityState.INITIALIZING) {
3838 // If this activity is already stopped, we can just finish
3839 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003840 boolean activityRemoved = destroyActivityLocked(r, true,
3841 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003842 if (activityRemoved) {
3843 resumeTopActivityLocked(null);
3844 }
3845 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003846 } else {
3847 // Need to go through the full pause cycle to get this
3848 // activity into the stopped state and then finish it.
3849 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3850 mFinishingActivities.add(r);
3851 resumeTopActivityLocked(null);
3852 }
3853 return r;
3854 }
3855
3856 /**
3857 * Perform the common clean-up of an activity record. This is called both
3858 * as part of destroyActivityLocked() (when destroying the client-side
3859 * representation) and cleaning things up as a result of its hosting
3860 * processing going away, in which case there is no remaining client-side
3861 * state to destroy so only the cleanup here is needed.
3862 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003863 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3864 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003865 if (mResumedActivity == r) {
3866 mResumedActivity = null;
3867 }
3868 if (mService.mFocusedActivity == r) {
3869 mService.mFocusedActivity = null;
3870 }
3871
3872 r.configDestroy = false;
3873 r.frozenBeforeDestroy = false;
3874
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003875 if (setState) {
3876 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3877 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003878 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003879 }
3880
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003881 // Make sure this record is no longer in the pending finishes list.
3882 // This could happen, for example, if we are trimming activities
3883 // down to the max limit while they are still waiting to finish.
3884 mFinishingActivities.remove(r);
3885 mWaitingVisibleActivities.remove(r);
3886
3887 // Remove any pending results.
3888 if (r.finishing && r.pendingResults != null) {
3889 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3890 PendingIntentRecord rec = apr.get();
3891 if (rec != null) {
3892 mService.cancelIntentSenderLocked(rec, false);
3893 }
3894 }
3895 r.pendingResults = null;
3896 }
3897
3898 if (cleanServices) {
3899 cleanUpActivityServicesLocked(r);
3900 }
3901
3902 if (mService.mPendingThumbnails.size() > 0) {
3903 // There are clients waiting to receive thumbnails so, in case
3904 // this is an activity that someone is waiting for, add it
3905 // to the pending list so we can correctly update the clients.
3906 mService.mCancelledThumbnails.add(r);
3907 }
3908
3909 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003910 removeTimeoutsForActivityLocked(r);
3911 }
3912
3913 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003914 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003915 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003916 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003917 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003918 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003919 }
3920
Dianne Hackborn5c607432012-02-28 14:44:19 -08003921 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003922 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
3923 r.makeFinishing();
3924 if (DEBUG_ADD_REMOVE) {
3925 RuntimeException here = new RuntimeException("here");
3926 here.fillInStackTrace();
3927 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003928 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003929 mHistory.remove(r);
3930 r.takeFromHistory();
3931 removeTimeoutsForActivityLocked(r);
3932 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3933 + " (removed from history)");
3934 r.state = ActivityState.DESTROYED;
3935 r.app = null;
3936 mService.mWindowManager.removeAppToken(r.appToken);
3937 if (VALIDATE_TOKENS) {
3938 validateAppTokensLocked();
3939 }
3940 cleanUpActivityServicesLocked(r);
3941 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003942 }
3943
3944 /**
3945 * Perform clean-up of service connections in an activity record.
3946 */
3947 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3948 // Throw away any services that have been bound by this activity.
3949 if (r.connections != null) {
3950 Iterator<ConnectionRecord> it = r.connections.iterator();
3951 while (it.hasNext()) {
3952 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003953 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003954 }
3955 r.connections = null;
3956 }
3957 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003958
3959 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
3960 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3961 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
3962 mHandler.sendMessage(msg);
3963 }
3964
Dianne Hackborn28695e02011-11-02 21:59:51 -07003965 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003966 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003967 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003968 for (int i=mHistory.size()-1; i>=0; i--) {
3969 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003970 if (r.finishing) {
3971 continue;
3972 }
3973 if (r.fullscreen) {
3974 lastIsOpaque = true;
3975 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003976 if (owner != null && r.app != owner) {
3977 continue;
3978 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003979 if (!lastIsOpaque) {
3980 continue;
3981 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003982 // We can destroy this one if we have its icicle saved and
3983 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003984 if (r.app != null && r != mResumedActivity && r != mPausingActivity
3985 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003986 && r.state != ActivityState.DESTROYING
3987 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003988 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3989 + " resumed=" + mResumedActivity
3990 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003991 if (destroyActivityLocked(r, true, oomAdj, reason)) {
3992 activityRemoved = true;
3993 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003994 }
3995 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003996 if (activityRemoved) {
3997 resumeTopActivityLocked(null);
3998 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003999 }
4000
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004001 /**
4002 * Destroy the current CLIENT SIDE instance of an activity. This may be
4003 * called both when actually finishing an activity, or when performing
4004 * a configuration switch where we destroy the current client-side object
4005 * but then create a new client-side object for this same HistoryRecord.
4006 */
4007 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004008 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004009 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004010 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004011 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4012 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004013 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004014 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004015
4016 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004017
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004018 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004019
4020 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004021
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004022 if (hadApp) {
4023 if (removeFromApp) {
4024 int idx = r.app.activities.indexOf(r);
4025 if (idx >= 0) {
4026 r.app.activities.remove(idx);
4027 }
4028 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4029 mService.mHeavyWeightProcess = null;
4030 mService.mHandler.sendEmptyMessage(
4031 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4032 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004033 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004034 // No longer have activities, so update oom adj.
4035 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004036 }
4037 }
4038
4039 boolean skipDestroy = false;
4040
4041 try {
4042 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004043 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004044 r.configChangeFlags);
4045 } catch (Exception e) {
4046 // We can just ignore exceptions here... if the process
4047 // has crashed, our death notification will clean things
4048 // up.
4049 //Slog.w(TAG, "Exception thrown during finish", e);
4050 if (r.finishing) {
4051 removeActivityFromHistoryLocked(r);
4052 removedFromHistory = true;
4053 skipDestroy = true;
4054 }
4055 }
4056
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004057 r.nowVisible = false;
4058
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004059 // If the activity is finishing, we need to wait on removing it
4060 // from the list to give it a chance to do its cleanup. During
4061 // that time it may make calls back with its token so we need to
4062 // be able to find it on the list and so we don't want to remove
4063 // it from the list yet. Otherwise, we can just immediately put
4064 // it in the destroyed state since we are not removing it from the
4065 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004066 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004067 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4068 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004069 r.state = ActivityState.DESTROYING;
4070 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4071 msg.obj = r;
4072 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4073 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004074 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4075 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004076 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004077 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004078 }
4079 } else {
4080 // remove this record from the history.
4081 if (r.finishing) {
4082 removeActivityFromHistoryLocked(r);
4083 removedFromHistory = true;
4084 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004085 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4086 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004087 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004088 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004089 }
4090 }
4091
4092 r.configChangeFlags = 0;
4093
4094 if (!mLRUActivities.remove(r) && hadApp) {
4095 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4096 }
4097
4098 return removedFromHistory;
4099 }
4100
4101 final void activityDestroyed(IBinder token) {
4102 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004103 final long origId = Binder.clearCallingIdentity();
4104 try {
4105 ActivityRecord r = ActivityRecord.forToken(token);
4106 if (r != null) {
4107 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004108 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004109
4110 int index = indexOfActivityLocked(r);
4111 if (index >= 0) {
4112 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004113 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004114 removeActivityFromHistoryLocked(r);
4115 }
4116 }
4117 resumeTopActivityLocked(null);
4118 } finally {
4119 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004120 }
4121 }
4122 }
4123
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004124 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app,
4125 String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004126 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004127 if (DEBUG_CLEANUP) Slog.v(
4128 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004129 + " with " + i + " entries");
4130 while (i > 0) {
4131 i--;
4132 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004133 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004134 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004135 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004136 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004137 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004138 }
4139 }
4140 }
4141
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004142 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4143 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4144 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4145 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4146 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4147 "mWaitingVisibleActivities");
4148 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4149
4150 boolean hasVisibleActivities = false;
4151
4152 // Clean out the history list.
4153 int i = mHistory.size();
4154 if (DEBUG_CLEANUP) Slog.v(
4155 TAG, "Removing app " + app + " from history with " + i + " entries");
4156 while (i > 0) {
4157 i--;
4158 ActivityRecord r = (ActivityRecord)mHistory.get(i);
4159 if (DEBUG_CLEANUP) Slog.v(
4160 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4161 if (r.app == app) {
4162 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4163 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4164 RuntimeException here = new RuntimeException("here");
4165 here.fillInStackTrace();
4166 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4167 + ": haveState=" + r.haveState
4168 + " stateNotNeeded=" + r.stateNotNeeded
4169 + " finishing=" + r.finishing
4170 + " state=" + r.state, here);
4171 }
4172 if (!r.finishing) {
4173 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4174 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4175 r.userId, System.identityHashCode(r),
4176 r.task.taskId, r.shortComponentName,
4177 "proc died without state saved");
4178 }
4179 removeActivityFromHistoryLocked(r);
4180
4181 } else {
4182 // We have the current state for this activity, so
4183 // it can be restarted later when needed.
4184 if (localLOGV) Slog.v(
4185 TAG, "Keeping entry, setting app to null");
4186 if (r.visible) {
4187 hasVisibleActivities = true;
4188 }
4189 r.app = null;
4190 r.nowVisible = false;
4191 if (!r.haveState) {
4192 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4193 "App died, clearing saved state of " + r);
4194 r.icicle = null;
4195 }
4196 }
4197
4198 r.stack.cleanUpActivityLocked(r, true, true);
4199 }
4200 }
4201
4202 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004203 }
4204
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004205 /**
4206 * Move the current home activity's task (if one exists) to the front
4207 * of the stack.
4208 */
4209 final void moveHomeToFrontLocked() {
4210 TaskRecord homeTask = null;
4211 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004212 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004213 if (hr.isHomeActivity) {
4214 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004215 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004216 }
4217 }
4218 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004219 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004220 }
4221 }
4222
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004223 final void updateTransitLocked(int transit, Bundle options) {
4224 if (options != null) {
4225 ActivityRecord r = topRunningActivityLocked(null);
4226 if (r != null && r.state != ActivityState.RESUMED) {
4227 r.updateOptionsLocked(options);
4228 } else {
4229 ActivityOptions.abort(options);
4230 }
4231 }
4232 mService.mWindowManager.prepareAppTransition(transit, false);
4233 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004234
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004235 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004236 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4237
4238 final int task = tr.taskId;
4239 int top = mHistory.size()-1;
4240
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004241 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004242 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004243 if (reason != null &&
4244 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4245 ActivityOptions.abort(options);
4246 } else {
4247 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4248 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004249 return;
4250 }
4251
Dianne Hackbornbe707852011-11-11 14:32:10 -08004252 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004253
4254 // Applying the affinities may have removed entries from the history,
4255 // so get the size again.
4256 top = mHistory.size()-1;
4257 int pos = top;
4258
4259 // Shift all activities with this task up to the top
4260 // of the stack, keeping them in the same internal order.
4261 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004262 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004263 if (localLOGV) Slog.v(
4264 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004265 if (r.task.taskId == task) {
4266 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004267 if (DEBUG_ADD_REMOVE) {
4268 RuntimeException here = new RuntimeException("here");
4269 here.fillInStackTrace();
4270 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4271 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004272 mHistory.remove(pos);
4273 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004274 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004275 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004276 }
4277 pos--;
4278 }
4279
4280 if (DEBUG_TRANSITION) Slog.v(TAG,
4281 "Prepare to front transition: task=" + tr);
4282 if (reason != null &&
4283 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004284 mService.mWindowManager.prepareAppTransition(
4285 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004286 ActivityRecord r = topRunningActivityLocked(null);
4287 if (r != null) {
4288 mNoAnimActivities.add(r);
4289 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004290 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004291 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004292 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004293 }
4294
4295 mService.mWindowManager.moveAppTokensToTop(moved);
4296 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004297 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004298 }
4299
4300 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004301 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004302 }
4303
4304 private final void finishTaskMoveLocked(int task) {
4305 resumeTopActivityLocked(null);
4306 }
4307
4308 /**
4309 * Worker method for rearranging history stack. Implements the function of moving all
4310 * activities for a specific task (gathering them if disjoint) into a single group at the
4311 * bottom of the stack.
4312 *
4313 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4314 * to premeptively cancel the move.
4315 *
4316 * @param task The taskId to collect and move to the bottom.
4317 * @return Returns true if the move completed, false if not.
4318 */
4319 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4320 Slog.i(TAG, "moveTaskToBack: " + task);
4321
4322 // If we have a watcher, preflight the move before committing to it. First check
4323 // for *other* available tasks, but if none are available, then try again allowing the
4324 // current task to be selected.
4325 if (mMainStack && mService.mController != null) {
4326 ActivityRecord next = topRunningActivityLocked(null, task);
4327 if (next == null) {
4328 next = topRunningActivityLocked(null, 0);
4329 }
4330 if (next != null) {
4331 // ask watcher if this is allowed
4332 boolean moveOK = true;
4333 try {
4334 moveOK = mService.mController.activityResuming(next.packageName);
4335 } catch (RemoteException e) {
4336 mService.mController = null;
4337 }
4338 if (!moveOK) {
4339 return false;
4340 }
4341 }
4342 }
4343
Dianne Hackbornbe707852011-11-11 14:32:10 -08004344 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004345
4346 if (DEBUG_TRANSITION) Slog.v(TAG,
4347 "Prepare to back transition: task=" + task);
4348
4349 final int N = mHistory.size();
4350 int bottom = 0;
4351 int pos = 0;
4352
4353 // Shift all activities with this task down to the bottom
4354 // of the stack, keeping them in the same internal order.
4355 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004356 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004357 if (localLOGV) Slog.v(
4358 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4359 if (r.task.taskId == task) {
4360 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004361 if (DEBUG_ADD_REMOVE) {
4362 RuntimeException here = new RuntimeException("here");
4363 here.fillInStackTrace();
4364 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4365 + bottom, here);
4366 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004367 mHistory.remove(pos);
4368 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004369 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004370 bottom++;
4371 }
4372 pos++;
4373 }
4374
4375 if (reason != null &&
4376 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004377 mService.mWindowManager.prepareAppTransition(
4378 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004379 ActivityRecord r = topRunningActivityLocked(null);
4380 if (r != null) {
4381 mNoAnimActivities.add(r);
4382 }
4383 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004384 mService.mWindowManager.prepareAppTransition(
4385 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004386 }
4387 mService.mWindowManager.moveAppTokensToBottom(moved);
4388 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004389 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004390 }
4391
4392 finishTaskMoveLocked(task);
4393 return true;
4394 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004395
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004396 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4397 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4398 ActivityRecord resumed = mResumedActivity;
4399 if (resumed != null && resumed.thumbHolder == tr) {
4400 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004401 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004402 if (info.mainThumbnail == null) {
4403 info.mainThumbnail = tr.lastThumbnail;
4404 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004405 return info;
4406 }
4407
Dianne Hackborn15491c62012-09-19 10:59:14 -07004408 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4409 ActivityRecord resumed = mResumedActivity;
4410 if (resumed != null && resumed.task == tr) {
4411 // This task is the current resumed task, we just need to take
4412 // a screenshot of it and return that.
4413 return resumed.stack.screenshotActivities(resumed);
4414 }
4415 // Return the information about the task, to figure out the top
4416 // thumbnail to return.
4417 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4418 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004419 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004420 } else {
4421 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
4422 }
4423 }
4424
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004425 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4426 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004427 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4428 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004429 if (taskRequired) {
4430 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4431 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004432 return null;
4433 }
4434
4435 if (subTaskIndex < 0) {
4436 // Just remove the entire task.
4437 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4438 return info.root;
4439 }
4440
4441 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004442 if (taskRequired) {
4443 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4444 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004445 return null;
4446 }
4447
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004448 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004449 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4450 performClearTaskAtIndexLocked(taskId, subtask.index);
4451 return subtask.activity;
4452 }
4453
4454 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004455 final TaskAccessInfo thumbs = new TaskAccessInfo();
4456 // How many different sub-thumbnails?
4457 final int NA = mHistory.size();
4458 int j = 0;
4459 ThumbnailHolder holder = null;
4460 while (j < NA) {
4461 ActivityRecord ar = mHistory.get(j);
4462 if (!ar.finishing && ar.task.taskId == taskId) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004463 thumbs.root = ar;
4464 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004465 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004466 if (holder != null) {
4467 thumbs.mainThumbnail = holder.lastThumbnail;
4468 }
4469 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004470 break;
4471 }
4472 j++;
4473 }
4474
4475 if (j >= NA) {
4476 return thumbs;
4477 }
4478
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004479 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4480 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004481 while (j < NA) {
4482 ActivityRecord ar = mHistory.get(j);
4483 j++;
4484 if (ar.finishing) {
4485 continue;
4486 }
4487 if (ar.task.taskId != taskId) {
4488 break;
4489 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004490 if (ar.thumbHolder != holder && holder != null) {
4491 thumbs.numSubThumbbails++;
4492 holder = ar.thumbHolder;
4493 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004494 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004495 sub.activity = ar;
4496 sub.index = j-1;
4497 subtasks.add(sub);
4498 }
4499 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004500 if (thumbs.numSubThumbbails > 0) {
4501 thumbs.retriever = new IThumbnailRetriever.Stub() {
4502 public Bitmap getThumbnail(int index) {
4503 if (index < 0 || index >= thumbs.subtasks.size()) {
4504 return null;
4505 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004506 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4507 ActivityRecord resumed = mResumedActivity;
4508 if (resumed != null && resumed.thumbHolder == sub.holder) {
4509 return resumed.stack.screenshotActivities(resumed);
4510 }
4511 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004512 }
4513 };
4514 }
4515 return thumbs;
4516 }
4517
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004518 private final void logStartActivity(int tag, ActivityRecord r,
4519 TaskRecord task) {
4520 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004521 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004522 r.shortComponentName, r.intent.getAction(),
4523 r.intent.getType(), r.intent.getDataString(),
4524 r.intent.getFlags());
4525 }
4526
4527 /**
4528 * Make sure the given activity matches the current configuration. Returns
4529 * false if the activity had to be destroyed. Returns true if the
4530 * configuration is the same, or the activity will remain running as-is
4531 * for whatever reason. Ensures the HistoryRecord is updated with the
4532 * correct configuration and all other bookkeeping is handled.
4533 */
4534 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4535 int globalChanges) {
4536 if (mConfigWillChange) {
4537 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4538 "Skipping config check (will change): " + r);
4539 return true;
4540 }
4541
4542 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4543 "Ensuring correct configuration: " + r);
4544
4545 // Short circuit: if the two configurations are the exact same
4546 // object (the common case), then there is nothing to do.
4547 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004548 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004549 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4550 "Configuration unchanged in " + r);
4551 return true;
4552 }
4553
4554 // We don't worry about activities that are finishing.
4555 if (r.finishing) {
4556 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4557 "Configuration doesn't matter in finishing " + r);
4558 r.stopFreezingScreenLocked(false);
4559 return true;
4560 }
4561
4562 // Okay we now are going to make this activity have the new config.
4563 // But then we need to figure out how it needs to deal with that.
4564 Configuration oldConfig = r.configuration;
4565 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004566
4567 // Determine what has changed. May be nothing, if this is a config
4568 // that has come back from the app after going idle. In that case
4569 // we just want to leave the official config object now in the
4570 // activity and do nothing else.
4571 final int changes = oldConfig.diff(newConfig);
4572 if (changes == 0 && !r.forceNewConfig) {
4573 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4574 "Configuration no differences in " + r);
4575 return true;
4576 }
4577
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004578 // If the activity isn't currently running, just leave the new
4579 // configuration and it will pick that up next time it starts.
4580 if (r.app == null || r.app.thread == null) {
4581 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4582 "Configuration doesn't matter not running " + r);
4583 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004584 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004585 return true;
4586 }
4587
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004588 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004589 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4590 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4591 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004592 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004593 + ", newConfig=" + newConfig);
4594 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004595 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004596 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4597 r.configChangeFlags |= changes;
4598 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004599 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004600 if (r.app == null || r.app.thread == null) {
4601 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004602 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004603 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004604 } else if (r.state == ActivityState.PAUSING) {
4605 // A little annoying: we are waiting for this activity to
4606 // finish pausing. Let's not do anything now, but just
4607 // flag that it needs to be restarted when done pausing.
4608 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004609 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004610 r.configDestroy = true;
4611 return true;
4612 } else if (r.state == ActivityState.RESUMED) {
4613 // Try to optimize this case: the configuration is changing
4614 // and we need to restart the top, resumed activity.
4615 // Instead of doing the normal handshaking, just say
4616 // "restart!".
4617 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004618 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004619 relaunchActivityLocked(r, r.configChangeFlags, true);
4620 r.configChangeFlags = 0;
4621 } else {
4622 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004623 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004624 relaunchActivityLocked(r, r.configChangeFlags, false);
4625 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004626 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004627
4628 // All done... tell the caller we weren't able to keep this
4629 // activity around.
4630 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004631 }
4632
4633 // Default case: the activity can handle this new configuration, so
4634 // hand it over. Note that we don't need to give it the new
4635 // configuration, since we always send configuration changes to all
4636 // process when they happen so it can just use whatever configuration
4637 // it last got.
4638 if (r.app != null && r.app.thread != null) {
4639 try {
4640 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004641 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004642 } catch (RemoteException e) {
4643 // If process died, whatever.
4644 }
4645 }
4646 r.stopFreezingScreenLocked(false);
4647
4648 return true;
4649 }
4650
4651 private final boolean relaunchActivityLocked(ActivityRecord r,
4652 int changes, boolean andResume) {
4653 List<ResultInfo> results = null;
4654 List<Intent> newIntents = null;
4655 if (andResume) {
4656 results = r.results;
4657 newIntents = r.newIntents;
4658 }
4659 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4660 + " with results=" + results + " newIntents=" + newIntents
4661 + " andResume=" + andResume);
4662 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004663 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004664 r.task.taskId, r.shortComponentName);
4665
4666 r.startFreezingScreenLocked(r.app, 0);
4667
4668 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004669 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4670 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4671 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004672 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004673 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004674 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004675 // Note: don't need to call pauseIfSleepingLocked() here, because
4676 // the caller will only pass in 'andResume' if this activity is
4677 // currently resumed, which implies we aren't sleeping.
4678 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004679 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004680 }
4681
4682 if (andResume) {
4683 r.results = null;
4684 r.newIntents = null;
4685 if (mMainStack) {
4686 mService.reportResumedActivityLocked(r);
4687 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004688 r.state = ActivityState.RESUMED;
4689 } else {
4690 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4691 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004692 }
4693
4694 return true;
4695 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004696
4697 public void dismissKeyguardOnNextActivityLocked() {
4698 mDismissKeyguardOnNextActivity = true;
4699 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004700}