blob: a6dc867bc7cb33d0078d4431fd6d5eddcbcbf499 [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 }
423
424 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
425 int i = mHistory.size()-1;
426 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700427 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700428 if (!r.finishing && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700429 return r;
430 }
431 i--;
432 }
433 return null;
434 }
435
436 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
437 int i = mHistory.size()-1;
438 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700439 ActivityRecord r = mHistory.get(i);
Amith Yamasani259d5e52012-08-31 15:11:01 -0700440 if (!r.finishing && !r.delayedResume && r != notTop && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700441 return r;
442 }
443 i--;
444 }
445 return null;
446 }
447
448 /**
449 * This is a simplified version of topRunningActivityLocked that provides a number of
450 * optional skip-over modes. It is intended for use with the ActivityController hook only.
451 *
452 * @param token If non-null, any history records matching this token will be skipped.
453 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
454 *
455 * @return Returns the HistoryRecord of the next activity on the stack.
456 */
457 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
458 int i = mHistory.size()-1;
459 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700460 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700461 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700462 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
463 && r.userId == mCurrentUser) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700464 return r;
465 }
466 i--;
467 }
468 return null;
469 }
470
471 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800472 return mHistory.indexOf(ActivityRecord.forToken(token));
473 }
474
475 final int indexOfActivityLocked(ActivityRecord r) {
476 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700477 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700478
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700479 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800480 ActivityRecord r = ActivityRecord.forToken(token);
481 if (mHistory.contains(r)) {
482 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700483 }
484 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700485 }
486
487 private final boolean updateLRUListLocked(ActivityRecord r) {
488 final boolean hadit = mLRUActivities.remove(r);
489 mLRUActivities.add(r);
490 return hadit;
491 }
492
493 /**
494 * Returns the top activity in any existing task matching the given
495 * Intent. Returns null if no such task is found.
496 */
497 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
498 ComponentName cls = intent.getComponent();
499 if (info.targetActivity != null) {
500 cls = new ComponentName(info.packageName, info.targetActivity);
501 }
502
503 TaskRecord cp = null;
504
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700505 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700506 final int N = mHistory.size();
507 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700508 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700509 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700510 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
511 cp = r.task;
512 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
513 // + "/aff=" + r.task.affinity + " to new cls="
514 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
515 if (r.task.affinity != null) {
516 if (r.task.affinity.equals(info.taskAffinity)) {
517 //Slog.i(TAG, "Found matching affinity!");
518 return r;
519 }
520 } else if (r.task.intent != null
521 && r.task.intent.getComponent().equals(cls)) {
522 //Slog.i(TAG, "Found matching class!");
523 //dump();
524 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
525 return r;
526 } else if (r.task.affinityIntent != null
527 && r.task.affinityIntent.getComponent().equals(cls)) {
528 //Slog.i(TAG, "Found matching class!");
529 //dump();
530 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
531 return r;
532 }
533 }
534 }
535
536 return null;
537 }
538
539 /**
540 * Returns the first activity (starting from the top of the stack) that
541 * is the same as the given activity. Returns null if no such activity
542 * is found.
543 */
544 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
545 ComponentName cls = intent.getComponent();
546 if (info.targetActivity != null) {
547 cls = new ComponentName(info.packageName, info.targetActivity);
548 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700549 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700550
551 final int N = mHistory.size();
552 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700553 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700554 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700555 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700556 //Slog.i(TAG, "Found matching class!");
557 //dump();
558 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
559 return r;
560 }
561 }
562 }
563
564 return null;
565 }
566
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700567 final void showAskCompatModeDialogLocked(ActivityRecord r) {
568 Message msg = Message.obtain();
569 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
570 msg.obj = r.task.askedCompatMode ? null : r;
571 mService.mHandler.sendMessage(msg);
572 }
573
Amith Yamasani742a6712011-05-04 14:49:28 -0700574 /*
575 * Move the activities around in the stack to bring a user to the foreground.
576 * @return whether there are any activities for the specified user.
577 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700578 final boolean switchUserLocked(int userId, UserStartedState uss) {
579 mCurrentUser = userId;
580 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700581
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700582 // Only one activity? Nothing to do...
583 if (mHistory.size() < 2)
584 return false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700585
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700586 boolean haveActivities = false;
587 // Check if the top activity is from the new user.
588 ActivityRecord top = mHistory.get(mHistory.size() - 1);
589 if (top.userId == userId) return true;
590 // Otherwise, move the user's activities to the top.
591 int N = mHistory.size();
592 int i = 0;
593 while (i < N) {
594 ActivityRecord r = mHistory.get(i);
595 if (r.userId == userId) {
596 ActivityRecord moveToTop = mHistory.remove(i);
597 mHistory.add(moveToTop);
598 // No need to check the top one now
599 N--;
600 haveActivities = true;
601 } else {
602 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700603 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700604 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700605 // Transition from the old top to the new top
606 resumeTopActivityLocked(top);
607 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700608 }
609
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700610 final boolean realStartActivityLocked(ActivityRecord r,
611 ProcessRecord app, boolean andResume, boolean checkConfig)
612 throws RemoteException {
613
614 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800615 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700616
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700617 // schedule launch ticks to collect information about slow apps.
618 r.startLaunchTickingLocked();
619
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700620 // Have the window manager re-evaluate the orientation of
621 // the screen based on the new activity order. Note that
622 // as a result of this, it can call back into the activity
623 // manager with a new orientation. We don't care about that,
624 // because the activity is not currently running so we are
625 // just restarting it anyway.
626 if (checkConfig) {
627 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
628 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800629 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800630 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700631 }
632
633 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700634 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700635
636 if (localLOGV) Slog.v(TAG, "Launching: " + r);
637
638 int idx = app.activities.indexOf(r);
639 if (idx < 0) {
640 app.activities.add(r);
641 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700642 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700643
644 try {
645 if (app.thread == null) {
646 throw new RemoteException();
647 }
648 List<ResultInfo> results = null;
649 List<Intent> newIntents = null;
650 if (andResume) {
651 results = r.results;
652 newIntents = r.newIntents;
653 }
654 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
655 + " icicle=" + r.icicle
656 + " with results=" + results + " newIntents=" + newIntents
657 + " andResume=" + andResume);
658 if (andResume) {
659 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700660 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700661 r.task.taskId, r.shortComponentName);
662 }
663 if (r.isHomeActivity) {
664 mService.mHomeProcess = app;
665 }
666 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800667 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400668 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700669 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700670 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700671 String profileFile = null;
672 ParcelFileDescriptor profileFd = null;
673 boolean profileAutoStop = false;
674 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
675 if (mService.mProfileProc == null || mService.mProfileProc == app) {
676 mService.mProfileProc = app;
677 profileFile = mService.mProfileFile;
678 profileFd = mService.mProfileFd;
679 profileAutoStop = mService.mAutoStopProfiler;
680 }
681 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700682 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700683 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700684 if (profileFd != null) {
685 try {
686 profileFd = profileFd.dup();
687 } catch (IOException e) {
688 profileFd = null;
689 }
690 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800691 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800692 System.identityHashCode(r), r.info,
693 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700694 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700695 mService.isNextTransitionForward(), profileFile, profileFd,
696 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700697
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700698 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700699 // This may be a heavy-weight process! Note that the package
700 // manager will ensure that only activity can run in the main
701 // process of the .apk, which is the only thing that will be
702 // considered heavy-weight.
703 if (app.processName.equals(app.info.packageName)) {
704 if (mService.mHeavyWeightProcess != null
705 && mService.mHeavyWeightProcess != app) {
706 Log.w(TAG, "Starting new heavy weight process " + app
707 + " when already running "
708 + mService.mHeavyWeightProcess);
709 }
710 mService.mHeavyWeightProcess = app;
711 Message msg = mService.mHandler.obtainMessage(
712 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
713 msg.obj = r;
714 mService.mHandler.sendMessage(msg);
715 }
716 }
717
718 } catch (RemoteException e) {
719 if (r.launchFailed) {
720 // This is the second time we failed -- finish activity
721 // and give up.
722 Slog.e(TAG, "Second failure launching "
723 + r.intent.getComponent().flattenToShortString()
724 + ", giving up", e);
725 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800726 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700727 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700728 return false;
729 }
730
731 // This is the first time we failed -- restart process and
732 // retry.
733 app.activities.remove(r);
734 throw e;
735 }
736
737 r.launchFailed = false;
738 if (updateLRUListLocked(r)) {
739 Slog.w(TAG, "Activity " + r
740 + " being launched, but already in LRU list");
741 }
742
743 if (andResume) {
744 // As part of the process of launching, ActivityThread also performs
745 // a resume.
746 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700747 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
748 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700749 r.stopped = false;
750 mResumedActivity = r;
751 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800752 if (mMainStack) {
753 mService.addRecentTaskLocked(r.task);
754 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700755 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800756 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700757 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700758 } else {
759 // This activity is not starting in the resumed state... which
760 // should look like we asked it to pause+stop (but remain visible),
761 // and it has done so and reported back the current icicle and
762 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700763 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
764 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700765 r.state = ActivityState.STOPPED;
766 r.stopped = true;
767 }
768
769 // Launch the new version setup screen if needed. We do this -after-
770 // launching the initial activity (that is, home), so that it can have
771 // a chance to initialize itself while in the background, making the
772 // switch back to it faster and look better.
773 if (mMainStack) {
774 mService.startSetupActivityLocked();
775 }
776
777 return true;
778 }
779
780 private final void startSpecificActivityLocked(ActivityRecord r,
781 boolean andResume, boolean checkConfig) {
782 // Is this activity's application already running?
783 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
784 r.info.applicationInfo.uid);
785
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700786 if (r.launchTime == 0) {
787 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700788 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700789 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700790 }
791 } else if (mInitialStartTime == 0) {
792 mInitialStartTime = SystemClock.uptimeMillis();
793 }
794
795 if (app != null && app.thread != null) {
796 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700797 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700798 realStartActivityLocked(r, app, andResume, checkConfig);
799 return;
800 } catch (RemoteException e) {
801 Slog.w(TAG, "Exception when starting activity "
802 + r.intent.getComponent().flattenToShortString(), e);
803 }
804
805 // If a dead object exception was thrown -- fall through to
806 // restart the application.
807 }
808
809 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800810 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700811 }
812
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800813 void stopIfSleepingLocked() {
814 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700815 if (!mGoingToSleep.isHeld()) {
816 mGoingToSleep.acquire();
817 if (mLaunchingActivity.isHeld()) {
818 mLaunchingActivity.release();
819 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
820 }
821 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800822 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
823 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
824 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
825 checkReadyForSleepLocked();
826 }
827 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700828
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800829 void awakeFromSleepingLocked() {
830 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
831 mSleepTimeout = false;
832 if (mGoingToSleep.isHeld()) {
833 mGoingToSleep.release();
834 }
835 // Ensure activities are no longer sleeping.
836 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700837 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800838 r.setSleeping(false);
839 }
840 mGoingToSleepActivities.clear();
841 }
842
843 void activitySleptLocked(ActivityRecord r) {
844 mGoingToSleepActivities.remove(r);
845 checkReadyForSleepLocked();
846 }
847
848 void checkReadyForSleepLocked() {
849 if (!mService.isSleeping()) {
850 // Do not care.
851 return;
852 }
853
854 if (!mSleepTimeout) {
855 if (mResumedActivity != null) {
856 // Still have something resumed; can't sleep until it is paused.
857 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700858 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
859 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800860 return;
861 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800862 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800863 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800864 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800865 return;
866 }
867
868 if (mStoppingActivities.size() > 0) {
869 // Still need to tell some activities to stop; can't sleep yet.
870 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
871 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700872 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800873 return;
874 }
875
876 ensureActivitiesVisibleLocked(null, 0);
877
878 // Make sure any stopped but visible activities are now sleeping.
879 // This ensures that the activity's onStop() is called.
880 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700881 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800882 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
883 r.setSleeping(true);
884 }
885 }
886
887 if (mGoingToSleepActivities.size() > 0) {
888 // Still need to tell some activities to sleep; can't sleep yet.
889 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
890 + mGoingToSleepActivities.size() + " activities");
891 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700892 }
893 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800894
895 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
896
897 if (mGoingToSleep.isHeld()) {
898 mGoingToSleep.release();
899 }
900 if (mService.mShuttingDown) {
901 mService.notifyAll();
902 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700903 }
Craig Mautner59c00972012-07-30 12:10:24 -0700904
Dianne Hackbornd2835932010-12-13 16:28:46 -0800905 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800906 if (who.noDisplay) {
907 return null;
908 }
909
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800910 Resources res = mService.mContext.getResources();
911 int w = mThumbnailWidth;
912 int h = mThumbnailHeight;
913 if (w < 0) {
914 mThumbnailWidth = w =
915 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
916 mThumbnailHeight = h =
917 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
918 }
919
920 if (w > 0) {
Craig Mautner59c00972012-07-30 12:10:24 -0700921 return mService.mWindowManager.screenshotApplications(who.appToken,
922 Display.DEFAULT_DISPLAY, w, h);
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800923 }
924 return null;
925 }
926
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700927 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800928 if (mPausingActivity != null) {
929 RuntimeException e = new RuntimeException();
930 Slog.e(TAG, "Trying to pause when pause is already pending for "
931 + mPausingActivity, e);
932 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700933 ActivityRecord prev = mResumedActivity;
934 if (prev == null) {
935 RuntimeException e = new RuntimeException();
936 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
937 resumeTopActivityLocked(null);
938 return;
939 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700940 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
941 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700942 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800943 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700944 mLastPausedActivity = prev;
945 prev.state = ActivityState.PAUSING;
946 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700947 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700948
949 mService.updateCpuStats();
950
951 if (prev.app != null && prev.app.thread != null) {
952 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
953 try {
954 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700955 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700956 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800957 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
958 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700959 if (mMainStack) {
960 mService.updateUsageStats(prev, false);
961 }
962 } catch (Exception e) {
963 // Ignore exception, if process died other code will cleanup.
964 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800965 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700966 mLastPausedActivity = null;
967 }
968 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800969 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700970 mLastPausedActivity = null;
971 }
972
973 // If we are not going to sleep, we want to ensure the device is
974 // awake until the next activity is started.
975 if (!mService.mSleeping && !mService.mShuttingDown) {
976 mLaunchingActivity.acquire();
977 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
978 // To be safe, don't allow the wake lock to be held for too long.
979 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
980 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
981 }
982 }
983
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800984
985 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700986 // Have the window manager pause its key dispatching until the new
987 // activity has started. If we're pausing the activity just because
988 // the screen is being turned off and the UI is sleeping, don't interrupt
989 // key dispatch; the same activity will pick it up again on wakeup.
990 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800991 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700992 } else {
993 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
994 }
995
996 // Schedule a pause timeout in case the app doesn't respond.
997 // We don't give it much time because this directly impacts the
998 // responsiveness seen by the user.
999 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1000 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001001 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001002 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1003 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1004 } else {
1005 // This activity failed to schedule the
1006 // pause, so just treat it as being paused now.
1007 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001008 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001009 }
1010 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001011
1012 final void activityResumed(IBinder token) {
1013 ActivityRecord r = null;
1014
1015 synchronized (mService) {
1016 int index = indexOfTokenLocked(token);
1017 if (index >= 0) {
1018 r = mHistory.get(index);
1019 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1020 r.icicle = null;
1021 r.haveState = false;
1022 }
1023 }
1024 }
1025
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001026 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001027 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001028 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001029
1030 ActivityRecord r = null;
1031
1032 synchronized (mService) {
1033 int index = indexOfTokenLocked(token);
1034 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001035 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001036 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001037 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001038 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1039 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001040 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001041 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001042 } else {
1043 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001044 r.userId, System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001045 mPausingActivity != null
1046 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001047 }
1048 }
1049 }
1050 }
1051
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001052 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1053 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001054 if (r.state != ActivityState.STOPPING) {
1055 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1056 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1057 return;
1058 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001059 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001060 if (icicle != null) {
1061 // If icicle is null, this is happening due to a timeout, so we
1062 // haven't really saved the state.
1063 r.icicle = icicle;
1064 r.haveState = true;
1065 r.updateThumbnail(thumbnail, description);
1066 }
1067 if (!r.stopped) {
1068 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1069 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1070 r.stopped = true;
1071 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001072 if (r.finishing) {
1073 r.clearOptionsLocked();
1074 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001075 if (r.configDestroy) {
1076 destroyActivityLocked(r, true, false, "stop-config");
1077 resumeTopActivityLocked(null);
1078 } else {
1079 // Now that this process has stopped, we may want to consider
1080 // it to be the previous app to try to keep around in case
1081 // the user wants to return to it.
1082 ProcessRecord fgApp = null;
1083 if (mResumedActivity != null) {
1084 fgApp = mResumedActivity.app;
1085 } else if (mPausingActivity != null) {
1086 fgApp = mPausingActivity.app;
1087 }
1088 if (r.app != null && fgApp != null && r.app != fgApp
1089 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1090 && r.app != mService.mHomeProcess) {
1091 mService.mPreviousProcess = r.app;
1092 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1093 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001094 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001095 }
1096 }
1097 }
1098
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001099 private final void completePauseLocked() {
1100 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001101 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1102
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001103 if (prev != null) {
1104 if (prev.finishing) {
1105 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001106 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001107 } else if (prev.app != null) {
1108 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1109 if (prev.waitingVisible) {
1110 prev.waitingVisible = false;
1111 mWaitingVisibleActivities.remove(prev);
1112 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1113 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001114 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001115 if (prev.configDestroy) {
1116 // The previous is being paused because the configuration
1117 // is changing, which means it is actually stopping...
1118 // To juggle the fact that we are also starting a new
1119 // instance right now, we need to first completely stop
1120 // the current instance before starting the new one.
1121 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1122 destroyActivityLocked(prev, true, false, "pause-config");
1123 } else {
1124 mStoppingActivities.add(prev);
1125 if (mStoppingActivities.size() > 3) {
1126 // If we already have a few activities waiting to stop,
1127 // then give up on things going idle and start clearing
1128 // them out.
1129 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1130 scheduleIdleLocked();
1131 } else {
1132 checkReadyForSleepLocked();
1133 }
1134 }
1135 } else {
1136 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1137 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001138 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001139 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001140 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001141
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001142 if (!mService.isSleeping()) {
1143 resumeTopActivityLocked(prev);
1144 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001145 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001146 ActivityRecord top = topRunningActivityLocked(null);
1147 if (top == null || (prev != null && top != prev)) {
1148 // If there are no more activities available to run,
1149 // do resume anyway to start something. Also if the top
1150 // activity on the stack is not the just paused activity,
1151 // we need to go ahead and resume it to ensure we complete
1152 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001153 resumeTopActivityLocked(null);
1154 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001155 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001156
1157 if (prev != null) {
1158 prev.resumeKeyDispatchingLocked();
1159 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001160
1161 if (prev.app != null && prev.cpuTimeAtResume > 0
1162 && mService.mBatteryStatsService.isOnBattery()) {
1163 long diff = 0;
1164 synchronized (mService.mProcessStatsThread) {
1165 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1166 - prev.cpuTimeAtResume;
1167 }
1168 if (diff > 0) {
1169 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1170 synchronized (bsi) {
1171 BatteryStatsImpl.Uid.Proc ps =
1172 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1173 prev.info.packageName);
1174 if (ps != null) {
1175 ps.addForegroundTimeLocked(diff);
1176 }
1177 }
1178 }
1179 }
1180 prev.cpuTimeAtResume = 0; // reset it
1181 }
1182
1183 /**
1184 * Once we know that we have asked an application to put an activity in
1185 * the resumed state (either by launching it or explicitly telling it),
1186 * this function updates the rest of our state to match that fact.
1187 */
1188 private final void completeResumeLocked(ActivityRecord next) {
1189 next.idle = false;
1190 next.results = null;
1191 next.newIntents = null;
1192
1193 // schedule an idle timeout in case the app doesn't do it for us.
1194 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1195 msg.obj = next;
1196 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1197
1198 if (false) {
1199 // The activity was never told to pause, so just keep
1200 // things going as-is. To maintain our own state,
1201 // we need to emulate it coming back and saying it is
1202 // idle.
1203 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1204 msg.obj = next;
1205 mHandler.sendMessage(msg);
1206 }
1207
1208 if (mMainStack) {
1209 mService.reportResumedActivityLocked(next);
1210 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001211
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001212 if (mMainStack) {
1213 mService.setFocusedActivityLocked(next);
1214 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001215 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001216 ensureActivitiesVisibleLocked(null, 0);
1217 mService.mWindowManager.executeAppTransition();
1218 mNoAnimActivities.clear();
1219
1220 // Mark the point when the activity is resuming
1221 // TODO: To be more accurate, the mark should be before the onCreate,
1222 // not after the onResume. But for subsequent starts, onResume is fine.
1223 if (next.app != null) {
1224 synchronized (mService.mProcessStatsThread) {
1225 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1226 }
1227 } else {
1228 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1229 }
1230 }
1231
1232 /**
1233 * Make sure that all activities that need to be visible (that is, they
1234 * currently can be seen by the user) actually are.
1235 */
1236 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1237 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1238 if (DEBUG_VISBILITY) Slog.v(
1239 TAG, "ensureActivitiesVisible behind " + top
1240 + " configChanges=0x" + Integer.toHexString(configChanges));
1241
1242 // If the top activity is not fullscreen, then we need to
1243 // make sure any activities under it are now visible.
1244 final int count = mHistory.size();
1245 int i = count-1;
1246 while (mHistory.get(i) != top) {
1247 i--;
1248 }
1249 ActivityRecord r;
1250 boolean behindFullscreen = false;
1251 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001252 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001253 if (DEBUG_VISBILITY) Slog.v(
1254 TAG, "Make visible? " + r + " finishing=" + r.finishing
1255 + " state=" + r.state);
1256 if (r.finishing) {
1257 continue;
1258 }
1259
1260 final boolean doThisProcess = onlyThisProcess == null
1261 || onlyThisProcess.equals(r.processName);
1262
1263 // First: if this is not the current activity being started, make
1264 // sure it matches the current configuration.
1265 if (r != starting && doThisProcess) {
1266 ensureActivityConfigurationLocked(r, 0);
1267 }
1268
1269 if (r.app == null || r.app.thread == null) {
1270 if (onlyThisProcess == null
1271 || onlyThisProcess.equals(r.processName)) {
1272 // This activity needs to be visible, but isn't even
1273 // running... get it started, but don't resume it
1274 // at this point.
1275 if (DEBUG_VISBILITY) Slog.v(
1276 TAG, "Start and freeze screen for " + r);
1277 if (r != starting) {
1278 r.startFreezingScreenLocked(r.app, configChanges);
1279 }
1280 if (!r.visible) {
1281 if (DEBUG_VISBILITY) Slog.v(
1282 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001283 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001284 }
1285 if (r != starting) {
1286 startSpecificActivityLocked(r, false, false);
1287 }
1288 }
1289
1290 } else if (r.visible) {
1291 // If this activity is already visible, then there is nothing
1292 // else to do here.
1293 if (DEBUG_VISBILITY) Slog.v(
1294 TAG, "Skipping: already visible at " + r);
1295 r.stopFreezingScreenLocked(false);
1296
1297 } else if (onlyThisProcess == null) {
1298 // This activity is not currently visible, but is running.
1299 // Tell it to become visible.
1300 r.visible = true;
1301 if (r.state != ActivityState.RESUMED && r != starting) {
1302 // If this activity is paused, tell it
1303 // to now show its window.
1304 if (DEBUG_VISBILITY) Slog.v(
1305 TAG, "Making visible and scheduling visibility: " + r);
1306 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001307 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001308 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001309 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001310 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001311 r.stopFreezingScreenLocked(false);
1312 } catch (Exception e) {
1313 // Just skip on any failure; we'll make it
1314 // visible when it next restarts.
1315 Slog.w(TAG, "Exception thrown making visibile: "
1316 + r.intent.getComponent(), e);
1317 }
1318 }
1319 }
1320
1321 // Aggregate current change flags.
1322 configChanges |= r.configChangeFlags;
1323
1324 if (r.fullscreen) {
1325 // At this point, nothing else needs to be shown
1326 if (DEBUG_VISBILITY) Slog.v(
1327 TAG, "Stopping: fullscreen at " + r);
1328 behindFullscreen = true;
1329 i--;
1330 break;
1331 }
1332 }
1333
1334 // Now for any activities that aren't visible to the user, make
1335 // sure they no longer are keeping the screen frozen.
1336 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001337 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001338 if (DEBUG_VISBILITY) Slog.v(
1339 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1340 + " state=" + r.state
1341 + " behindFullscreen=" + behindFullscreen);
1342 if (!r.finishing) {
1343 if (behindFullscreen) {
1344 if (r.visible) {
1345 if (DEBUG_VISBILITY) Slog.v(
1346 TAG, "Making invisible: " + r);
1347 r.visible = false;
1348 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001349 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001350 if ((r.state == ActivityState.STOPPING
1351 || r.state == ActivityState.STOPPED)
1352 && r.app != null && r.app.thread != null) {
1353 if (DEBUG_VISBILITY) Slog.v(
1354 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001355 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001356 }
1357 } catch (Exception e) {
1358 // Just skip on any failure; we'll make it
1359 // visible when it next restarts.
1360 Slog.w(TAG, "Exception thrown making hidden: "
1361 + r.intent.getComponent(), e);
1362 }
1363 } else {
1364 if (DEBUG_VISBILITY) Slog.v(
1365 TAG, "Already invisible: " + r);
1366 }
1367 } else if (r.fullscreen) {
1368 if (DEBUG_VISBILITY) Slog.v(
1369 TAG, "Now behindFullscreen: " + r);
1370 behindFullscreen = true;
1371 }
1372 }
1373 i--;
1374 }
1375 }
1376
1377 /**
1378 * Version of ensureActivitiesVisible that can easily be called anywhere.
1379 */
1380 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1381 int configChanges) {
1382 ActivityRecord r = topRunningActivityLocked(null);
1383 if (r != null) {
1384 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1385 }
1386 }
1387
1388 /**
1389 * Ensure that the top activity in the stack is resumed.
1390 *
1391 * @param prev The previously resumed activity, for when in the process
1392 * of pausing; can be null to call from elsewhere.
1393 *
1394 * @return Returns true if something is being resumed, or false if
1395 * nothing happened.
1396 */
1397 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001398 return resumeTopActivityLocked(prev, null);
1399 }
1400
1401 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001402 // Find the first activity that is not finishing.
1403 ActivityRecord next = topRunningActivityLocked(null);
1404
1405 // Remember how we'll process this pause/resume situation, and ensure
1406 // that the state is reset however we wind up proceeding.
1407 final boolean userLeaving = mUserLeaving;
1408 mUserLeaving = false;
1409
1410 if (next == null) {
1411 // There are no more activities! Let's just start up the
1412 // Launcher...
1413 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001414 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001415 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001416 }
1417 }
1418
1419 next.delayedResume = false;
1420
1421 // If the top activity is the resumed one, nothing to do.
1422 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1423 // Make sure we have executed any pending transitions, since there
1424 // should be nothing left to do at this point.
1425 mService.mWindowManager.executeAppTransition();
1426 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001427 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001428 return false;
1429 }
1430
1431 // If we are sleeping, and there is no resumed activity, and the top
1432 // activity is paused, well that is the state we want.
1433 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001434 && mLastPausedActivity == next
1435 && (next.state == ActivityState.PAUSED
1436 || next.state == ActivityState.STOPPED
1437 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001438 // Make sure we have executed any pending transitions, since there
1439 // should be nothing left to do at this point.
1440 mService.mWindowManager.executeAppTransition();
1441 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001442 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001443 return false;
1444 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001445
1446 // Make sure that the user who owns this activity is started. If not,
1447 // we will just leave it as is because someone should be bringing
1448 // another user's activities to the top of the stack.
1449 if (mService.mStartedUsers.get(next.userId) == null) {
1450 Slog.w(TAG, "Skipping resume of top activity " + next
1451 + ": user " + next.userId + " is stopped");
1452 return false;
1453 }
1454
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001455 // The activity may be waiting for stop, but that is no longer
1456 // appropriate for it.
1457 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001458 mGoingToSleepActivities.remove(next);
1459 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001460 mWaitingVisibleActivities.remove(next);
1461
Dianne Hackborn84375872012-06-01 19:03:50 -07001462 next.updateOptionsLocked(options);
1463
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001464 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1465
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001466 // If we are currently pausing an activity, then don't do anything
1467 // until that is done.
1468 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001469 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1470 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001471 return false;
1472 }
1473
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001474 // Okay we are now going to start a switch, to 'next'. We may first
1475 // have to pause the current activity, but this is an important point
1476 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001477 // XXX "App Redirected" dialog is getting too many false positives
1478 // at this point, so turn off for now.
1479 if (false) {
1480 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1481 long now = SystemClock.uptimeMillis();
1482 final boolean inTime = mLastStartedActivity.startTime != 0
1483 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1484 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1485 final int nextUid = next.info.applicationInfo.uid;
1486 if (inTime && lastUid != nextUid
1487 && lastUid != next.launchedFromUid
1488 && mService.checkPermission(
1489 android.Manifest.permission.STOP_APP_SWITCHES,
1490 -1, next.launchedFromUid)
1491 != PackageManager.PERMISSION_GRANTED) {
1492 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1493 } else {
1494 next.startTime = now;
1495 mLastStartedActivity = next;
1496 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001497 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001498 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001499 mLastStartedActivity = next;
1500 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001501 }
1502
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001503 // We need to start pausing the current activity so the top one
1504 // can be resumed...
1505 if (mResumedActivity != null) {
1506 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001507 // At this point we want to put the upcoming activity's process
1508 // at the top of the LRU list, since we know we will be needing it
1509 // very soon and it would be a waste to let it get killed if it
1510 // happens to be sitting towards the end.
1511 if (next.app != null && next.app.thread != null) {
1512 // No reason to do full oom adj update here; we'll let that
1513 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001514 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001515 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001516 startPausingLocked(userLeaving, false);
1517 return true;
1518 }
1519
Christopher Tated3f175c2012-06-14 14:16:54 -07001520 // If the most recent activity was noHistory but was only stopped rather
1521 // than stopped+finished because the device went to sleep, we need to make
1522 // sure to finish it as we're making a new activity topmost.
1523 final ActivityRecord last = mLastPausedActivity;
1524 if (mService.mSleeping && last != null && !last.finishing) {
1525 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1526 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1527 if (DEBUG_STATES) {
1528 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1529 }
1530 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001531 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001532 }
1533 }
1534
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001535 if (prev != null && prev != next) {
1536 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1537 prev.waitingVisible = true;
1538 mWaitingVisibleActivities.add(prev);
1539 if (DEBUG_SWITCH) Slog.v(
1540 TAG, "Resuming top, waiting visible to hide: " + prev);
1541 } else {
1542 // The next activity is already visible, so hide the previous
1543 // activity's windows right now so we can show the new one ASAP.
1544 // We only do this if the previous is finishing, which should mean
1545 // it is on top of the one being resumed so hiding it quickly
1546 // is good. Otherwise, we want to do the normal route of allowing
1547 // the resumed activity to be shown so we can decide if the
1548 // previous should actually be hidden depending on whether the
1549 // new one is found to be full-screen or not.
1550 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001551 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001552 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1553 + prev + ", waitingVisible="
1554 + (prev != null ? prev.waitingVisible : null)
1555 + ", nowVisible=" + next.nowVisible);
1556 } else {
1557 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1558 + prev + ", waitingVisible="
1559 + (prev != null ? prev.waitingVisible : null)
1560 + ", nowVisible=" + next.nowVisible);
1561 }
1562 }
1563 }
1564
Dianne Hackborne7f97212011-02-24 14:40:20 -08001565 // Launching this app's activity, make sure the app is no longer
1566 // considered stopped.
1567 try {
1568 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001569 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001570 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001571 } catch (IllegalArgumentException e) {
1572 Slog.w(TAG, "Failed trying to unstop package "
1573 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001574 }
1575
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001576 // We are starting up the next activity, so tell the window manager
1577 // that the previous one will be hidden soon. This way it can know
1578 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001579 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001580 if (prev != null) {
1581 if (prev.finishing) {
1582 if (DEBUG_TRANSITION) Slog.v(TAG,
1583 "Prepare close transition: prev=" + prev);
1584 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001585 mService.mWindowManager.prepareAppTransition(
1586 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001587 } else {
1588 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1589 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001590 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001591 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001592 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1593 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001594 } else {
1595 if (DEBUG_TRANSITION) Slog.v(TAG,
1596 "Prepare open transition: prev=" + prev);
1597 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001598 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001599 mService.mWindowManager.prepareAppTransition(
1600 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001601 } else {
1602 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1603 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001604 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001605 }
1606 }
1607 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001608 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1609 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001610 }
1611 } else if (mHistory.size() > 1) {
1612 if (DEBUG_TRANSITION) Slog.v(TAG,
1613 "Prepare open transition: no previous");
1614 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001615 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001616 mService.mWindowManager.prepareAppTransition(
1617 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001618 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001619 mService.mWindowManager.prepareAppTransition(
1620 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001621 }
1622 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001623 if (!noAnim) {
1624 next.applyOptionsLocked();
1625 } else {
1626 next.clearOptionsLocked();
1627 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001628
1629 if (next.app != null && next.app.thread != null) {
1630 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1631
1632 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001633 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001634
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001635 // schedule launch ticks to collect information about slow apps.
1636 next.startLaunchTickingLocked();
1637
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001638 ActivityRecord lastResumedActivity = mResumedActivity;
1639 ActivityState lastState = next.state;
1640
1641 mService.updateCpuStats();
1642
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001643 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001644 next.state = ActivityState.RESUMED;
1645 mResumedActivity = next;
1646 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001647 if (mMainStack) {
1648 mService.addRecentTaskLocked(next.task);
1649 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001650 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001651 updateLRUListLocked(next);
1652
1653 // Have the window manager re-evaluate the orientation of
1654 // the screen based on the new activity order.
1655 boolean updated = false;
1656 if (mMainStack) {
1657 synchronized (mService) {
1658 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1659 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001660 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001661 if (config != null) {
1662 next.frozenBeforeDestroy = true;
1663 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001664 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001665 }
1666 }
1667 if (!updated) {
1668 // The configuration update wasn't able to keep the existing
1669 // instance of the activity, and instead started a new one.
1670 // We should be all done, but let's just make sure our activity
1671 // is still at the top and schedule another run if something
1672 // weird happened.
1673 ActivityRecord nextNext = topRunningActivityLocked(null);
1674 if (DEBUG_SWITCH) Slog.i(TAG,
1675 "Activity config changed during resume: " + next
1676 + ", new next: " + nextNext);
1677 if (nextNext != next) {
1678 // Do over!
1679 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1680 }
1681 if (mMainStack) {
1682 mService.setFocusedActivityLocked(next);
1683 }
1684 ensureActivitiesVisibleLocked(null, 0);
1685 mService.mWindowManager.executeAppTransition();
1686 mNoAnimActivities.clear();
1687 return true;
1688 }
1689
1690 try {
1691 // Deliver all pending results.
1692 ArrayList a = next.results;
1693 if (a != null) {
1694 final int N = a.size();
1695 if (!next.finishing && N > 0) {
1696 if (DEBUG_RESULTS) Slog.v(
1697 TAG, "Delivering results to " + next
1698 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001699 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001700 }
1701 }
1702
1703 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001704 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001705 }
1706
1707 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001708 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001709 next.task.taskId, next.shortComponentName);
1710
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001711 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001712 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001713 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001714 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001715 mService.isNextTransitionForward());
1716
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001717 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001718
1719 } catch (Exception e) {
1720 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001721 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1722 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001723 next.state = lastState;
1724 mResumedActivity = lastResumedActivity;
1725 Slog.i(TAG, "Restarting because process died: " + next);
1726 if (!next.hasBeenLaunched) {
1727 next.hasBeenLaunched = true;
1728 } else {
1729 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1730 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001731 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001732 mService.compatibilityInfoForPackageLocked(
1733 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001734 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001735 next.labelRes, next.icon, next.windowFlags,
1736 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001737 }
1738 }
1739 startSpecificActivityLocked(next, true, false);
1740 return true;
1741 }
1742
1743 // From this point on, if something goes wrong there is no way
1744 // to recover the activity.
1745 try {
1746 next.visible = true;
1747 completeResumeLocked(next);
1748 } catch (Exception e) {
1749 // If any exception gets thrown, toss away this
1750 // activity and try the next one.
1751 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001752 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001753 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001754 return true;
1755 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001756 next.stopped = false;
1757
1758 } else {
1759 // Whoops, need to restart this activity!
1760 if (!next.hasBeenLaunched) {
1761 next.hasBeenLaunched = true;
1762 } else {
1763 if (SHOW_APP_STARTING_PREVIEW) {
1764 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001765 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001766 mService.compatibilityInfoForPackageLocked(
1767 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001768 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001769 next.labelRes, next.icon, next.windowFlags,
1770 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001771 }
1772 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1773 }
1774 startSpecificActivityLocked(next, true, true);
1775 }
1776
1777 return true;
1778 }
1779
1780 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001781 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001782 final int NH = mHistory.size();
1783
1784 int addPos = -1;
1785
1786 if (!newTask) {
1787 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 boolean startIt = true;
1789 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001790 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001791 if (p.finishing) {
1792 continue;
1793 }
1794 if (p.task == r.task) {
1795 // Here it is! Now, if this is not yet visible to the
1796 // user, then just add it without starting; it will
1797 // get started when the user navigates back to it.
1798 addPos = i+1;
1799 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001800 if (DEBUG_ADD_REMOVE) {
1801 RuntimeException here = new RuntimeException("here");
1802 here.fillInStackTrace();
1803 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1804 here);
1805 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001806 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001807 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001808 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001809 r.info.screenOrientation, r.fullscreen);
1810 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001811 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001812 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001813 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001814 return;
1815 }
1816 break;
1817 }
1818 if (p.fullscreen) {
1819 startIt = false;
1820 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 }
1822 }
1823
1824 // Place a new activity at top of stack, so it is next to interact
1825 // with the user.
1826 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001827 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001828 }
1829
1830 // If we are not placing the new activity frontmost, we do not want
1831 // to deliver the onUserLeaving callback to the actual frontmost
1832 // activity
1833 if (addPos < NH) {
1834 mUserLeaving = false;
1835 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1836 }
1837
1838 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001839 if (DEBUG_ADD_REMOVE) {
1840 RuntimeException here = new RuntimeException("here");
1841 here.fillInStackTrace();
1842 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1843 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001845 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001846 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001847 if (NH > 0) {
1848 // We want to show the starting preview window if we are
1849 // switching to a new task, or the next activity's process is
1850 // not currently running.
1851 boolean showStartingIcon = newTask;
1852 ProcessRecord proc = r.app;
1853 if (proc == null) {
1854 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1855 }
1856 if (proc == null || proc.thread == null) {
1857 showStartingIcon = true;
1858 }
1859 if (DEBUG_TRANSITION) Slog.v(TAG,
1860 "Prepare open transition: starting " + r);
1861 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001862 mService.mWindowManager.prepareAppTransition(
1863 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001864 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001865 } else {
1866 mService.mWindowManager.prepareAppTransition(newTask
1867 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001868 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 mNoAnimActivities.remove(r);
1870 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001871 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001872 mService.mWindowManager.addAppToken(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001873 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001874 boolean doShow = true;
1875 if (newTask) {
1876 // Even though this activity is starting fresh, we still need
1877 // to reset it to make sure we apply affinities to move any
1878 // existing activities from other tasks in to it.
1879 // If the caller has requested that the target task be
1880 // reset, then do so.
1881 if ((r.intent.getFlags()
1882 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1883 resetTaskIfNeededLocked(r, r);
1884 doShow = topRunningNonDelayedActivityLocked(null) == r;
1885 }
1886 }
1887 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1888 // Figure out if we are transitioning from another activity that is
1889 // "has the same starting icon" as the next one. This allows the
1890 // window manager to keep the previous window it had previously
1891 // created, if it still had one.
1892 ActivityRecord prev = mResumedActivity;
1893 if (prev != null) {
1894 // We don't want to reuse the previous starting preview if:
1895 // (1) The current activity is in a different task.
1896 if (prev.task != r.task) prev = null;
1897 // (2) The current activity is already displayed.
1898 else if (prev.nowVisible) prev = null;
1899 }
1900 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001901 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001902 mService.compatibilityInfoForPackageLocked(
1903 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001904 r.labelRes, r.icon, r.windowFlags,
1905 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001906 }
1907 } else {
1908 // If this is the first activity, don't do any fancy animations,
1909 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001910 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 r.info.screenOrientation, r.fullscreen);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001912 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 }
1914 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001915 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001916 }
1917
1918 if (doResume) {
1919 resumeTopActivityLocked(null);
1920 }
1921 }
1922
Dianne Hackbornbe707852011-11-11 14:32:10 -08001923 final void validateAppTokensLocked() {
1924 mValidateAppTokens.clear();
1925 mValidateAppTokens.ensureCapacity(mHistory.size());
1926 for (int i=0; i<mHistory.size(); i++) {
1927 mValidateAppTokens.add(mHistory.get(i).appToken);
1928 }
1929 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1930 }
1931
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001932 /**
1933 * Perform a reset of the given task, if needed as part of launching it.
1934 * Returns the new HistoryRecord at the top of the task.
1935 */
1936 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1937 ActivityRecord newActivity) {
1938 boolean forceReset = (newActivity.info.flags
1939 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001940 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1941 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001942 if ((newActivity.info.flags
1943 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1944 forceReset = true;
1945 }
1946 }
1947
1948 final TaskRecord task = taskTop.task;
1949
1950 // We are going to move through the history list so that we can look
1951 // at each activity 'target' with 'below' either the interesting
1952 // activity immediately below it in the stack or null.
1953 ActivityRecord target = null;
1954 int targetI = 0;
1955 int taskTopI = -1;
1956 int replyChainEnd = -1;
1957 int lastReparentPos = -1;
1958 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001959 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001960
1961 if (below != null && below.finishing) {
1962 continue;
1963 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001964 // Don't check any lower in the stack if we're crossing a user boundary.
1965 if (below != null && below.userId != taskTop.userId) {
1966 break;
1967 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001968 if (target == null) {
1969 target = below;
1970 targetI = i;
1971 // If we were in the middle of a reply chain before this
1972 // task, it doesn't appear like the root of the chain wants
1973 // anything interesting, so drop it.
1974 replyChainEnd = -1;
1975 continue;
1976 }
1977
1978 final int flags = target.info.flags;
1979
1980 final boolean finishOnTaskLaunch =
1981 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
1982 final boolean allowTaskReparenting =
1983 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
1984
1985 if (target.task == task) {
1986 // We are inside of the task being reset... we'll either
1987 // finish this activity, push it out for another task,
1988 // or leave it as-is. We only do this
1989 // for activities that are not the root of the task (since
1990 // if we finish the root, we may no longer have the task!).
1991 if (taskTopI < 0) {
1992 taskTopI = targetI;
1993 }
1994 if (below != null && below.task == task) {
1995 final boolean clearWhenTaskReset =
1996 (target.intent.getFlags()
1997 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
1998 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
1999 // If this activity is sending a reply to a previous
2000 // activity, we can't do anything with it now until
2001 // we reach the start of the reply chain.
2002 // XXX note that we are assuming the result is always
2003 // to the previous activity, which is almost always
2004 // the case but we really shouldn't count on.
2005 if (replyChainEnd < 0) {
2006 replyChainEnd = targetI;
2007 }
2008 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2009 && target.taskAffinity != null
2010 && !target.taskAffinity.equals(task.affinity)) {
2011 // If this activity has an affinity for another
2012 // task, then we need to move it out of here. We will
2013 // move it as far out of the way as possible, to the
2014 // bottom of the activity stack. This also keeps it
2015 // correctly ordered with any activities we previously
2016 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002017 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002018 if (target.taskAffinity != null
2019 && target.taskAffinity.equals(p.task.affinity)) {
2020 // If the activity currently at the bottom has the
2021 // same task affinity as the one we are moving,
2022 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002023 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002024 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2025 + " out to bottom task " + p.task);
2026 } else {
2027 mService.mCurTask++;
2028 if (mService.mCurTask <= 0) {
2029 mService.mCurTask = 1;
2030 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002031 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2032 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002033 target.task.affinityIntent = target.intent;
2034 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2035 + " out to new task " + target.task);
2036 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002037 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002038 if (replyChainEnd < 0) {
2039 replyChainEnd = targetI;
2040 }
2041 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002042 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002043 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002044 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002045 if (p.finishing) {
2046 continue;
2047 }
2048 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2049 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002050 p.setTask(target.task, curThumbHolder, false);
2051 curThumbHolder = p.thumbHolder;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002052 if (DEBUG_ADD_REMOVE) {
2053 RuntimeException here = new RuntimeException("here");
2054 here.fillInStackTrace();
2055 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2056 + dstPos, here);
2057 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002058 mHistory.remove(srcPos);
2059 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002060 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2061 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002062 dstPos++;
2063 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002064 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002065 }
2066 i++;
2067 }
2068 if (taskTop == p) {
2069 taskTop = below;
2070 }
2071 if (taskTopI == replyChainEnd) {
2072 taskTopI = -1;
2073 }
2074 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002075 } else if (forceReset || finishOnTaskLaunch
2076 || clearWhenTaskReset) {
2077 // If the activity should just be removed -- either
2078 // because it asks for it, or the task should be
2079 // cleared -- then finish it and anything that is
2080 // part of its reply chain.
2081 if (clearWhenTaskReset) {
2082 // In this case, we want to finish this activity
2083 // and everything above it, so be sneaky and pretend
2084 // like these are all in the reply chain.
2085 replyChainEnd = targetI+1;
2086 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002087 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002088 replyChainEnd)).task == task) {
2089 replyChainEnd++;
2090 }
2091 replyChainEnd--;
2092 } else if (replyChainEnd < 0) {
2093 replyChainEnd = targetI;
2094 }
2095 ActivityRecord p = null;
2096 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002097 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002098 if (p.finishing) {
2099 continue;
2100 }
2101 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002102 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002103 replyChainEnd--;
2104 srcPos--;
2105 }
2106 }
2107 if (taskTop == p) {
2108 taskTop = below;
2109 }
2110 if (taskTopI == replyChainEnd) {
2111 taskTopI = -1;
2112 }
2113 replyChainEnd = -1;
2114 } else {
2115 // If we were in the middle of a chain, well the
2116 // activity that started it all doesn't want anything
2117 // special, so leave it all as-is.
2118 replyChainEnd = -1;
2119 }
2120 } else {
2121 // Reached the bottom of the task -- any reply chain
2122 // should be left as-is.
2123 replyChainEnd = -1;
2124 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002125
2126 } else if (target.resultTo != null && (below == null
2127 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002128 // If this activity is sending a reply to a previous
2129 // activity, we can't do anything with it now until
2130 // we reach the start of the reply chain.
2131 // XXX note that we are assuming the result is always
2132 // to the previous activity, which is almost always
2133 // the case but we really shouldn't count on.
2134 if (replyChainEnd < 0) {
2135 replyChainEnd = targetI;
2136 }
2137
2138 } else if (taskTopI >= 0 && allowTaskReparenting
2139 && task.affinity != null
2140 && task.affinity.equals(target.taskAffinity)) {
2141 // We are inside of another task... if this activity has
2142 // an affinity for our task, then either remove it if we are
2143 // clearing or move it over to our task. Note that
2144 // we currently punt on the case where we are resetting a
2145 // task that is not at the top but who has activities above
2146 // with an affinity to it... this is really not a normal
2147 // case, and we will need to later pull that task to the front
2148 // and usually at that point we will do the reset and pick
2149 // up those remaining activities. (This only happens if
2150 // someone starts an activity in a new task from an activity
2151 // in a task that is not currently on top.)
2152 if (forceReset || finishOnTaskLaunch) {
2153 if (replyChainEnd < 0) {
2154 replyChainEnd = targetI;
2155 }
2156 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002157 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2158 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002159 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002160 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002161 if (p.finishing) {
2162 continue;
2163 }
2164 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002165 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002166 taskTopI--;
2167 lastReparentPos--;
2168 replyChainEnd--;
2169 srcPos--;
2170 }
2171 }
2172 replyChainEnd = -1;
2173 } else {
2174 if (replyChainEnd < 0) {
2175 replyChainEnd = targetI;
2176 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002177 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2178 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002179 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002180 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002181 if (p.finishing) {
2182 continue;
2183 }
2184 if (lastReparentPos < 0) {
2185 lastReparentPos = taskTopI;
2186 taskTop = p;
2187 } else {
2188 lastReparentPos--;
2189 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002190 if (DEBUG_ADD_REMOVE) {
2191 RuntimeException here = new RuntimeException("here");
2192 here.fillInStackTrace();
2193 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2194 + lastReparentPos, here);
2195 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002196 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002197 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002198 mHistory.add(lastReparentPos, p);
2199 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002200 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002201 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002202 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2203 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002204 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002205 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002206 }
2207 }
2208 replyChainEnd = -1;
2209
2210 // Now we've moved it in to place... but what if this is
2211 // a singleTop activity and we have put it on top of another
2212 // instance of the same activity? Then we drop the instance
2213 // below so it remains singleTop.
2214 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2215 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002216 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002217 if (p.finishing) {
2218 continue;
2219 }
2220 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2221 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002222 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002223 taskTopI--;
2224 lastReparentPos--;
2225 }
2226 }
2227 }
2228 }
2229 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002230
2231 } else if (below != null && below.task != target.task) {
2232 // We hit the botton of a task; the reply chain can't
2233 // pass through it.
2234 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002235 }
2236
2237 target = below;
2238 targetI = i;
2239 }
2240
2241 return taskTop;
2242 }
2243
2244 /**
2245 * Perform clear operation as requested by
2246 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2247 * stack to the given task, then look for
2248 * an instance of that activity in the stack and, if found, finish all
2249 * activities on top of it and return the instance.
2250 *
2251 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002252 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002253 * or null if none was found.
2254 */
2255 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002256 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002257 int i = mHistory.size();
2258
2259 // First find the requested task.
2260 while (i > 0) {
2261 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002262 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002263 if (r.task.taskId == taskId) {
2264 i++;
2265 break;
2266 }
2267 }
2268
2269 // Now clear it.
2270 while (i > 0) {
2271 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002272 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 if (r.finishing) {
2274 continue;
2275 }
2276 if (r.task.taskId != taskId) {
2277 return null;
2278 }
2279 if (r.realActivity.equals(newR.realActivity)) {
2280 // Here it is! Now finish everything in front...
2281 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002282 while (i < (mHistory.size()-1)) {
2283 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002284 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002285 if (r.task.taskId != taskId) {
2286 break;
2287 }
2288 if (r.finishing) {
2289 continue;
2290 }
2291 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002292 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002293 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002294 }
2295 }
2296
2297 // Finally, if this is a normal launch mode (that is, not
2298 // expecting onNewIntent()), then we will finish the current
2299 // instance of the activity so a new fresh one can be started.
2300 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2301 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2302 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002303 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002304 if (index >= 0) {
2305 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002306 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002307 }
2308 return null;
2309 }
2310 }
2311
2312 return ret;
2313 }
2314 }
2315
2316 return null;
2317 }
2318
2319 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002320 * Completely remove all activities associated with an existing
2321 * task starting at a specified index.
2322 */
2323 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002324 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002325 ActivityRecord r = mHistory.get(i);
2326 if (r.task.taskId != taskId) {
2327 // Whoops hit the end.
2328 return;
2329 }
2330 if (r.finishing) {
2331 i++;
2332 continue;
2333 }
2334 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002335 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002336 i++;
2337 }
2338 }
2339 }
2340
2341 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002342 * Completely remove all activities associated with an existing task.
2343 */
2344 private final void performClearTaskLocked(int taskId) {
2345 int i = mHistory.size();
2346
2347 // First find the requested task.
2348 while (i > 0) {
2349 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002350 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002351 if (r.task.taskId == taskId) {
2352 i++;
2353 break;
2354 }
2355 }
2356
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002357 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002358 while (i > 0) {
2359 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002360 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002361 if (r.finishing) {
2362 continue;
2363 }
2364 if (r.task.taskId != taskId) {
2365 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002366 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002367 return;
2368 }
2369 }
2370 }
2371
2372 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 * Find the activity in the history stack within the given task. Returns
2374 * the index within the history at which it's found, or < 0 if not found.
2375 */
2376 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2377 int i = mHistory.size();
2378 while (i > 0) {
2379 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002380 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002381 if (candidate.finishing) {
2382 continue;
2383 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002384 if (candidate.task.taskId != task) {
2385 break;
2386 }
2387 if (candidate.realActivity.equals(r.realActivity)) {
2388 return i;
2389 }
2390 }
2391
2392 return -1;
2393 }
2394
2395 /**
2396 * Reorder the history stack so that the activity at the given index is
2397 * brought to the front.
2398 */
2399 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002400 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002401 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002402 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002403 if (DEBUG_ADD_REMOVE) {
2404 RuntimeException here = new RuntimeException("here");
2405 here.fillInStackTrace();
2406 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2407 + top, here);
2408 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002409 mHistory.add(top, newTop);
2410 oldTop.frontOfTask = false;
2411 newTop.frontOfTask = true;
2412 return newTop;
2413 }
2414
2415 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002416 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002417 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002418 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002419 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002420
Dianne Hackborna4972e92012-03-14 10:38:05 -07002421 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002422
2423 ProcessRecord callerApp = null;
2424 if (caller != null) {
2425 callerApp = mService.getRecordForAppLocked(caller);
2426 if (callerApp != null) {
2427 callingPid = callerApp.pid;
2428 callingUid = callerApp.info.uid;
2429 } else {
2430 Slog.w(TAG, "Unable to find app for caller " + caller
2431 + " (pid=" + callingPid + ") when starting: "
2432 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002433 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002434 }
2435 }
2436
Dianne Hackborna4972e92012-03-14 10:38:05 -07002437 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002438 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002439 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2440 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002441 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002442
2443 ActivityRecord sourceRecord = null;
2444 ActivityRecord resultRecord = null;
2445 if (resultTo != null) {
2446 int index = indexOfTokenLocked(resultTo);
2447 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002448 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002449 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002450 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002451 if (requestCode >= 0 && !sourceRecord.finishing) {
2452 resultRecord = sourceRecord;
2453 }
2454 }
2455 }
2456
2457 int launchFlags = intent.getFlags();
2458
2459 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2460 && sourceRecord != null) {
2461 // Transfer the result target from the source activity to the new
2462 // one being started, including any failures.
2463 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002464 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002465 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002466 }
2467 resultRecord = sourceRecord.resultTo;
2468 resultWho = sourceRecord.resultWho;
2469 requestCode = sourceRecord.requestCode;
2470 sourceRecord.resultTo = null;
2471 if (resultRecord != null) {
2472 resultRecord.removeResultsLocked(
2473 sourceRecord, resultWho, requestCode);
2474 }
2475 }
2476
Dianne Hackborna4972e92012-03-14 10:38:05 -07002477 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002478 // We couldn't find a class that can handle the given Intent.
2479 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002480 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002481 }
2482
Dianne Hackborna4972e92012-03-14 10:38:05 -07002483 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002484 // We couldn't find the specific class specified in the Intent.
2485 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002486 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002487 }
2488
Dianne Hackborna4972e92012-03-14 10:38:05 -07002489 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002490 if (resultRecord != null) {
2491 sendActivityResultLocked(-1,
2492 resultRecord, resultWho, requestCode,
2493 Activity.RESULT_CANCELED, null);
2494 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002495 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002496 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002497 return err;
2498 }
2499
Jeff Sharkey35be7562012-04-18 19:16:15 -07002500 final int startAnyPerm = mService.checkPermission(
2501 START_ANY_ACTIVITY, callingPid, callingUid);
2502 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002503 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002504 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002505 if (resultRecord != null) {
2506 sendActivityResultLocked(-1,
2507 resultRecord, resultWho, requestCode,
2508 Activity.RESULT_CANCELED, null);
2509 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002510 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002511 String msg;
2512 if (!aInfo.exported) {
2513 msg = "Permission Denial: starting " + intent.toString()
2514 + " from " + callerApp + " (pid=" + callingPid
2515 + ", uid=" + callingUid + ")"
2516 + " not exported from uid " + aInfo.applicationInfo.uid;
2517 } else {
2518 msg = "Permission Denial: starting " + intent.toString()
2519 + " from " + callerApp + " (pid=" + callingPid
2520 + ", uid=" + callingUid + ")"
2521 + " requires " + aInfo.permission;
2522 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002523 Slog.w(TAG, msg);
2524 throw new SecurityException(msg);
2525 }
2526
2527 if (mMainStack) {
2528 if (mService.mController != null) {
2529 boolean abort = false;
2530 try {
2531 // The Intent we give to the watcher has the extra data
2532 // stripped off, since it can contain private information.
2533 Intent watchIntent = intent.cloneFilter();
2534 abort = !mService.mController.activityStarting(watchIntent,
2535 aInfo.applicationInfo.packageName);
2536 } catch (RemoteException e) {
2537 mService.mController = null;
2538 }
2539
2540 if (abort) {
2541 if (resultRecord != null) {
2542 sendActivityResultLocked(-1,
2543 resultRecord, resultWho, requestCode,
2544 Activity.RESULT_CANCELED, null);
2545 }
2546 // We pretend to the caller that it was really started, but
2547 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002548 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002549 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002550 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 }
2552 }
2553 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002554
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002555 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2556 intent, resolvedType, aInfo, mService.mConfiguration,
2557 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002558 if (outActivity != null) {
2559 outActivity[0] = r;
2560 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561
2562 if (mMainStack) {
2563 if (mResumedActivity == null
2564 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2565 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2566 PendingActivityLaunch pal = new PendingActivityLaunch();
2567 pal.r = r;
2568 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002569 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002570 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002571 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002572 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002573 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002574 }
2575 }
2576
2577 if (mService.mDidAppSwitch) {
2578 // This is the second allowed switch since we stopped switches,
2579 // so now just generally allow switches. Use case: user presses
2580 // home (switches disabled, switch to home, mDidAppSwitch now true);
2581 // user taps a home icon (coming from home so allowed, we hit here
2582 // and now allow anyone to switch again).
2583 mService.mAppSwitchesAllowedTime = 0;
2584 } else {
2585 mService.mDidAppSwitch = true;
2586 }
2587
2588 mService.doPendingActivityLaunchesLocked(false);
2589 }
2590
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002591 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002592 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002593 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002594 // Someone asked to have the keyguard dismissed on the next
2595 // activity start, but we are not actually doing an activity
2596 // switch... just dismiss the keyguard now, because we
2597 // probably want to see whatever is behind it.
2598 mDismissKeyguardOnNextActivity = false;
2599 mService.mWindowManager.dismissKeyguard();
2600 }
2601 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002602 }
2603
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002604 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2605 if ((launchFlags &
2606 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2607 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2608 // Caller wants to appear on home activity, so before starting
2609 // their own activity we will bring home to the front.
2610 moveHomeToFrontLocked();
2611 }
2612 }
2613
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002614 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002615 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2616 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 final Intent intent = r.intent;
2618 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002619 final int userId = r.userId;
2620
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002621 int launchFlags = intent.getFlags();
2622
2623 // We'll invoke onUserLeaving before onPause only if the launching
2624 // activity did not explicitly state that this is an automated launch.
2625 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2626 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2627 "startActivity() => mUserLeaving=" + mUserLeaving);
2628
2629 // If the caller has asked not to resume at this point, we make note
2630 // of this in the record so that we can skip it when trying to find
2631 // the top running activity.
2632 if (!doResume) {
2633 r.delayedResume = true;
2634 }
2635
2636 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2637 != 0 ? r : null;
2638
2639 // If the onlyIfNeeded flag is set, then we can do this if the activity
2640 // being launched is the same as the one making the call... or, as
2641 // a special case, if we do not know the caller then we count the
2642 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002643 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002644 ActivityRecord checkedCaller = sourceRecord;
2645 if (checkedCaller == null) {
2646 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2647 }
2648 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2649 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002650 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002651 }
2652 }
2653
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002654 if (sourceRecord == null) {
2655 // This activity is not being started from another... in this
2656 // case we -always- start a new task.
2657 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2658 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2659 + intent);
2660 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2661 }
2662 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2663 // The original activity who is starting us is running as a single
2664 // instance... this new activity it is starting must go on its
2665 // own task.
2666 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2667 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2668 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2669 // The activity being started is a single instance... it always
2670 // gets launched into its own task.
2671 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2672 }
2673
2674 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2675 // For whatever reason this activity is being launched into a new
2676 // task... yet the caller has requested a result back. Well, that
2677 // is pretty messed up, so instead immediately send back a cancel
2678 // and let the new task continue launched as normal without a
2679 // dependency on its originator.
2680 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2681 sendActivityResultLocked(-1,
2682 r.resultTo, r.resultWho, r.requestCode,
2683 Activity.RESULT_CANCELED, null);
2684 r.resultTo = null;
2685 }
2686
2687 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002688 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002689 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002690 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2691 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2692 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2693 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2694 // If bring to front is requested, and no result is requested, and
2695 // we can find a task that was started with this same
2696 // component, then instead of launching bring that one to the front.
2697 if (r.resultTo == null) {
2698 // See if there is a task to bring to the front. If this is
2699 // a SINGLE_INSTANCE activity, there can be one and only one
2700 // instance of it in the history, and it is always in its own
2701 // unique task, so we do a special search.
2702 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2703 ? findTaskLocked(intent, r.info)
2704 : findActivityLocked(intent, r.info);
2705 if (taskTop != null) {
2706 if (taskTop.task.intent == null) {
2707 // This task was started because of movement of
2708 // the activity based on affinity... now that we
2709 // are actually launching it, we can assign the
2710 // base intent.
2711 taskTop.task.setIntent(intent, r.info);
2712 }
2713 // If the target task is not in the front, then we need
2714 // to bring it to the front... except... well, with
2715 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2716 // to have the same behavior as if a new instance was
2717 // being started, which means not bringing it to the front
2718 // if the caller is not itself in the front.
2719 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002720 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002721 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2722 boolean callerAtFront = sourceRecord == null
2723 || curTop.task == sourceRecord.task;
2724 if (callerAtFront) {
2725 // We really do want to push this one into the
2726 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002727 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002728 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002729 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002730 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002731 }
2732 }
2733 // If the caller has requested that the target task be
2734 // reset, then do so.
2735 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2736 taskTop = resetTaskIfNeededLocked(taskTop, r);
2737 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002738 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002739 // We don't need to start a new activity, and
2740 // the client said not to do anything if that
2741 // is the case, so this is it! And for paranoia, make
2742 // sure we have correctly resumed the top activity.
2743 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002744 resumeTopActivityLocked(null, options);
2745 } else {
2746 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002747 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002748 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002749 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002750 if ((launchFlags &
2751 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2752 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2753 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002754 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002755 // not be too hard...
2756 reuseTask = taskTop.task;
2757 performClearTaskLocked(taskTop.task.taskId);
2758 reuseTask.setIntent(r.intent, r.info);
2759 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002760 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2761 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2762 // In this situation we want to remove all activities
2763 // from the task up to the one being started. In most
2764 // cases this means we are resetting the task to its
2765 // initial state.
2766 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002767 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002768 if (top != null) {
2769 if (top.frontOfTask) {
2770 // Activity aliases may mean we use different
2771 // intents for the top activity, so make sure
2772 // the task now has the identity of the new
2773 // intent.
2774 top.task.setIntent(r.intent, r.info);
2775 }
2776 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002777 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002778 } else {
2779 // A special case: we need to
2780 // start the activity because it is not currently
2781 // running, and the caller has asked to clear the
2782 // current task to have this activity at the top.
2783 addingToTask = true;
2784 // Now pretend like this activity is being started
2785 // by the top of its task, so it is put in the
2786 // right place.
2787 sourceRecord = taskTop;
2788 }
2789 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2790 // In this case the top activity on the task is the
2791 // same as the one being launched, so we take that
2792 // as a request to bring the task to the foreground.
2793 // If the top activity in the task is the root
2794 // activity, deliver this new intent to it if it
2795 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002796 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2797 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002798 && taskTop.realActivity.equals(r.realActivity)) {
2799 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2800 if (taskTop.frontOfTask) {
2801 taskTop.task.setIntent(r.intent, r.info);
2802 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002803 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002804 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2805 // In this case we are launching the root activity
2806 // of the task, but with a different intent. We
2807 // should start a new instance on top.
2808 addingToTask = true;
2809 sourceRecord = taskTop;
2810 }
2811 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2812 // In this case an activity is being launched in to an
2813 // existing task, without resetting that task. This
2814 // is typically the situation of launching an activity
2815 // from a notification or shortcut. We want to place
2816 // the new activity on top of the current task.
2817 addingToTask = true;
2818 sourceRecord = taskTop;
2819 } else if (!taskTop.task.rootWasReset) {
2820 // In this case we are launching in to an existing task
2821 // that has not yet been started from its front door.
2822 // The current task has been brought to the front.
2823 // Ideally, we'd probably like to place this new task
2824 // at the bottom of its stack, but that's a little hard
2825 // to do with the current organization of the code so
2826 // for now we'll just drop it.
2827 taskTop.task.setIntent(r.intent, r.info);
2828 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002829 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002830 // We didn't do anything... but it was needed (a.k.a., client
2831 // don't use that intent!) And for paranoia, make
2832 // sure we have correctly resumed the top activity.
2833 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002834 resumeTopActivityLocked(null, options);
2835 } else {
2836 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002837 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002838 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002839 }
2840 }
2841 }
2842 }
2843
2844 //String uri = r.intent.toURI();
2845 //Intent intent2 = new Intent(uri);
2846 //Slog.i(TAG, "Given intent: " + r.intent);
2847 //Slog.i(TAG, "URI is: " + uri);
2848 //Slog.i(TAG, "To intent: " + intent2);
2849
2850 if (r.packageName != null) {
2851 // If the activity being launched is the same as the one currently
2852 // at the top, then we need to check if it should only be launched
2853 // once.
2854 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2855 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002856 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002857 if (top.app != null && top.app.thread != null) {
2858 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2859 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2860 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2861 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2862 // For paranoia, make sure we have correctly
2863 // resumed the top activity.
2864 if (doResume) {
2865 resumeTopActivityLocked(null);
2866 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002867 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002868 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002869 // We don't need to start a new activity, and
2870 // the client said not to do anything if that
2871 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002872 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002873 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002874 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002875 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002876 }
2877 }
2878 }
2879 }
2880
2881 } else {
2882 if (r.resultTo != null) {
2883 sendActivityResultLocked(-1,
2884 r.resultTo, r.resultWho, r.requestCode,
2885 Activity.RESULT_CANCELED, null);
2886 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002887 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 }
2890
2891 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002892 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002893
2894 // Should this be considered a new task?
2895 if (r.resultTo == null && !addingToTask
2896 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002897 if (reuseTask == null) {
2898 // todo: should do better management of integers.
2899 mService.mCurTask++;
2900 if (mService.mCurTask <= 0) {
2901 mService.mCurTask = 1;
2902 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002903 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002904 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2905 + " in new task " + r.task);
2906 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002907 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002908 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002909 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002910 if (!movedHome) {
2911 moveHomeToFrontFromLaunchLocked(launchFlags);
2912 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002913
2914 } else if (sourceRecord != null) {
2915 if (!addingToTask &&
2916 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2917 // In this case, we are adding the activity to an existing
2918 // task, but the caller has asked to clear that task if the
2919 // activity is already running.
2920 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002921 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002922 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002923 if (top != null) {
2924 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002925 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 // For paranoia, make sure we have correctly
2927 // resumed the top activity.
2928 if (doResume) {
2929 resumeTopActivityLocked(null);
2930 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002931 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002932 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002933 }
2934 } else if (!addingToTask &&
2935 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2936 // In this case, we are launching an activity in our own task
2937 // that may already be running somewhere in the history, and
2938 // we want to shuffle it to the front of the stack if so.
2939 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
2940 if (where >= 0) {
2941 ActivityRecord top = moveActivityToFrontLocked(where);
2942 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002943 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002944 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002945 if (doResume) {
2946 resumeTopActivityLocked(null);
2947 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002948 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002949 }
2950 }
2951 // An existing activity is starting this new activity, so we want
2952 // to keep the new one in the same task as the one that is starting
2953 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002954 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002955 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2956 + " in existing task " + r.task);
2957
2958 } else {
2959 // This not being started from an existing activity, and not part
2960 // of a new task... just put it in the top task, though these days
2961 // this case should never happen.
2962 final int N = mHistory.size();
2963 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002964 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002965 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002966 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002967 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002968 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2969 + " in new guessed " + r.task);
2970 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002971
Dianne Hackborn39792d22010-08-19 18:01:52 -07002972 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07002973 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07002974
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002975 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07002976 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002977 }
2978 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002979 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002980 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002981 }
2982
Dianne Hackborna4972e92012-03-14 10:38:05 -07002983 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07002984 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002985 // Collect information about the target of the Intent.
2986 ActivityInfo aInfo;
2987 try {
2988 ResolveInfo rInfo =
2989 AppGlobals.getPackageManager().resolveIntent(
2990 intent, resolvedType,
2991 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07002992 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002993 aInfo = rInfo != null ? rInfo.activityInfo : null;
2994 } catch (RemoteException e) {
2995 aInfo = null;
2996 }
2997
2998 if (aInfo != null) {
2999 // Store the found target back into the intent, because now that
3000 // we have it we never want to do this again. For example, if the
3001 // user navigates back to this point in the history, we should
3002 // always restart the exact same activity.
3003 intent.setComponent(new ComponentName(
3004 aInfo.applicationInfo.packageName, aInfo.name));
3005
3006 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003007 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003008 if (!aInfo.processName.equals("system")) {
3009 mService.setDebugApp(aInfo.processName, true, false);
3010 }
3011 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003012
Dianne Hackborna4972e92012-03-14 10:38:05 -07003013 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003014 if (!aInfo.processName.equals("system")) {
3015 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3016 }
3017 }
3018
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003019 if (profileFile != null) {
3020 if (!aInfo.processName.equals("system")) {
3021 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003022 profileFile, profileFd,
3023 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003024 }
3025 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003026 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003027 return aInfo;
3028 }
3029
3030 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003031 Intent intent, String resolvedType, IBinder resultTo,
3032 String resultWho, int requestCode, int startFlags, String profileFile,
3033 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3034 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003035 // Refuse possible leaked file descriptors
3036 if (intent != null && intent.hasFileDescriptors()) {
3037 throw new IllegalArgumentException("File descriptors passed in Intent");
3038 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003039 boolean componentSpecified = intent.getComponent() != null;
3040
3041 // Don't modify the client's object!
3042 intent = new Intent(intent);
3043
3044 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003045 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003046 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003047
3048 synchronized (mService) {
3049 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003050 if (callingUid >= 0) {
3051 callingPid = -1;
3052 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003053 callingPid = Binder.getCallingPid();
3054 callingUid = Binder.getCallingUid();
3055 } else {
3056 callingPid = callingUid = -1;
3057 }
3058
3059 mConfigWillChange = config != null
3060 && mService.mConfiguration.diff(config) != 0;
3061 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3062 "Starting activity when config will change = " + mConfigWillChange);
3063
3064 final long origId = Binder.clearCallingIdentity();
3065
3066 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003067 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003068 // This may be a heavy-weight process! Check to see if we already
3069 // have another, different heavy-weight process running.
3070 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3071 if (mService.mHeavyWeightProcess != null &&
3072 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3073 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3074 int realCallingPid = callingPid;
3075 int realCallingUid = callingUid;
3076 if (caller != null) {
3077 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3078 if (callerApp != null) {
3079 realCallingPid = callerApp.pid;
3080 realCallingUid = callerApp.info.uid;
3081 } else {
3082 Slog.w(TAG, "Unable to find app for caller " + caller
3083 + " (pid=" + realCallingPid + ") when starting: "
3084 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003085 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003086 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003087 }
3088 }
3089
3090 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003091 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003092 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003093 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003094 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003095
3096 Intent newIntent = new Intent();
3097 if (requestCode >= 0) {
3098 // Caller is requesting a result.
3099 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3100 }
3101 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3102 new IntentSender(target));
3103 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3104 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3105 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3106 hist.packageName);
3107 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3108 hist.task.taskId);
3109 }
3110 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3111 aInfo.packageName);
3112 newIntent.setFlags(intent.getFlags());
3113 newIntent.setClassName("android",
3114 HeavyWeightSwitcherActivity.class.getName());
3115 intent = newIntent;
3116 resolvedType = null;
3117 caller = null;
3118 callingUid = Binder.getCallingUid();
3119 callingPid = Binder.getCallingPid();
3120 componentSpecified = true;
3121 try {
3122 ResolveInfo rInfo =
3123 AppGlobals.getPackageManager().resolveIntent(
3124 intent, null,
3125 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003126 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003127 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003128 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003129 } catch (RemoteException e) {
3130 aInfo = null;
3131 }
3132 }
3133 }
3134 }
3135
3136 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003137 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3138 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003139
3140 if (mConfigWillChange && mMainStack) {
3141 // If the caller also wants to switch to a new configuration,
3142 // do so now. This allows a clean switch, as we are waiting
3143 // for the current activity to pause (so we will not destroy
3144 // it), and have not yet started the next activity.
3145 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3146 "updateConfiguration()");
3147 mConfigWillChange = false;
3148 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3149 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003150 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003151 }
3152
3153 Binder.restoreCallingIdentity(origId);
3154
3155 if (outResult != null) {
3156 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003157 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158 mWaitingActivityLaunched.add(outResult);
3159 do {
3160 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003161 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003162 } catch (InterruptedException e) {
3163 }
3164 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003165 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003166 ActivityRecord r = this.topRunningActivityLocked(null);
3167 if (r.nowVisible) {
3168 outResult.timeout = false;
3169 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3170 outResult.totalTime = 0;
3171 outResult.thisTime = 0;
3172 } else {
3173 outResult.thisTime = SystemClock.uptimeMillis();
3174 mWaitingActivityVisible.add(outResult);
3175 do {
3176 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003177 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 } catch (InterruptedException e) {
3179 }
3180 } while (!outResult.timeout && outResult.who == null);
3181 }
3182 }
3183 }
3184
3185 return res;
3186 }
3187 }
3188
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003189 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003190 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3191 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003192 if (intents == null) {
3193 throw new NullPointerException("intents is null");
3194 }
3195 if (resolvedTypes == null) {
3196 throw new NullPointerException("resolvedTypes is null");
3197 }
3198 if (intents.length != resolvedTypes.length) {
3199 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3200 }
3201
3202 ActivityRecord[] outActivity = new ActivityRecord[1];
3203
3204 int callingPid;
3205 if (callingUid >= 0) {
3206 callingPid = -1;
3207 } else if (caller == null) {
3208 callingPid = Binder.getCallingPid();
3209 callingUid = Binder.getCallingUid();
3210 } else {
3211 callingPid = callingUid = -1;
3212 }
3213 final long origId = Binder.clearCallingIdentity();
3214 try {
3215 synchronized (mService) {
3216
3217 for (int i=0; i<intents.length; i++) {
3218 Intent intent = intents[i];
3219 if (intent == null) {
3220 continue;
3221 }
3222
3223 // Refuse possible leaked file descriptors
3224 if (intent != null && intent.hasFileDescriptors()) {
3225 throw new IllegalArgumentException("File descriptors passed in Intent");
3226 }
3227
3228 boolean componentSpecified = intent.getComponent() != null;
3229
3230 // Don't modify the client's object!
3231 intent = new Intent(intent);
3232
3233 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003234 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003235 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003236 // TODO: New, check if this is correct
3237 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003238
3239 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3240 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3241 throw new IllegalArgumentException(
3242 "FLAG_CANT_SAVE_STATE not supported here");
3243 }
3244
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003245 Bundle theseOptions;
3246 if (options != null && i == intents.length-1) {
3247 theseOptions = options;
3248 } else {
3249 theseOptions = null;
3250 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003251 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003252 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003253 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003254 if (res < 0) {
3255 return res;
3256 }
3257
Dianne Hackbornbe707852011-11-11 14:32:10 -08003258 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003259 }
3260 }
3261 } finally {
3262 Binder.restoreCallingIdentity(origId);
3263 }
3264
Dianne Hackborna4972e92012-03-14 10:38:05 -07003265 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003266 }
3267
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003268 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3269 long thisTime, long totalTime) {
3270 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3271 WaitResult w = mWaitingActivityLaunched.get(i);
3272 w.timeout = timeout;
3273 if (r != null) {
3274 w.who = new ComponentName(r.info.packageName, r.info.name);
3275 }
3276 w.thisTime = thisTime;
3277 w.totalTime = totalTime;
3278 }
3279 mService.notifyAll();
3280 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003281
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003282 void reportActivityVisibleLocked(ActivityRecord r) {
3283 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3284 WaitResult w = mWaitingActivityVisible.get(i);
3285 w.timeout = false;
3286 if (r != null) {
3287 w.who = new ComponentName(r.info.packageName, r.info.name);
3288 }
3289 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3290 w.thisTime = w.totalTime;
3291 }
3292 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003293
3294 if (mDismissKeyguardOnNextActivity) {
3295 mDismissKeyguardOnNextActivity = false;
3296 mService.mWindowManager.dismissKeyguard();
3297 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003298 }
3299
3300 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3301 String resultWho, int requestCode, int resultCode, Intent data) {
3302
3303 if (callingUid > 0) {
3304 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003305 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003306 }
3307
3308 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3309 + " : who=" + resultWho + " req=" + requestCode
3310 + " res=" + resultCode + " data=" + data);
3311 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3312 try {
3313 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3314 list.add(new ResultInfo(resultWho, requestCode,
3315 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003316 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003317 return;
3318 } catch (Exception e) {
3319 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3320 }
3321 }
3322
3323 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3324 }
3325
3326 private final void stopActivityLocked(ActivityRecord r) {
3327 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3328 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3329 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3330 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003331 if (!mService.mSleeping) {
3332 if (DEBUG_STATES) {
3333 Slog.d(TAG, "no-history finish of " + r);
3334 }
3335 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003336 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003337 } else {
3338 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3339 + " on stop because we're just sleeping");
3340 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003341 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003342 }
3343
3344 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003345 if (mMainStack) {
3346 if (mService.mFocusedActivity == r) {
3347 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3348 }
3349 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003350 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003351 try {
3352 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003353 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3354 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003355 r.state = ActivityState.STOPPING;
3356 if (DEBUG_VISBILITY) Slog.v(
3357 TAG, "Stopping visible=" + r.visible + " for " + r);
3358 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003359 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003360 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003361 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003362 if (mService.isSleeping()) {
3363 r.setSleeping(true);
3364 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003365 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3366 msg.obj = r;
3367 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003368 } catch (Exception e) {
3369 // Maybe just ignore exceptions here... if the process
3370 // has crashed, our death notification will clean things
3371 // up.
3372 Slog.w(TAG, "Exception thrown during pause", e);
3373 // Just in case, assume it to be stopped.
3374 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003375 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003376 r.state = ActivityState.STOPPED;
3377 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003378 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003379 }
3380 }
3381 }
3382 }
3383
3384 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3385 boolean remove) {
3386 int N = mStoppingActivities.size();
3387 if (N <= 0) return null;
3388
3389 ArrayList<ActivityRecord> stops = null;
3390
3391 final boolean nowVisible = mResumedActivity != null
3392 && mResumedActivity.nowVisible
3393 && !mResumedActivity.waitingVisible;
3394 for (int i=0; i<N; i++) {
3395 ActivityRecord s = mStoppingActivities.get(i);
3396 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3397 + nowVisible + " waitingVisible=" + s.waitingVisible
3398 + " finishing=" + s.finishing);
3399 if (s.waitingVisible && nowVisible) {
3400 mWaitingVisibleActivities.remove(s);
3401 s.waitingVisible = false;
3402 if (s.finishing) {
3403 // If this activity is finishing, it is sitting on top of
3404 // everyone else but we now know it is no longer needed...
3405 // so get rid of it. Otherwise, we need to go through the
3406 // normal flow and hide it once we determine that it is
3407 // hidden by the activities in front of it.
3408 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003409 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003410 }
3411 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003412 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003413 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3414 if (stops == null) {
3415 stops = new ArrayList<ActivityRecord>();
3416 }
3417 stops.add(s);
3418 mStoppingActivities.remove(i);
3419 N--;
3420 i--;
3421 }
3422 }
3423
3424 return stops;
3425 }
3426
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003427 final void scheduleIdleLocked() {
3428 Message msg = Message.obtain();
3429 msg.what = IDLE_NOW_MSG;
3430 mHandler.sendMessage(msg);
3431 }
3432
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003433 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003434 Configuration config) {
3435 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3436
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003437 ActivityRecord res = null;
3438
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003439 ArrayList<ActivityRecord> stops = null;
3440 ArrayList<ActivityRecord> finishes = null;
3441 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003442 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003443 int NS = 0;
3444 int NF = 0;
3445 int NT = 0;
3446 IApplicationThread sendThumbnail = null;
3447 boolean booting = false;
3448 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003449 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003450
3451 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003452 ActivityRecord r = ActivityRecord.forToken(token);
3453 if (r != null) {
3454 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003455 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003456 }
3457
3458 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003459 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003460 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003461 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003462
3463 if (fromTimeout) {
3464 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3465 }
3466
3467 // This is a hack to semi-deal with a race condition
3468 // in the client where it can be constructed with a
3469 // newer configuration from when we asked it to launch.
3470 // We'll update with whatever configuration it now says
3471 // it used to launch.
3472 if (config != null) {
3473 r.configuration = config;
3474 }
3475
3476 // No longer need to keep the device awake.
3477 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3478 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3479 mLaunchingActivity.release();
3480 }
3481
3482 // We are now idle. If someone is waiting for a thumbnail from
3483 // us, we can now deliver.
3484 r.idle = true;
3485 mService.scheduleAppGcsLocked();
3486 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3487 sendThumbnail = r.app.thread;
3488 r.thumbnailNeeded = false;
3489 }
3490
3491 // If this activity is fullscreen, set up to hide those under it.
3492
3493 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3494 ensureActivitiesVisibleLocked(null, 0);
3495
3496 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3497 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003498 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003499 mService.mBooted = true;
3500 enableScreen = true;
3501 }
3502 }
3503
3504 } else if (fromTimeout) {
3505 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3506 }
3507
3508 // Atomically retrieve all of the other things to do.
3509 stops = processStoppingActivitiesLocked(true);
3510 NS = stops != null ? stops.size() : 0;
3511 if ((NF=mFinishingActivities.size()) > 0) {
3512 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3513 mFinishingActivities.clear();
3514 }
3515 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3516 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3517 mService.mCancelledThumbnails.clear();
3518 }
3519
3520 if (mMainStack) {
3521 booting = mService.mBooting;
3522 mService.mBooting = false;
3523 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003524 if (mStartingUsers.size() > 0) {
3525 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3526 mStartingUsers.clear();
3527 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003528 }
3529
3530 int i;
3531
3532 // Send thumbnail if requested.
3533 if (sendThumbnail != null) {
3534 try {
3535 sendThumbnail.requestThumbnail(token);
3536 } catch (Exception e) {
3537 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3538 mService.sendPendingThumbnail(null, token, null, null, true);
3539 }
3540 }
3541
3542 // Stop any activities that are scheduled to do so but have been
3543 // waiting for the next one to start.
3544 for (i=0; i<NS; i++) {
3545 ActivityRecord r = (ActivityRecord)stops.get(i);
3546 synchronized (mService) {
3547 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003548 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003549 } else {
3550 stopActivityLocked(r);
3551 }
3552 }
3553 }
3554
3555 // Finish any activities that are scheduled to do so but have been
3556 // waiting for the next one to start.
3557 for (i=0; i<NF; i++) {
3558 ActivityRecord r = (ActivityRecord)finishes.get(i);
3559 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003560 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003561 }
3562 }
3563
3564 // Report back to any thumbnail receivers.
3565 for (i=0; i<NT; i++) {
3566 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3567 mService.sendPendingThumbnail(r, null, null, null, true);
3568 }
3569
3570 if (booting) {
3571 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003572 } else if (startingUsers != null) {
3573 for (i=0; i<startingUsers.size(); i++) {
3574 mService.finishUserSwitch(startingUsers.get(i));
3575 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003576 }
3577
3578 mService.trimApplications();
3579 //dump();
3580 //mWindowManager.dump();
3581
3582 if (enableScreen) {
3583 mService.enableScreenAfterBoot();
3584 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003585
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003586 if (activityRemoved) {
3587 resumeTopActivityLocked(null);
3588 }
3589
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003590 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003591 }
3592
3593 /**
3594 * @return Returns true if the activity is being finished, false if for
3595 * some reason it is being left as-is.
3596 */
3597 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003598 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003599 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003600 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003601 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003602 + ", result=" + resultCode + ", data=" + resultData
3603 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003604 if (index < 0) {
3605 return false;
3606 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003607 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003608
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003609 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003610 return true;
3611 }
3612
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003613 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3614 ActivityRecord self = isInStackLocked(token);
3615 if (self == null) {
3616 return;
3617 }
3618
3619 int i;
3620 for (i=mHistory.size()-1; i>=0; i--) {
3621 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3622 if (r.resultTo == self && r.requestCode == requestCode) {
3623 if ((r.resultWho == null && resultWho == null) ||
3624 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3625 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003626 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003627 }
3628 }
3629 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003630 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003631 }
3632
3633 final boolean finishActivityAffinityLocked(IBinder token) {
3634 int index = indexOfTokenLocked(token);
3635 if (DEBUG_RESULTS) Slog.v(
3636 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3637 if (index < 0) {
3638 return false;
3639 }
3640 ActivityRecord r = mHistory.get(index);
3641
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003642 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003643 ActivityRecord cur = mHistory.get(index);
3644 if (cur.task != r.task) {
3645 break;
3646 }
3647 if (cur.taskAffinity == null && r.taskAffinity != null) {
3648 break;
3649 }
3650 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3651 break;
3652 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003653 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3654 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003655 index--;
3656 }
3657 return true;
3658 }
3659
Dianne Hackborn5c607432012-02-28 14:44:19 -08003660 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3661 // send the result
3662 ActivityRecord resultTo = r.resultTo;
3663 if (resultTo != null) {
3664 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3665 + " who=" + r.resultWho + " req=" + r.requestCode
3666 + " res=" + resultCode + " data=" + resultData);
3667 if (r.info.applicationInfo.uid > 0) {
3668 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3669 resultTo.packageName, resultData,
3670 resultTo.getUriPermissionsLocked());
3671 }
3672 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3673 resultData);
3674 r.resultTo = null;
3675 }
3676 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3677
3678 // Make sure this HistoryRecord is not holding on to other resources,
3679 // because clients have remote IPC references to this object so we
3680 // can't assume that will go away and want to avoid circular IPC refs.
3681 r.results = null;
3682 r.pendingResults = null;
3683 r.newIntents = null;
3684 r.icicle = null;
3685 }
3686
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003687 /**
3688 * @return Returns true if this activity has been removed from the history
3689 * list, or false if it is still in the list and will be removed later.
3690 */
3691 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003692 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3693 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003694 }
3695
3696 /**
3697 * @return Returns true if this activity has been removed from the history
3698 * list, or false if it is still in the list and will be removed later.
3699 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003700 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3701 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003702 if (r.finishing) {
3703 Slog.w(TAG, "Duplicate finish request for " + r);
3704 return false;
3705 }
3706
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003707 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003708 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003709 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003710 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003711 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003712 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003713 if (next.task == r.task) {
3714 if (r.frontOfTask) {
3715 // The next activity is now the front of the task.
3716 next.frontOfTask = true;
3717 }
3718 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3719 // If the caller asked that this activity (and all above it)
3720 // be cleared when the task is reset, don't lose that information,
3721 // but propagate it up to the next activity.
3722 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3723 }
3724 }
3725 }
3726
3727 r.pauseKeyDispatchingLocked();
3728 if (mMainStack) {
3729 if (mService.mFocusedActivity == r) {
3730 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3731 }
3732 }
3733
Dianne Hackborn5c607432012-02-28 14:44:19 -08003734 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003735
3736 if (mService.mPendingThumbnails.size() > 0) {
3737 // There are clients waiting to receive thumbnails so, in case
3738 // this is an activity that someone is waiting for, add it
3739 // to the pending list so we can correctly update the clients.
3740 mService.mCancelledThumbnails.add(r);
3741 }
3742
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003743 if (immediate) {
3744 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003745 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003746 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003747 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003748 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003749 if (DEBUG_TRANSITION) Slog.v(TAG,
3750 "Prepare close transition: finishing " + r);
3751 mService.mWindowManager.prepareAppTransition(endTask
3752 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003753 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003754
3755 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003756 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003757
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003758 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003759 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3760 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3761 startPausingLocked(false, false);
3762 }
3763
3764 } else if (r.state != ActivityState.PAUSING) {
3765 // If the activity is PAUSING, we will complete the finish once
3766 // it is done pausing; else we can just directly finish it here.
3767 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3768 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003769 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003770 } else {
3771 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3772 }
3773
3774 return false;
3775 }
3776
3777 private static final int FINISH_IMMEDIATELY = 0;
3778 private static final int FINISH_AFTER_PAUSE = 1;
3779 private static final int FINISH_AFTER_VISIBLE = 2;
3780
3781 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003782 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003783 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003784 if (index < 0) {
3785 return null;
3786 }
3787
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003788 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003789 }
3790
3791 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003792 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003793 // First things first: if this activity is currently visible,
3794 // and the resumed activity is not yet visible, then hold off on
3795 // finishing until the resumed one becomes visible.
3796 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3797 if (!mStoppingActivities.contains(r)) {
3798 mStoppingActivities.add(r);
3799 if (mStoppingActivities.size() > 3) {
3800 // If we already have a few activities waiting to stop,
3801 // then give up on things going idle and start clearing
3802 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003803 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003804 } else {
3805 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003806 }
3807 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003808 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3809 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003810 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003811 if (oomAdj) {
3812 mService.updateOomAdjLocked();
3813 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003814 return r;
3815 }
3816
3817 // make sure the record is cleaned out of other places.
3818 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003819 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003820 mWaitingVisibleActivities.remove(r);
3821 if (mResumedActivity == r) {
3822 mResumedActivity = null;
3823 }
3824 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003825 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003826 r.state = ActivityState.FINISHING;
3827
3828 if (mode == FINISH_IMMEDIATELY
3829 || prevState == ActivityState.STOPPED
3830 || prevState == ActivityState.INITIALIZING) {
3831 // If this activity is already stopped, we can just finish
3832 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003833 boolean activityRemoved = destroyActivityLocked(r, true,
3834 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003835 if (activityRemoved) {
3836 resumeTopActivityLocked(null);
3837 }
3838 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003839 } else {
3840 // Need to go through the full pause cycle to get this
3841 // activity into the stopped state and then finish it.
3842 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3843 mFinishingActivities.add(r);
3844 resumeTopActivityLocked(null);
3845 }
3846 return r;
3847 }
3848
3849 /**
3850 * Perform the common clean-up of an activity record. This is called both
3851 * as part of destroyActivityLocked() (when destroying the client-side
3852 * representation) and cleaning things up as a result of its hosting
3853 * processing going away, in which case there is no remaining client-side
3854 * state to destroy so only the cleanup here is needed.
3855 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003856 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3857 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003858 if (mResumedActivity == r) {
3859 mResumedActivity = null;
3860 }
3861 if (mService.mFocusedActivity == r) {
3862 mService.mFocusedActivity = null;
3863 }
3864
3865 r.configDestroy = false;
3866 r.frozenBeforeDestroy = false;
3867
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003868 if (setState) {
3869 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3870 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003871 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003872 }
3873
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003874 // Make sure this record is no longer in the pending finishes list.
3875 // This could happen, for example, if we are trimming activities
3876 // down to the max limit while they are still waiting to finish.
3877 mFinishingActivities.remove(r);
3878 mWaitingVisibleActivities.remove(r);
3879
3880 // Remove any pending results.
3881 if (r.finishing && r.pendingResults != null) {
3882 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3883 PendingIntentRecord rec = apr.get();
3884 if (rec != null) {
3885 mService.cancelIntentSenderLocked(rec, false);
3886 }
3887 }
3888 r.pendingResults = null;
3889 }
3890
3891 if (cleanServices) {
3892 cleanUpActivityServicesLocked(r);
3893 }
3894
3895 if (mService.mPendingThumbnails.size() > 0) {
3896 // There are clients waiting to receive thumbnails so, in case
3897 // this is an activity that someone is waiting for, add it
3898 // to the pending list so we can correctly update the clients.
3899 mService.mCancelledThumbnails.add(r);
3900 }
3901
3902 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003903 removeTimeoutsForActivityLocked(r);
3904 }
3905
3906 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003907 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003908 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003909 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003910 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003911 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003912 }
3913
Dianne Hackborn5c607432012-02-28 14:44:19 -08003914 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003915 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
3916 r.makeFinishing();
3917 if (DEBUG_ADD_REMOVE) {
3918 RuntimeException here = new RuntimeException("here");
3919 here.fillInStackTrace();
3920 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003921 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003922 mHistory.remove(r);
3923 r.takeFromHistory();
3924 removeTimeoutsForActivityLocked(r);
3925 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3926 + " (removed from history)");
3927 r.state = ActivityState.DESTROYED;
3928 r.app = null;
3929 mService.mWindowManager.removeAppToken(r.appToken);
3930 if (VALIDATE_TOKENS) {
3931 validateAppTokensLocked();
3932 }
3933 cleanUpActivityServicesLocked(r);
3934 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003935 }
3936
3937 /**
3938 * Perform clean-up of service connections in an activity record.
3939 */
3940 final void cleanUpActivityServicesLocked(ActivityRecord r) {
3941 // Throw away any services that have been bound by this activity.
3942 if (r.connections != null) {
3943 Iterator<ConnectionRecord> it = r.connections.iterator();
3944 while (it.hasNext()) {
3945 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07003946 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003947 }
3948 r.connections = null;
3949 }
3950 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003951
3952 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
3953 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
3954 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
3955 mHandler.sendMessage(msg);
3956 }
3957
Dianne Hackborn28695e02011-11-02 21:59:51 -07003958 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003959 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003960 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003961 for (int i=mHistory.size()-1; i>=0; i--) {
3962 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003963 if (r.finishing) {
3964 continue;
3965 }
3966 if (r.fullscreen) {
3967 lastIsOpaque = true;
3968 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003969 if (owner != null && r.app != owner) {
3970 continue;
3971 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003972 if (!lastIsOpaque) {
3973 continue;
3974 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003975 // We can destroy this one if we have its icicle saved and
3976 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003977 if (r.app != null && r != mResumedActivity && r != mPausingActivity
3978 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003979 && r.state != ActivityState.DESTROYING
3980 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07003981 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
3982 + " resumed=" + mResumedActivity
3983 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003984 if (destroyActivityLocked(r, true, oomAdj, reason)) {
3985 activityRemoved = true;
3986 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003987 }
3988 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003989 if (activityRemoved) {
3990 resumeTopActivityLocked(null);
3991 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003992 }
3993
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 /**
3995 * Destroy the current CLIENT SIDE instance of an activity. This may be
3996 * called both when actually finishing an activity, or when performing
3997 * a configuration switch where we destroy the current client-side object
3998 * but then create a new client-side object for this same HistoryRecord.
3999 */
4000 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004001 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004002 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004003 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004004 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4005 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004006 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004007 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004008
4009 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004010
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004011 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004012
4013 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004014
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004015 if (hadApp) {
4016 if (removeFromApp) {
4017 int idx = r.app.activities.indexOf(r);
4018 if (idx >= 0) {
4019 r.app.activities.remove(idx);
4020 }
4021 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4022 mService.mHeavyWeightProcess = null;
4023 mService.mHandler.sendEmptyMessage(
4024 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4025 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004026 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004027 // No longer have activities, so update oom adj.
4028 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004029 }
4030 }
4031
4032 boolean skipDestroy = false;
4033
4034 try {
4035 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004036 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004037 r.configChangeFlags);
4038 } catch (Exception e) {
4039 // We can just ignore exceptions here... if the process
4040 // has crashed, our death notification will clean things
4041 // up.
4042 //Slog.w(TAG, "Exception thrown during finish", e);
4043 if (r.finishing) {
4044 removeActivityFromHistoryLocked(r);
4045 removedFromHistory = true;
4046 skipDestroy = true;
4047 }
4048 }
4049
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004050 r.nowVisible = false;
4051
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004052 // If the activity is finishing, we need to wait on removing it
4053 // from the list to give it a chance to do its cleanup. During
4054 // that time it may make calls back with its token so we need to
4055 // be able to find it on the list and so we don't want to remove
4056 // it from the list yet. Otherwise, we can just immediately put
4057 // it in the destroyed state since we are not removing it from the
4058 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004059 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004060 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4061 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004062 r.state = ActivityState.DESTROYING;
4063 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4064 msg.obj = r;
4065 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4066 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004067 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4068 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004069 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004070 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004071 }
4072 } else {
4073 // remove this record from the history.
4074 if (r.finishing) {
4075 removeActivityFromHistoryLocked(r);
4076 removedFromHistory = true;
4077 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004078 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4079 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004080 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004081 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004082 }
4083 }
4084
4085 r.configChangeFlags = 0;
4086
4087 if (!mLRUActivities.remove(r) && hadApp) {
4088 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4089 }
4090
4091 return removedFromHistory;
4092 }
4093
4094 final void activityDestroyed(IBinder token) {
4095 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004096 final long origId = Binder.clearCallingIdentity();
4097 try {
4098 ActivityRecord r = ActivityRecord.forToken(token);
4099 if (r != null) {
4100 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004101 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004102
4103 int index = indexOfActivityLocked(r);
4104 if (index >= 0) {
4105 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004106 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004107 removeActivityFromHistoryLocked(r);
4108 }
4109 }
4110 resumeTopActivityLocked(null);
4111 } finally {
4112 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004113 }
4114 }
4115 }
4116
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004117 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app,
4118 String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004119 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004120 if (DEBUG_CLEANUP) Slog.v(
4121 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004122 + " with " + i + " entries");
4123 while (i > 0) {
4124 i--;
4125 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004126 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004128 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004129 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004130 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004131 }
4132 }
4133 }
4134
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004135 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4136 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4137 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4138 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4139 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4140 "mWaitingVisibleActivities");
4141 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4142
4143 boolean hasVisibleActivities = false;
4144
4145 // Clean out the history list.
4146 int i = mHistory.size();
4147 if (DEBUG_CLEANUP) Slog.v(
4148 TAG, "Removing app " + app + " from history with " + i + " entries");
4149 while (i > 0) {
4150 i--;
4151 ActivityRecord r = (ActivityRecord)mHistory.get(i);
4152 if (DEBUG_CLEANUP) Slog.v(
4153 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4154 if (r.app == app) {
4155 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4156 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4157 RuntimeException here = new RuntimeException("here");
4158 here.fillInStackTrace();
4159 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4160 + ": haveState=" + r.haveState
4161 + " stateNotNeeded=" + r.stateNotNeeded
4162 + " finishing=" + r.finishing
4163 + " state=" + r.state, here);
4164 }
4165 if (!r.finishing) {
4166 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4167 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4168 r.userId, System.identityHashCode(r),
4169 r.task.taskId, r.shortComponentName,
4170 "proc died without state saved");
4171 }
4172 removeActivityFromHistoryLocked(r);
4173
4174 } else {
4175 // We have the current state for this activity, so
4176 // it can be restarted later when needed.
4177 if (localLOGV) Slog.v(
4178 TAG, "Keeping entry, setting app to null");
4179 if (r.visible) {
4180 hasVisibleActivities = true;
4181 }
4182 r.app = null;
4183 r.nowVisible = false;
4184 if (!r.haveState) {
4185 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4186 "App died, clearing saved state of " + r);
4187 r.icicle = null;
4188 }
4189 }
4190
4191 r.stack.cleanUpActivityLocked(r, true, true);
4192 }
4193 }
4194
4195 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004196 }
4197
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004198 /**
4199 * Move the current home activity's task (if one exists) to the front
4200 * of the stack.
4201 */
4202 final void moveHomeToFrontLocked() {
4203 TaskRecord homeTask = null;
4204 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004205 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004206 if (hr.isHomeActivity) {
4207 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004208 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004209 }
4210 }
4211 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004212 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004213 }
4214 }
4215
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004216 final void updateTransitLocked(int transit, Bundle options) {
4217 if (options != null) {
4218 ActivityRecord r = topRunningActivityLocked(null);
4219 if (r != null && r.state != ActivityState.RESUMED) {
4220 r.updateOptionsLocked(options);
4221 } else {
4222 ActivityOptions.abort(options);
4223 }
4224 }
4225 mService.mWindowManager.prepareAppTransition(transit, false);
4226 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004227
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004228 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004229 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4230
4231 final int task = tr.taskId;
4232 int top = mHistory.size()-1;
4233
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004234 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004235 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004236 if (reason != null &&
4237 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4238 ActivityOptions.abort(options);
4239 } else {
4240 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4241 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004242 return;
4243 }
4244
Dianne Hackbornbe707852011-11-11 14:32:10 -08004245 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004246
4247 // Applying the affinities may have removed entries from the history,
4248 // so get the size again.
4249 top = mHistory.size()-1;
4250 int pos = top;
4251
4252 // Shift all activities with this task up to the top
4253 // of the stack, keeping them in the same internal order.
4254 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004255 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004256 if (localLOGV) Slog.v(
4257 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004258 if (r.task.taskId == task) {
4259 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004260 if (DEBUG_ADD_REMOVE) {
4261 RuntimeException here = new RuntimeException("here");
4262 here.fillInStackTrace();
4263 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4264 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004265 mHistory.remove(pos);
4266 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004267 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004268 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004269 }
4270 pos--;
4271 }
4272
4273 if (DEBUG_TRANSITION) Slog.v(TAG,
4274 "Prepare to front transition: task=" + tr);
4275 if (reason != null &&
4276 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004277 mService.mWindowManager.prepareAppTransition(
4278 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004279 ActivityRecord r = topRunningActivityLocked(null);
4280 if (r != null) {
4281 mNoAnimActivities.add(r);
4282 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004283 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004284 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004285 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004286 }
4287
4288 mService.mWindowManager.moveAppTokensToTop(moved);
4289 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004290 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004291 }
4292
4293 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004294 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004295 }
4296
4297 private final void finishTaskMoveLocked(int task) {
4298 resumeTopActivityLocked(null);
4299 }
4300
4301 /**
4302 * Worker method for rearranging history stack. Implements the function of moving all
4303 * activities for a specific task (gathering them if disjoint) into a single group at the
4304 * bottom of the stack.
4305 *
4306 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4307 * to premeptively cancel the move.
4308 *
4309 * @param task The taskId to collect and move to the bottom.
4310 * @return Returns true if the move completed, false if not.
4311 */
4312 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4313 Slog.i(TAG, "moveTaskToBack: " + task);
4314
4315 // If we have a watcher, preflight the move before committing to it. First check
4316 // for *other* available tasks, but if none are available, then try again allowing the
4317 // current task to be selected.
4318 if (mMainStack && mService.mController != null) {
4319 ActivityRecord next = topRunningActivityLocked(null, task);
4320 if (next == null) {
4321 next = topRunningActivityLocked(null, 0);
4322 }
4323 if (next != null) {
4324 // ask watcher if this is allowed
4325 boolean moveOK = true;
4326 try {
4327 moveOK = mService.mController.activityResuming(next.packageName);
4328 } catch (RemoteException e) {
4329 mService.mController = null;
4330 }
4331 if (!moveOK) {
4332 return false;
4333 }
4334 }
4335 }
4336
Dianne Hackbornbe707852011-11-11 14:32:10 -08004337 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004338
4339 if (DEBUG_TRANSITION) Slog.v(TAG,
4340 "Prepare to back transition: task=" + task);
4341
4342 final int N = mHistory.size();
4343 int bottom = 0;
4344 int pos = 0;
4345
4346 // Shift all activities with this task down to the bottom
4347 // of the stack, keeping them in the same internal order.
4348 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004349 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004350 if (localLOGV) Slog.v(
4351 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4352 if (r.task.taskId == task) {
4353 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004354 if (DEBUG_ADD_REMOVE) {
4355 RuntimeException here = new RuntimeException("here");
4356 here.fillInStackTrace();
4357 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4358 + bottom, here);
4359 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004360 mHistory.remove(pos);
4361 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004362 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004363 bottom++;
4364 }
4365 pos++;
4366 }
4367
4368 if (reason != null &&
4369 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004370 mService.mWindowManager.prepareAppTransition(
4371 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004372 ActivityRecord r = topRunningActivityLocked(null);
4373 if (r != null) {
4374 mNoAnimActivities.add(r);
4375 }
4376 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004377 mService.mWindowManager.prepareAppTransition(
4378 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004379 }
4380 mService.mWindowManager.moveAppTokensToBottom(moved);
4381 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004382 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004383 }
4384
4385 finishTaskMoveLocked(task);
4386 return true;
4387 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004388
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004389 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4390 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4391 ActivityRecord resumed = mResumedActivity;
4392 if (resumed != null && resumed.thumbHolder == tr) {
4393 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004394 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004395 if (info.mainThumbnail == null) {
4396 info.mainThumbnail = tr.lastThumbnail;
4397 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004398 return info;
4399 }
4400
Dianne Hackborn15491c62012-09-19 10:59:14 -07004401 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4402 ActivityRecord resumed = mResumedActivity;
4403 if (resumed != null && resumed.task == tr) {
4404 // This task is the current resumed task, we just need to take
4405 // a screenshot of it and return that.
4406 return resumed.stack.screenshotActivities(resumed);
4407 }
4408 // Return the information about the task, to figure out the top
4409 // thumbnail to return.
4410 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4411 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004412 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004413 } else {
4414 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
4415 }
4416 }
4417
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004418 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4419 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004420 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4421 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004422 if (taskRequired) {
4423 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4424 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004425 return null;
4426 }
4427
4428 if (subTaskIndex < 0) {
4429 // Just remove the entire task.
4430 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4431 return info.root;
4432 }
4433
4434 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004435 if (taskRequired) {
4436 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4437 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004438 return null;
4439 }
4440
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004441 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004442 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4443 performClearTaskAtIndexLocked(taskId, subtask.index);
4444 return subtask.activity;
4445 }
4446
4447 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004448 final TaskAccessInfo thumbs = new TaskAccessInfo();
4449 // How many different sub-thumbnails?
4450 final int NA = mHistory.size();
4451 int j = 0;
4452 ThumbnailHolder holder = null;
4453 while (j < NA) {
4454 ActivityRecord ar = mHistory.get(j);
4455 if (!ar.finishing && ar.task.taskId == taskId) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004456 thumbs.root = ar;
4457 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004458 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004459 if (holder != null) {
4460 thumbs.mainThumbnail = holder.lastThumbnail;
4461 }
4462 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004463 break;
4464 }
4465 j++;
4466 }
4467
4468 if (j >= NA) {
4469 return thumbs;
4470 }
4471
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004472 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4473 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004474 while (j < NA) {
4475 ActivityRecord ar = mHistory.get(j);
4476 j++;
4477 if (ar.finishing) {
4478 continue;
4479 }
4480 if (ar.task.taskId != taskId) {
4481 break;
4482 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004483 if (ar.thumbHolder != holder && holder != null) {
4484 thumbs.numSubThumbbails++;
4485 holder = ar.thumbHolder;
4486 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004487 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004488 sub.activity = ar;
4489 sub.index = j-1;
4490 subtasks.add(sub);
4491 }
4492 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004493 if (thumbs.numSubThumbbails > 0) {
4494 thumbs.retriever = new IThumbnailRetriever.Stub() {
4495 public Bitmap getThumbnail(int index) {
4496 if (index < 0 || index >= thumbs.subtasks.size()) {
4497 return null;
4498 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004499 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4500 ActivityRecord resumed = mResumedActivity;
4501 if (resumed != null && resumed.thumbHolder == sub.holder) {
4502 return resumed.stack.screenshotActivities(resumed);
4503 }
4504 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004505 }
4506 };
4507 }
4508 return thumbs;
4509 }
4510
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004511 private final void logStartActivity(int tag, ActivityRecord r,
4512 TaskRecord task) {
4513 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004514 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004515 r.shortComponentName, r.intent.getAction(),
4516 r.intent.getType(), r.intent.getDataString(),
4517 r.intent.getFlags());
4518 }
4519
4520 /**
4521 * Make sure the given activity matches the current configuration. Returns
4522 * false if the activity had to be destroyed. Returns true if the
4523 * configuration is the same, or the activity will remain running as-is
4524 * for whatever reason. Ensures the HistoryRecord is updated with the
4525 * correct configuration and all other bookkeeping is handled.
4526 */
4527 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4528 int globalChanges) {
4529 if (mConfigWillChange) {
4530 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4531 "Skipping config check (will change): " + r);
4532 return true;
4533 }
4534
4535 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4536 "Ensuring correct configuration: " + r);
4537
4538 // Short circuit: if the two configurations are the exact same
4539 // object (the common case), then there is nothing to do.
4540 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004541 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004542 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4543 "Configuration unchanged in " + r);
4544 return true;
4545 }
4546
4547 // We don't worry about activities that are finishing.
4548 if (r.finishing) {
4549 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4550 "Configuration doesn't matter in finishing " + r);
4551 r.stopFreezingScreenLocked(false);
4552 return true;
4553 }
4554
4555 // Okay we now are going to make this activity have the new config.
4556 // But then we need to figure out how it needs to deal with that.
4557 Configuration oldConfig = r.configuration;
4558 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004559
4560 // Determine what has changed. May be nothing, if this is a config
4561 // that has come back from the app after going idle. In that case
4562 // we just want to leave the official config object now in the
4563 // activity and do nothing else.
4564 final int changes = oldConfig.diff(newConfig);
4565 if (changes == 0 && !r.forceNewConfig) {
4566 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4567 "Configuration no differences in " + r);
4568 return true;
4569 }
4570
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004571 // If the activity isn't currently running, just leave the new
4572 // configuration and it will pick that up next time it starts.
4573 if (r.app == null || r.app.thread == null) {
4574 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4575 "Configuration doesn't matter not running " + r);
4576 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004577 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004578 return true;
4579 }
4580
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004581 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004582 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4583 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4584 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004585 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004586 + ", newConfig=" + newConfig);
4587 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004588 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004589 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4590 r.configChangeFlags |= changes;
4591 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004592 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004593 if (r.app == null || r.app.thread == null) {
4594 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004595 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004596 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004597 } else if (r.state == ActivityState.PAUSING) {
4598 // A little annoying: we are waiting for this activity to
4599 // finish pausing. Let's not do anything now, but just
4600 // flag that it needs to be restarted when done pausing.
4601 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004602 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004603 r.configDestroy = true;
4604 return true;
4605 } else if (r.state == ActivityState.RESUMED) {
4606 // Try to optimize this case: the configuration is changing
4607 // and we need to restart the top, resumed activity.
4608 // Instead of doing the normal handshaking, just say
4609 // "restart!".
4610 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004611 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004612 relaunchActivityLocked(r, r.configChangeFlags, true);
4613 r.configChangeFlags = 0;
4614 } else {
4615 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004616 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004617 relaunchActivityLocked(r, r.configChangeFlags, false);
4618 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004619 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004620
4621 // All done... tell the caller we weren't able to keep this
4622 // activity around.
4623 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004624 }
4625
4626 // Default case: the activity can handle this new configuration, so
4627 // hand it over. Note that we don't need to give it the new
4628 // configuration, since we always send configuration changes to all
4629 // process when they happen so it can just use whatever configuration
4630 // it last got.
4631 if (r.app != null && r.app.thread != null) {
4632 try {
4633 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004634 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004635 } catch (RemoteException e) {
4636 // If process died, whatever.
4637 }
4638 }
4639 r.stopFreezingScreenLocked(false);
4640
4641 return true;
4642 }
4643
4644 private final boolean relaunchActivityLocked(ActivityRecord r,
4645 int changes, boolean andResume) {
4646 List<ResultInfo> results = null;
4647 List<Intent> newIntents = null;
4648 if (andResume) {
4649 results = r.results;
4650 newIntents = r.newIntents;
4651 }
4652 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4653 + " with results=" + results + " newIntents=" + newIntents
4654 + " andResume=" + andResume);
4655 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004656 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004657 r.task.taskId, r.shortComponentName);
4658
4659 r.startFreezingScreenLocked(r.app, 0);
4660
4661 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004662 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4663 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4664 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004665 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004666 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004667 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004668 // Note: don't need to call pauseIfSleepingLocked() here, because
4669 // the caller will only pass in 'andResume' if this activity is
4670 // currently resumed, which implies we aren't sleeping.
4671 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004672 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004673 }
4674
4675 if (andResume) {
4676 r.results = null;
4677 r.newIntents = null;
4678 if (mMainStack) {
4679 mService.reportResumedActivityLocked(r);
4680 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004681 r.state = ActivityState.RESUMED;
4682 } else {
4683 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4684 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004685 }
4686
4687 return true;
4688 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004689
4690 public void dismissKeyguardOnNextActivityLocked() {
4691 mDismissKeyguardOnNextActivity = true;
4692 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004693}