blob: 0e01e4cb2a74825609db0fa634fcc21dde07c1b0 [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;
Craig Mautnerb12428a2012-12-20 16:07:06 -080048import android.graphics.Bitmap.Config;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070049import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070050import android.os.Bundle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070051import android.os.Handler;
52import android.os.IBinder;
Zoran Marcetaf958b322012-08-09 20:27:12 +090053import android.os.Looper;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070054import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070055import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.PowerManager;
57import android.os.RemoteException;
58import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070059import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070060import android.util.EventLog;
61import android.util.Log;
62import android.util.Slog;
Craig Mautner59c00972012-07-30 12:10:24 -070063import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070064import android.view.WindowManagerPolicy;
65
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070066import java.io.IOException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070067import java.lang.ref.WeakReference;
68import java.util.ArrayList;
69import java.util.Iterator;
70import java.util.List;
71
72/**
73 * State and management of a single stack of activities.
74 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070075final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070077 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070078 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
79 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
80 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
81 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
82 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
83 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
84 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
85 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
Dianne Hackborncc5a0552012-10-01 16:32:39 -070086 static final boolean DEBUG_CLEANUP = ActivityManagerService.DEBUG_CLEANUP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070087
Dianne Hackbornce86ba82011-07-13 19:33:41 -070088 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070089 static final boolean DEBUG_ADD_REMOVE = false;
90 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070091
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070092 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
93
94 // How long we wait until giving up on the last activity telling us it
95 // is idle.
96 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -070097
98 // Ticks during which we check progress while waiting for an app to launch.
99 static final int LAUNCH_TICK = 500;
100
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700101 // How long we wait until giving up on the last activity to pause. This
102 // is short because it directly impacts the responsiveness of starting the
103 // next activity.
104 static final int PAUSE_TIMEOUT = 500;
105
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700106 // How long we wait for the activity to tell us it has stopped before
107 // giving up. This is a good amount of time because we really need this
108 // from the application in order to get its saved state.
109 static final int STOP_TIMEOUT = 10*1000;
110
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800111 // How long we can hold the sleep wake lock before giving up.
112 static final int SLEEP_TIMEOUT = 5*1000;
113
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700114 // How long we can hold the launch wake lock before giving up.
115 static final int LAUNCH_TIMEOUT = 10*1000;
116
117 // How long we wait until giving up on an activity telling us it has
118 // finished destroying itself.
119 static final int DESTROY_TIMEOUT = 10*1000;
120
121 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800122 // disabled.
123 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700124
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700125 // How long between activity launches that we consider safe to not warn
126 // the user about an unexpected activity being launched on top.
127 static final long START_WARN_TIME = 5*1000;
128
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700129 // Set to false to disable the preview that is shown while a new activity
130 // is being started.
131 static final boolean SHOW_APP_STARTING_PREVIEW = true;
132
133 enum ActivityState {
134 INITIALIZING,
135 RESUMED,
136 PAUSING,
137 PAUSED,
138 STOPPING,
139 STOPPED,
140 FINISHING,
141 DESTROYING,
142 DESTROYED
143 }
144
145 final ActivityManagerService mService;
146 final boolean mMainStack;
147
148 final Context mContext;
149
150 /**
151 * The back history of all previous (and possibly still
152 * running) activities. It contains HistoryRecord objects.
153 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700154 final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800155
156 /**
157 * Used for validating app tokens with window manager.
158 */
159 final ArrayList<IBinder> mValidateAppTokens = new ArrayList<IBinder>();
160
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700161 /**
162 * List of running activities, sorted by recent usage.
163 * The first entry in the list is the least recently used.
164 * It contains HistoryRecord objects.
165 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700166 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700167
168 /**
169 * List of activities that are waiting for a new activity
170 * to become visible before completing whatever operation they are
171 * supposed to do.
172 */
173 final ArrayList<ActivityRecord> mWaitingVisibleActivities
174 = new ArrayList<ActivityRecord>();
175
176 /**
177 * List of activities that are ready to be stopped, but waiting
178 * for the next activity to settle down before doing so. It contains
179 * HistoryRecord objects.
180 */
181 final ArrayList<ActivityRecord> mStoppingActivities
182 = new ArrayList<ActivityRecord>();
183
184 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800185 * List of activities that are in the process of going to sleep.
186 */
187 final ArrayList<ActivityRecord> mGoingToSleepActivities
188 = new ArrayList<ActivityRecord>();
189
190 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700191 * Animations that for the current transition have requested not to
192 * be considered for the transition animation.
193 */
194 final ArrayList<ActivityRecord> mNoAnimActivities
195 = new ArrayList<ActivityRecord>();
196
197 /**
198 * List of activities that are ready to be finished, but waiting
199 * for the previous activity to settle down before doing so. It contains
200 * HistoryRecord objects.
201 */
202 final ArrayList<ActivityRecord> mFinishingActivities
203 = new ArrayList<ActivityRecord>();
204
205 /**
206 * List of people waiting to find out about the next launched activity.
207 */
208 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
209 = new ArrayList<IActivityManager.WaitResult>();
210
211 /**
212 * List of people waiting to find out about the next visible activity.
213 */
214 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
215 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700216
217 final ArrayList<UserStartedState> mStartingUsers
218 = new ArrayList<UserStartedState>();
219
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700220 /**
221 * Set when the system is going to sleep, until we have
222 * successfully paused the current activity and released our wake lock.
223 * At that point the system is allowed to actually sleep.
224 */
225 final PowerManager.WakeLock mGoingToSleep;
226
227 /**
228 * We don't want to allow the device to go to sleep while in the process
229 * of launching an activity. This is primarily to allow alarm intent
230 * receivers to launch an activity and get that to run before the device
231 * goes back to sleep.
232 */
233 final PowerManager.WakeLock mLaunchingActivity;
234
235 /**
236 * When we are in the process of pausing an activity, before starting the
237 * next one, this variable holds the activity that is currently being paused.
238 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800239 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700240
241 /**
242 * This is the last activity that we put into the paused state. This is
243 * used to determine if we need to do an activity transition while sleeping,
244 * when we normally hold the top activity paused.
245 */
246 ActivityRecord mLastPausedActivity = null;
247
248 /**
249 * Current activity that is resumed, or null if there is none.
250 */
251 ActivityRecord mResumedActivity = null;
252
253 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700254 * This is the last activity that has been started. It is only used to
255 * identify when multiple activities are started at once so that the user
256 * can be warned they may not be in the activity they think they are.
257 */
258 ActivityRecord mLastStartedActivity = null;
259
260 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700261 * Set when we know we are going to be calling updateConfiguration()
262 * soon, so want to skip intermediate config checks.
263 */
264 boolean mConfigWillChange;
265
266 /**
267 * Set to indicate whether to issue an onUserLeaving callback when a
268 * newly launched activity is being brought in front of us.
269 */
270 boolean mUserLeaving = false;
271
272 long mInitialStartTime = 0;
273
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800274 /**
275 * Set when we have taken too long waiting to go to sleep.
276 */
277 boolean mSleepTimeout = false;
278
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700279 /**
280 * Dismiss the keyguard after the next activity is displayed?
281 */
282 boolean mDismissKeyguardOnNextActivity = false;
283
Craig Mautnerb12428a2012-12-20 16:07:06 -0800284 /**
285 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
286 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
287 */
288 private ActivityRecord mLastScreenshotActivity = null;
289 private Bitmap mLastScreenshotBitmap = null;
290
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800291 int mThumbnailWidth = -1;
292 int mThumbnailHeight = -1;
293
Amith Yamasani742a6712011-05-04 14:49:28 -0700294 private int mCurrentUser;
295
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800296 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
297 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
298 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
299 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
300 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
301 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
302 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700303 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700304 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700305 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
306
307 static class ScheduleDestroyArgs {
308 final ProcessRecord mOwner;
309 final boolean mOomAdj;
310 final String mReason;
311 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
312 mOwner = owner;
313 mOomAdj = oomAdj;
314 mReason = reason;
315 }
316 }
317
Zoran Marcetaf958b322012-08-09 20:27:12 +0900318 final Handler mHandler;
319
320 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700321 //public Handler() {
322 // if (localLOGV) Slog.v(TAG, "Handler started!");
323 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900324 public ActivityStackHandler(Looper looper) {
325 super(looper);
326 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700327
Zoran Marcetaf958b322012-08-09 20:27:12 +0900328 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700329 public void handleMessage(Message msg) {
330 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800331 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700332 synchronized (mService) {
333 if (mService.isSleeping()) {
334 Slog.w(TAG, "Sleep timeout! Sleeping now.");
335 mSleepTimeout = true;
336 checkReadyForSleepLocked();
337 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800338 }
339 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700340 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800341 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700342 // We don't at this point know if the activity is fullscreen,
343 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800344 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700345 synchronized (mService) {
346 if (r.app != null) {
347 mService.logAppTooSlow(r.app, r.pauseTime,
348 "pausing " + r);
349 }
350 }
351
Dianne Hackbornbe707852011-11-11 14:32:10 -0800352 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700353 } break;
354 case IDLE_TIMEOUT_MSG: {
355 if (mService.mDidDexOpt) {
356 mService.mDidDexOpt = false;
357 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
358 nmsg.obj = msg.obj;
359 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
360 return;
361 }
362 // We don't at this point know if the activity is fullscreen,
363 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800364 ActivityRecord r = (ActivityRecord)msg.obj;
365 Slog.w(TAG, "Activity idle timeout for " + r);
366 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700368 case LAUNCH_TICK_MSG: {
369 ActivityRecord r = (ActivityRecord)msg.obj;
370 synchronized (mService) {
371 if (r.continueLaunchTickingLocked()) {
372 mService.logAppTooSlow(r.app, r.launchTickTime,
373 "launching " + r);
374 }
375 }
376 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700377 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800378 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700379 // We don't at this point know if the activity is fullscreen,
380 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800381 Slog.w(TAG, "Activity destroy timeout for " + r);
382 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700383 } break;
384 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800385 ActivityRecord r = (ActivityRecord)msg.obj;
386 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700387 } break;
388 case LAUNCH_TIMEOUT_MSG: {
389 if (mService.mDidDexOpt) {
390 mService.mDidDexOpt = false;
391 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
392 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
393 return;
394 }
395 synchronized (mService) {
396 if (mLaunchingActivity.isHeld()) {
397 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
398 mLaunchingActivity.release();
399 }
400 }
401 } break;
402 case RESUME_TOP_ACTIVITY_MSG: {
403 synchronized (mService) {
404 resumeTopActivityLocked(null);
405 }
406 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700407 case STOP_TIMEOUT_MSG: {
408 ActivityRecord r = (ActivityRecord)msg.obj;
409 // We don't at this point know if the activity is fullscreen,
410 // so we need to be conservative and assume it isn't.
411 Slog.w(TAG, "Activity stop timeout for " + r);
412 synchronized (mService) {
413 if (r.isInHistory()) {
414 activityStoppedLocked(r, null, null, null);
415 }
416 }
417 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700418 case DESTROY_ACTIVITIES_MSG: {
419 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
420 synchronized (mService) {
421 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
422 }
423 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700424 }
425 }
426 };
427
Zoran Marcetaf958b322012-08-09 20:27:12 +0900428 ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper) {
429 mHandler = new ActivityStackHandler(looper);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700430 mService = service;
431 mContext = context;
432 mMainStack = mainStack;
433 PowerManager pm =
434 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
435 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
436 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
437 mLaunchingActivity.setReferenceCounted(false);
438 }
Craig Mautner5962b122012-10-05 14:45:52 -0700439
440 private boolean okToShow(ActivityRecord r) {
441 return r.userId == mCurrentUser
442 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
443 }
444
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700445 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
446 int i = mHistory.size()-1;
447 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700448 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700449 if (!r.finishing && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700450 return r;
451 }
452 i--;
453 }
454 return null;
455 }
456
457 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
458 int i = mHistory.size()-1;
459 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700460 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700461 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700462 return r;
463 }
464 i--;
465 }
466 return null;
467 }
468
469 /**
470 * This is a simplified version of topRunningActivityLocked that provides a number of
471 * optional skip-over modes. It is intended for use with the ActivityController hook only.
472 *
473 * @param token If non-null, any history records matching this token will be skipped.
474 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
475 *
476 * @return Returns the HistoryRecord of the next activity on the stack.
477 */
478 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
479 int i = mHistory.size()-1;
480 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700481 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700482 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700483 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
Craig Mautner5962b122012-10-05 14:45:52 -0700484 && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700485 return r;
486 }
487 i--;
488 }
489 return null;
490 }
491
492 final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800493 return mHistory.indexOf(ActivityRecord.forToken(token));
494 }
495
496 final int indexOfActivityLocked(ActivityRecord r) {
497 return mHistory.indexOf(r);
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700498 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700499
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700500 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800501 ActivityRecord r = ActivityRecord.forToken(token);
502 if (mHistory.contains(r)) {
503 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700504 }
505 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700506 }
507
508 private final boolean updateLRUListLocked(ActivityRecord r) {
509 final boolean hadit = mLRUActivities.remove(r);
510 mLRUActivities.add(r);
511 return hadit;
512 }
513
514 /**
515 * Returns the top activity in any existing task matching the given
516 * Intent. Returns null if no such task is found.
517 */
518 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
519 ComponentName cls = intent.getComponent();
520 if (info.targetActivity != null) {
521 cls = new ComponentName(info.packageName, info.targetActivity);
522 }
523
524 TaskRecord cp = null;
525
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700526 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700527 final int N = mHistory.size();
528 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700529 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700530 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700531 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
532 cp = r.task;
533 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
534 // + "/aff=" + r.task.affinity + " to new cls="
535 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
536 if (r.task.affinity != null) {
537 if (r.task.affinity.equals(info.taskAffinity)) {
538 //Slog.i(TAG, "Found matching affinity!");
539 return r;
540 }
541 } else if (r.task.intent != null
542 && r.task.intent.getComponent().equals(cls)) {
543 //Slog.i(TAG, "Found matching class!");
544 //dump();
545 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
546 return r;
547 } else if (r.task.affinityIntent != null
548 && r.task.affinityIntent.getComponent().equals(cls)) {
549 //Slog.i(TAG, "Found matching class!");
550 //dump();
551 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
552 return r;
553 }
554 }
555 }
556
557 return null;
558 }
559
560 /**
561 * Returns the first activity (starting from the top of the stack) that
562 * is the same as the given activity. Returns null if no such activity
563 * is found.
564 */
565 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
566 ComponentName cls = intent.getComponent();
567 if (info.targetActivity != null) {
568 cls = new ComponentName(info.packageName, info.targetActivity);
569 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700570 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700571
572 final int N = mHistory.size();
573 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700574 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700575 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700576 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700577 //Slog.i(TAG, "Found matching class!");
578 //dump();
579 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
580 return r;
581 }
582 }
583 }
584
585 return null;
586 }
587
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700588 final void showAskCompatModeDialogLocked(ActivityRecord r) {
589 Message msg = Message.obtain();
590 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
591 msg.obj = r.task.askedCompatMode ? null : r;
592 mService.mHandler.sendMessage(msg);
593 }
594
Amith Yamasani742a6712011-05-04 14:49:28 -0700595 /*
596 * Move the activities around in the stack to bring a user to the foreground.
597 * @return whether there are any activities for the specified user.
598 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700599 final boolean switchUserLocked(int userId, UserStartedState uss) {
600 mCurrentUser = userId;
601 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700602
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700603 // Only one activity? Nothing to do...
604 if (mHistory.size() < 2)
605 return false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700606
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700607 boolean haveActivities = false;
608 // Check if the top activity is from the new user.
609 ActivityRecord top = mHistory.get(mHistory.size() - 1);
610 if (top.userId == userId) return true;
611 // Otherwise, move the user's activities to the top.
612 int N = mHistory.size();
613 int i = 0;
614 while (i < N) {
615 ActivityRecord r = mHistory.get(i);
616 if (r.userId == userId) {
617 ActivityRecord moveToTop = mHistory.remove(i);
618 mHistory.add(moveToTop);
619 // No need to check the top one now
620 N--;
621 haveActivities = true;
622 } else {
623 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700624 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700625 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700626 // Transition from the old top to the new top
627 resumeTopActivityLocked(top);
628 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700629 }
630
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700631 final boolean realStartActivityLocked(ActivityRecord r,
632 ProcessRecord app, boolean andResume, boolean checkConfig)
633 throws RemoteException {
634
635 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800636 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700637
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700638 // schedule launch ticks to collect information about slow apps.
639 r.startLaunchTickingLocked();
640
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700641 // Have the window manager re-evaluate the orientation of
642 // the screen based on the new activity order. Note that
643 // as a result of this, it can call back into the activity
644 // manager with a new orientation. We don't care about that,
645 // because the activity is not currently running so we are
646 // just restarting it anyway.
647 if (checkConfig) {
648 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
649 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800650 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800651 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700652 }
653
654 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700655 app.waitingToKill = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700656
657 if (localLOGV) Slog.v(TAG, "Launching: " + r);
658
659 int idx = app.activities.indexOf(r);
660 if (idx < 0) {
661 app.activities.add(r);
662 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700663 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700664
665 try {
666 if (app.thread == null) {
667 throw new RemoteException();
668 }
669 List<ResultInfo> results = null;
670 List<Intent> newIntents = null;
671 if (andResume) {
672 results = r.results;
673 newIntents = r.newIntents;
674 }
675 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
676 + " icicle=" + r.icicle
677 + " with results=" + results + " newIntents=" + newIntents
678 + " andResume=" + andResume);
679 if (andResume) {
680 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700681 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700682 r.task.taskId, r.shortComponentName);
683 }
684 if (r.isHomeActivity) {
685 mService.mHomeProcess = app;
686 }
687 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800688 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400689 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700690 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700691 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700692 String profileFile = null;
693 ParcelFileDescriptor profileFd = null;
694 boolean profileAutoStop = false;
695 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
696 if (mService.mProfileProc == null || mService.mProfileProc == app) {
697 mService.mProfileProc = app;
698 profileFile = mService.mProfileFile;
699 profileFd = mService.mProfileFd;
700 profileAutoStop = mService.mAutoStopProfiler;
701 }
702 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700703 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700704 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700705 if (profileFd != null) {
706 try {
707 profileFd = profileFd.dup();
708 } catch (IOException e) {
709 profileFd = null;
710 }
711 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800712 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800713 System.identityHashCode(r), r.info,
714 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700715 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700716 mService.isNextTransitionForward(), profileFile, profileFd,
717 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700718
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700719 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700720 // This may be a heavy-weight process! Note that the package
721 // manager will ensure that only activity can run in the main
722 // process of the .apk, which is the only thing that will be
723 // considered heavy-weight.
724 if (app.processName.equals(app.info.packageName)) {
725 if (mService.mHeavyWeightProcess != null
726 && mService.mHeavyWeightProcess != app) {
727 Log.w(TAG, "Starting new heavy weight process " + app
728 + " when already running "
729 + mService.mHeavyWeightProcess);
730 }
731 mService.mHeavyWeightProcess = app;
732 Message msg = mService.mHandler.obtainMessage(
733 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
734 msg.obj = r;
735 mService.mHandler.sendMessage(msg);
736 }
737 }
738
739 } catch (RemoteException e) {
740 if (r.launchFailed) {
741 // This is the second time we failed -- finish activity
742 // and give up.
743 Slog.e(TAG, "Second failure launching "
744 + r.intent.getComponent().flattenToShortString()
745 + ", giving up", e);
746 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800747 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700748 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700749 return false;
750 }
751
752 // This is the first time we failed -- restart process and
753 // retry.
754 app.activities.remove(r);
755 throw e;
756 }
757
758 r.launchFailed = false;
759 if (updateLRUListLocked(r)) {
760 Slog.w(TAG, "Activity " + r
761 + " being launched, but already in LRU list");
762 }
763
764 if (andResume) {
765 // As part of the process of launching, ActivityThread also performs
766 // a resume.
767 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700768 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
769 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700770 r.stopped = false;
771 mResumedActivity = r;
772 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800773 if (mMainStack) {
774 mService.addRecentTaskLocked(r.task);
775 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700776 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800777 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700778 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700779 } else {
780 // This activity is not starting in the resumed state... which
781 // should look like we asked it to pause+stop (but remain visible),
782 // and it has done so and reported back the current icicle and
783 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700784 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
785 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700786 r.state = ActivityState.STOPPED;
787 r.stopped = true;
788 }
789
790 // Launch the new version setup screen if needed. We do this -after-
791 // launching the initial activity (that is, home), so that it can have
792 // a chance to initialize itself while in the background, making the
793 // switch back to it faster and look better.
794 if (mMainStack) {
795 mService.startSetupActivityLocked();
796 }
797
798 return true;
799 }
800
801 private final void startSpecificActivityLocked(ActivityRecord r,
802 boolean andResume, boolean checkConfig) {
803 // Is this activity's application already running?
804 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
805 r.info.applicationInfo.uid);
806
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700807 if (r.launchTime == 0) {
808 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700809 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700810 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700811 }
812 } else if (mInitialStartTime == 0) {
813 mInitialStartTime = SystemClock.uptimeMillis();
814 }
815
816 if (app != null && app.thread != null) {
817 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700818 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700819 realStartActivityLocked(r, app, andResume, checkConfig);
820 return;
821 } catch (RemoteException e) {
822 Slog.w(TAG, "Exception when starting activity "
823 + r.intent.getComponent().flattenToShortString(), e);
824 }
825
826 // If a dead object exception was thrown -- fall through to
827 // restart the application.
828 }
829
830 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800831 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700832 }
833
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800834 void stopIfSleepingLocked() {
835 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700836 if (!mGoingToSleep.isHeld()) {
837 mGoingToSleep.acquire();
838 if (mLaunchingActivity.isHeld()) {
839 mLaunchingActivity.release();
840 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
841 }
842 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800843 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
844 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
845 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
846 checkReadyForSleepLocked();
847 }
848 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700849
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800850 void awakeFromSleepingLocked() {
851 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
852 mSleepTimeout = false;
853 if (mGoingToSleep.isHeld()) {
854 mGoingToSleep.release();
855 }
856 // Ensure activities are no longer sleeping.
857 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700858 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800859 r.setSleeping(false);
860 }
861 mGoingToSleepActivities.clear();
862 }
863
864 void activitySleptLocked(ActivityRecord r) {
865 mGoingToSleepActivities.remove(r);
866 checkReadyForSleepLocked();
867 }
868
869 void checkReadyForSleepLocked() {
870 if (!mService.isSleeping()) {
871 // Do not care.
872 return;
873 }
874
875 if (!mSleepTimeout) {
876 if (mResumedActivity != null) {
877 // Still have something resumed; can't sleep until it is paused.
878 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700879 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
880 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800881 return;
882 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800883 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800884 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800885 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800886 return;
887 }
888
889 if (mStoppingActivities.size() > 0) {
890 // Still need to tell some activities to stop; can't sleep yet.
891 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
892 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700893 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800894 return;
895 }
896
897 ensureActivitiesVisibleLocked(null, 0);
898
899 // Make sure any stopped but visible activities are now sleeping.
900 // This ensures that the activity's onStop() is called.
901 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700902 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800903 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
904 r.setSleeping(true);
905 }
906 }
907
908 if (mGoingToSleepActivities.size() > 0) {
909 // Still need to tell some activities to sleep; can't sleep yet.
910 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
911 + mGoingToSleepActivities.size() + " activities");
912 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700913 }
914 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800915
916 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
917
918 if (mGoingToSleep.isHeld()) {
919 mGoingToSleep.release();
920 }
921 if (mService.mShuttingDown) {
922 mService.notifyAll();
923 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700924 }
Craig Mautner59c00972012-07-30 12:10:24 -0700925
Dianne Hackbornd2835932010-12-13 16:28:46 -0800926 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800927 if (who.noDisplay) {
928 return null;
929 }
930
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800931 Resources res = mService.mContext.getResources();
932 int w = mThumbnailWidth;
933 int h = mThumbnailHeight;
934 if (w < 0) {
935 mThumbnailWidth = w =
936 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
937 mThumbnailHeight = h =
938 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
939 }
940
941 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -0800942 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
943 || mLastScreenshotBitmap.getWidth() != w
944 || mLastScreenshotBitmap.getHeight() != h) {
945 mLastScreenshotActivity = who;
946 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
947 who.appToken, Display.DEFAULT_DISPLAY, w, h);
948 }
949 if (mLastScreenshotBitmap != null) {
950 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
951 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800952 }
953 return null;
954 }
955
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700956 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800957 if (mPausingActivity != null) {
958 RuntimeException e = new RuntimeException();
959 Slog.e(TAG, "Trying to pause when pause is already pending for "
960 + mPausingActivity, e);
961 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700962 ActivityRecord prev = mResumedActivity;
963 if (prev == null) {
964 RuntimeException e = new RuntimeException();
965 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
966 resumeTopActivityLocked(null);
967 return;
968 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700969 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
970 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700971 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800972 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700973 mLastPausedActivity = prev;
974 prev.state = ActivityState.PAUSING;
975 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -0700976 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700977
978 mService.updateCpuStats();
979
980 if (prev.app != null && prev.app.thread != null) {
981 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
982 try {
983 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700984 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700985 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800986 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
987 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700988 if (mMainStack) {
989 mService.updateUsageStats(prev, false);
990 }
991 } catch (Exception e) {
992 // Ignore exception, if process died other code will cleanup.
993 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800994 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700995 mLastPausedActivity = null;
996 }
997 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800998 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700999 mLastPausedActivity = null;
1000 }
1001
1002 // If we are not going to sleep, we want to ensure the device is
1003 // awake until the next activity is started.
1004 if (!mService.mSleeping && !mService.mShuttingDown) {
1005 mLaunchingActivity.acquire();
1006 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1007 // To be safe, don't allow the wake lock to be held for too long.
1008 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1009 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1010 }
1011 }
1012
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001013
1014 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001015 // Have the window manager pause its key dispatching until the new
1016 // activity has started. If we're pausing the activity just because
1017 // the screen is being turned off and the UI is sleeping, don't interrupt
1018 // key dispatch; the same activity will pick it up again on wakeup.
1019 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001020 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001021 } else {
1022 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1023 }
1024
1025 // Schedule a pause timeout in case the app doesn't respond.
1026 // We don't give it much time because this directly impacts the
1027 // responsiveness seen by the user.
1028 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1029 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001030 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001031 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1032 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1033 } else {
1034 // This activity failed to schedule the
1035 // pause, so just treat it as being paused now.
1036 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001037 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001038 }
1039 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001040
1041 final void activityResumed(IBinder token) {
1042 ActivityRecord r = null;
1043
1044 synchronized (mService) {
1045 int index = indexOfTokenLocked(token);
1046 if (index >= 0) {
1047 r = mHistory.get(index);
1048 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1049 r.icicle = null;
1050 r.haveState = false;
1051 }
1052 }
1053 }
1054
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001055 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001056 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001057 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001058
1059 ActivityRecord r = null;
1060
1061 synchronized (mService) {
1062 int index = indexOfTokenLocked(token);
1063 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001064 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001065 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001066 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001067 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1068 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001069 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001070 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001071 } else {
1072 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001073 r.userId, System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001074 mPausingActivity != null
1075 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001076 }
1077 }
1078 }
1079 }
1080
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001081 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1082 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001083 if (r.state != ActivityState.STOPPING) {
1084 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1085 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1086 return;
1087 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001088 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001089 if (icicle != null) {
1090 // If icicle is null, this is happening due to a timeout, so we
1091 // haven't really saved the state.
1092 r.icicle = icicle;
1093 r.haveState = true;
1094 r.updateThumbnail(thumbnail, description);
1095 }
1096 if (!r.stopped) {
1097 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1098 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1099 r.stopped = true;
1100 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001101 if (r.finishing) {
1102 r.clearOptionsLocked();
1103 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001104 if (r.configDestroy) {
1105 destroyActivityLocked(r, true, false, "stop-config");
1106 resumeTopActivityLocked(null);
1107 } else {
1108 // Now that this process has stopped, we may want to consider
1109 // it to be the previous app to try to keep around in case
1110 // the user wants to return to it.
1111 ProcessRecord fgApp = null;
1112 if (mResumedActivity != null) {
1113 fgApp = mResumedActivity.app;
1114 } else if (mPausingActivity != null) {
1115 fgApp = mPausingActivity.app;
1116 }
1117 if (r.app != null && fgApp != null && r.app != fgApp
1118 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1119 && r.app != mService.mHomeProcess) {
1120 mService.mPreviousProcess = r.app;
1121 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1122 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001123 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001124 }
1125 }
1126 }
1127
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001128 private final void completePauseLocked() {
1129 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001130 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1131
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001132 if (prev != null) {
1133 if (prev.finishing) {
1134 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001135 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001136 } else if (prev.app != null) {
1137 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1138 if (prev.waitingVisible) {
1139 prev.waitingVisible = false;
1140 mWaitingVisibleActivities.remove(prev);
1141 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1142 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001143 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001144 if (prev.configDestroy) {
1145 // The previous is being paused because the configuration
1146 // is changing, which means it is actually stopping...
1147 // To juggle the fact that we are also starting a new
1148 // instance right now, we need to first completely stop
1149 // the current instance before starting the new one.
1150 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1151 destroyActivityLocked(prev, true, false, "pause-config");
1152 } else {
1153 mStoppingActivities.add(prev);
1154 if (mStoppingActivities.size() > 3) {
1155 // If we already have a few activities waiting to stop,
1156 // then give up on things going idle and start clearing
1157 // them out.
1158 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1159 scheduleIdleLocked();
1160 } else {
1161 checkReadyForSleepLocked();
1162 }
1163 }
1164 } else {
1165 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1166 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001167 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001168 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001169 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001170
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001171 if (!mService.isSleeping()) {
1172 resumeTopActivityLocked(prev);
1173 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001174 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001175 ActivityRecord top = topRunningActivityLocked(null);
1176 if (top == null || (prev != null && top != prev)) {
1177 // If there are no more activities available to run,
1178 // do resume anyway to start something. Also if the top
1179 // activity on the stack is not the just paused activity,
1180 // we need to go ahead and resume it to ensure we complete
1181 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001182 resumeTopActivityLocked(null);
1183 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001184 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001185
1186 if (prev != null) {
1187 prev.resumeKeyDispatchingLocked();
1188 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001189
1190 if (prev.app != null && prev.cpuTimeAtResume > 0
1191 && mService.mBatteryStatsService.isOnBattery()) {
1192 long diff = 0;
1193 synchronized (mService.mProcessStatsThread) {
1194 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1195 - prev.cpuTimeAtResume;
1196 }
1197 if (diff > 0) {
1198 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1199 synchronized (bsi) {
1200 BatteryStatsImpl.Uid.Proc ps =
1201 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1202 prev.info.packageName);
1203 if (ps != null) {
1204 ps.addForegroundTimeLocked(diff);
1205 }
1206 }
1207 }
1208 }
1209 prev.cpuTimeAtResume = 0; // reset it
1210 }
1211
1212 /**
1213 * Once we know that we have asked an application to put an activity in
1214 * the resumed state (either by launching it or explicitly telling it),
1215 * this function updates the rest of our state to match that fact.
1216 */
1217 private final void completeResumeLocked(ActivityRecord next) {
1218 next.idle = false;
1219 next.results = null;
1220 next.newIntents = null;
1221
1222 // schedule an idle timeout in case the app doesn't do it for us.
1223 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1224 msg.obj = next;
1225 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1226
1227 if (false) {
1228 // The activity was never told to pause, so just keep
1229 // things going as-is. To maintain our own state,
1230 // we need to emulate it coming back and saying it is
1231 // idle.
1232 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1233 msg.obj = next;
1234 mHandler.sendMessage(msg);
1235 }
1236
1237 if (mMainStack) {
1238 mService.reportResumedActivityLocked(next);
1239 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001240
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001241 if (mMainStack) {
1242 mService.setFocusedActivityLocked(next);
1243 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001244 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001245 ensureActivitiesVisibleLocked(null, 0);
1246 mService.mWindowManager.executeAppTransition();
1247 mNoAnimActivities.clear();
1248
1249 // Mark the point when the activity is resuming
1250 // TODO: To be more accurate, the mark should be before the onCreate,
1251 // not after the onResume. But for subsequent starts, onResume is fine.
1252 if (next.app != null) {
1253 synchronized (mService.mProcessStatsThread) {
1254 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1255 }
1256 } else {
1257 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1258 }
1259 }
1260
1261 /**
1262 * Make sure that all activities that need to be visible (that is, they
1263 * currently can be seen by the user) actually are.
1264 */
1265 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1266 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1267 if (DEBUG_VISBILITY) Slog.v(
1268 TAG, "ensureActivitiesVisible behind " + top
1269 + " configChanges=0x" + Integer.toHexString(configChanges));
1270
1271 // If the top activity is not fullscreen, then we need to
1272 // make sure any activities under it are now visible.
1273 final int count = mHistory.size();
1274 int i = count-1;
1275 while (mHistory.get(i) != top) {
1276 i--;
1277 }
1278 ActivityRecord r;
1279 boolean behindFullscreen = false;
1280 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001281 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001282 if (DEBUG_VISBILITY) Slog.v(
1283 TAG, "Make visible? " + r + " finishing=" + r.finishing
1284 + " state=" + r.state);
1285 if (r.finishing) {
1286 continue;
1287 }
1288
1289 final boolean doThisProcess = onlyThisProcess == null
1290 || onlyThisProcess.equals(r.processName);
1291
1292 // First: if this is not the current activity being started, make
1293 // sure it matches the current configuration.
1294 if (r != starting && doThisProcess) {
1295 ensureActivityConfigurationLocked(r, 0);
1296 }
1297
1298 if (r.app == null || r.app.thread == null) {
1299 if (onlyThisProcess == null
1300 || onlyThisProcess.equals(r.processName)) {
1301 // This activity needs to be visible, but isn't even
1302 // running... get it started, but don't resume it
1303 // at this point.
1304 if (DEBUG_VISBILITY) Slog.v(
1305 TAG, "Start and freeze screen for " + r);
1306 if (r != starting) {
1307 r.startFreezingScreenLocked(r.app, configChanges);
1308 }
1309 if (!r.visible) {
1310 if (DEBUG_VISBILITY) Slog.v(
1311 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001312 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001313 }
1314 if (r != starting) {
1315 startSpecificActivityLocked(r, false, false);
1316 }
1317 }
1318
1319 } else if (r.visible) {
1320 // If this activity is already visible, then there is nothing
1321 // else to do here.
1322 if (DEBUG_VISBILITY) Slog.v(
1323 TAG, "Skipping: already visible at " + r);
1324 r.stopFreezingScreenLocked(false);
1325
1326 } else if (onlyThisProcess == null) {
1327 // This activity is not currently visible, but is running.
1328 // Tell it to become visible.
1329 r.visible = true;
1330 if (r.state != ActivityState.RESUMED && r != starting) {
1331 // If this activity is paused, tell it
1332 // to now show its window.
1333 if (DEBUG_VISBILITY) Slog.v(
1334 TAG, "Making visible and scheduling visibility: " + r);
1335 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001336 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001337 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001338 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001339 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001340 r.stopFreezingScreenLocked(false);
1341 } catch (Exception e) {
1342 // Just skip on any failure; we'll make it
1343 // visible when it next restarts.
1344 Slog.w(TAG, "Exception thrown making visibile: "
1345 + r.intent.getComponent(), e);
1346 }
1347 }
1348 }
1349
1350 // Aggregate current change flags.
1351 configChanges |= r.configChangeFlags;
1352
1353 if (r.fullscreen) {
1354 // At this point, nothing else needs to be shown
1355 if (DEBUG_VISBILITY) Slog.v(
1356 TAG, "Stopping: fullscreen at " + r);
1357 behindFullscreen = true;
1358 i--;
1359 break;
1360 }
1361 }
1362
1363 // Now for any activities that aren't visible to the user, make
1364 // sure they no longer are keeping the screen frozen.
1365 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001366 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001367 if (DEBUG_VISBILITY) Slog.v(
1368 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1369 + " state=" + r.state
1370 + " behindFullscreen=" + behindFullscreen);
1371 if (!r.finishing) {
1372 if (behindFullscreen) {
1373 if (r.visible) {
1374 if (DEBUG_VISBILITY) Slog.v(
1375 TAG, "Making invisible: " + r);
1376 r.visible = false;
1377 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001378 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001379 if ((r.state == ActivityState.STOPPING
1380 || r.state == ActivityState.STOPPED)
1381 && r.app != null && r.app.thread != null) {
1382 if (DEBUG_VISBILITY) Slog.v(
1383 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001384 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001385 }
1386 } catch (Exception e) {
1387 // Just skip on any failure; we'll make it
1388 // visible when it next restarts.
1389 Slog.w(TAG, "Exception thrown making hidden: "
1390 + r.intent.getComponent(), e);
1391 }
1392 } else {
1393 if (DEBUG_VISBILITY) Slog.v(
1394 TAG, "Already invisible: " + r);
1395 }
1396 } else if (r.fullscreen) {
1397 if (DEBUG_VISBILITY) Slog.v(
1398 TAG, "Now behindFullscreen: " + r);
1399 behindFullscreen = true;
1400 }
1401 }
1402 i--;
1403 }
1404 }
1405
1406 /**
1407 * Version of ensureActivitiesVisible that can easily be called anywhere.
1408 */
1409 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1410 int configChanges) {
1411 ActivityRecord r = topRunningActivityLocked(null);
1412 if (r != null) {
1413 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1414 }
1415 }
1416
1417 /**
1418 * Ensure that the top activity in the stack is resumed.
1419 *
1420 * @param prev The previously resumed activity, for when in the process
1421 * of pausing; can be null to call from elsewhere.
1422 *
1423 * @return Returns true if something is being resumed, or false if
1424 * nothing happened.
1425 */
1426 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001427 return resumeTopActivityLocked(prev, null);
1428 }
1429
1430 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001431 // Find the first activity that is not finishing.
1432 ActivityRecord next = topRunningActivityLocked(null);
1433
1434 // Remember how we'll process this pause/resume situation, and ensure
1435 // that the state is reset however we wind up proceeding.
1436 final boolean userLeaving = mUserLeaving;
1437 mUserLeaving = false;
1438
1439 if (next == null) {
1440 // There are no more activities! Let's just start up the
1441 // Launcher...
1442 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001443 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001444 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001445 }
1446 }
1447
1448 next.delayedResume = false;
1449
1450 // If the top activity is the resumed one, nothing to do.
1451 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1452 // Make sure we have executed any pending transitions, since there
1453 // should be nothing left to do at this point.
1454 mService.mWindowManager.executeAppTransition();
1455 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001456 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001457 return false;
1458 }
1459
1460 // If we are sleeping, and there is no resumed activity, and the top
1461 // activity is paused, well that is the state we want.
1462 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001463 && mLastPausedActivity == next
1464 && (next.state == ActivityState.PAUSED
1465 || next.state == ActivityState.STOPPED
1466 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001467 // Make sure we have executed any pending transitions, since there
1468 // should be nothing left to do at this point.
1469 mService.mWindowManager.executeAppTransition();
1470 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001471 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001472 return false;
1473 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001474
1475 // Make sure that the user who owns this activity is started. If not,
1476 // we will just leave it as is because someone should be bringing
1477 // another user's activities to the top of the stack.
1478 if (mService.mStartedUsers.get(next.userId) == null) {
1479 Slog.w(TAG, "Skipping resume of top activity " + next
1480 + ": user " + next.userId + " is stopped");
1481 return false;
1482 }
1483
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001484 // The activity may be waiting for stop, but that is no longer
1485 // appropriate for it.
1486 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001487 mGoingToSleepActivities.remove(next);
1488 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001489 mWaitingVisibleActivities.remove(next);
1490
Dianne Hackborn84375872012-06-01 19:03:50 -07001491 next.updateOptionsLocked(options);
1492
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001493 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1494
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001495 // If we are currently pausing an activity, then don't do anything
1496 // until that is done.
1497 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001498 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1499 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001500 return false;
1501 }
1502
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001503 // Okay we are now going to start a switch, to 'next'. We may first
1504 // have to pause the current activity, but this is an important point
1505 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001506 // XXX "App Redirected" dialog is getting too many false positives
1507 // at this point, so turn off for now.
1508 if (false) {
1509 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1510 long now = SystemClock.uptimeMillis();
1511 final boolean inTime = mLastStartedActivity.startTime != 0
1512 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1513 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1514 final int nextUid = next.info.applicationInfo.uid;
1515 if (inTime && lastUid != nextUid
1516 && lastUid != next.launchedFromUid
1517 && mService.checkPermission(
1518 android.Manifest.permission.STOP_APP_SWITCHES,
1519 -1, next.launchedFromUid)
1520 != PackageManager.PERMISSION_GRANTED) {
1521 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1522 } else {
1523 next.startTime = now;
1524 mLastStartedActivity = next;
1525 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001526 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001527 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001528 mLastStartedActivity = next;
1529 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001530 }
1531
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001532 // We need to start pausing the current activity so the top one
1533 // can be resumed...
1534 if (mResumedActivity != null) {
1535 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001536 // At this point we want to put the upcoming activity's process
1537 // at the top of the LRU list, since we know we will be needing it
1538 // very soon and it would be a waste to let it get killed if it
1539 // happens to be sitting towards the end.
1540 if (next.app != null && next.app.thread != null) {
1541 // No reason to do full oom adj update here; we'll let that
1542 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001543 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001544 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001545 startPausingLocked(userLeaving, false);
1546 return true;
1547 }
1548
Christopher Tated3f175c2012-06-14 14:16:54 -07001549 // If the most recent activity was noHistory but was only stopped rather
1550 // than stopped+finished because the device went to sleep, we need to make
1551 // sure to finish it as we're making a new activity topmost.
1552 final ActivityRecord last = mLastPausedActivity;
1553 if (mService.mSleeping && last != null && !last.finishing) {
1554 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1555 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1556 if (DEBUG_STATES) {
1557 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1558 }
1559 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001560 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001561 }
1562 }
1563
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001564 if (prev != null && prev != next) {
1565 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1566 prev.waitingVisible = true;
1567 mWaitingVisibleActivities.add(prev);
1568 if (DEBUG_SWITCH) Slog.v(
1569 TAG, "Resuming top, waiting visible to hide: " + prev);
1570 } else {
1571 // The next activity is already visible, so hide the previous
1572 // activity's windows right now so we can show the new one ASAP.
1573 // We only do this if the previous is finishing, which should mean
1574 // it is on top of the one being resumed so hiding it quickly
1575 // is good. Otherwise, we want to do the normal route of allowing
1576 // the resumed activity to be shown so we can decide if the
1577 // previous should actually be hidden depending on whether the
1578 // new one is found to be full-screen or not.
1579 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001580 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1582 + prev + ", waitingVisible="
1583 + (prev != null ? prev.waitingVisible : null)
1584 + ", nowVisible=" + next.nowVisible);
1585 } else {
1586 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1587 + prev + ", waitingVisible="
1588 + (prev != null ? prev.waitingVisible : null)
1589 + ", nowVisible=" + next.nowVisible);
1590 }
1591 }
1592 }
1593
Dianne Hackborne7f97212011-02-24 14:40:20 -08001594 // Launching this app's activity, make sure the app is no longer
1595 // considered stopped.
1596 try {
1597 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001598 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001599 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001600 } catch (IllegalArgumentException e) {
1601 Slog.w(TAG, "Failed trying to unstop package "
1602 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001603 }
1604
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001605 // We are starting up the next activity, so tell the window manager
1606 // that the previous one will be hidden soon. This way it can know
1607 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001608 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001609 if (prev != null) {
1610 if (prev.finishing) {
1611 if (DEBUG_TRANSITION) Slog.v(TAG,
1612 "Prepare close transition: prev=" + prev);
1613 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001614 mService.mWindowManager.prepareAppTransition(
1615 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001616 } else {
1617 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1618 ? WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001619 : WindowManagerPolicy.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001620 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001621 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1622 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001623 } else {
1624 if (DEBUG_TRANSITION) Slog.v(TAG,
1625 "Prepare open transition: prev=" + prev);
1626 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001627 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001628 mService.mWindowManager.prepareAppTransition(
1629 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001630 } else {
1631 mService.mWindowManager.prepareAppTransition(prev.task == next.task
1632 ? WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001633 : WindowManagerPolicy.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001634 }
1635 }
1636 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001637 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1638 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001639 }
1640 } else if (mHistory.size() > 1) {
1641 if (DEBUG_TRANSITION) Slog.v(TAG,
1642 "Prepare open transition: no previous");
1643 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001644 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001645 mService.mWindowManager.prepareAppTransition(
1646 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001647 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001648 mService.mWindowManager.prepareAppTransition(
1649 WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001650 }
1651 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001652 if (!noAnim) {
1653 next.applyOptionsLocked();
1654 } else {
1655 next.clearOptionsLocked();
1656 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001657
1658 if (next.app != null && next.app.thread != null) {
1659 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1660
1661 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001662 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001663
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001664 // schedule launch ticks to collect information about slow apps.
1665 next.startLaunchTickingLocked();
1666
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001667 ActivityRecord lastResumedActivity = mResumedActivity;
1668 ActivityState lastState = next.state;
1669
1670 mService.updateCpuStats();
1671
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001672 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001673 next.state = ActivityState.RESUMED;
1674 mResumedActivity = next;
1675 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001676 if (mMainStack) {
1677 mService.addRecentTaskLocked(next.task);
1678 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001679 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001680 updateLRUListLocked(next);
1681
1682 // Have the window manager re-evaluate the orientation of
1683 // the screen based on the new activity order.
1684 boolean updated = false;
1685 if (mMainStack) {
1686 synchronized (mService) {
1687 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1688 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001689 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001690 if (config != null) {
1691 next.frozenBeforeDestroy = true;
1692 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001693 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001694 }
1695 }
1696 if (!updated) {
1697 // The configuration update wasn't able to keep the existing
1698 // instance of the activity, and instead started a new one.
1699 // We should be all done, but let's just make sure our activity
1700 // is still at the top and schedule another run if something
1701 // weird happened.
1702 ActivityRecord nextNext = topRunningActivityLocked(null);
1703 if (DEBUG_SWITCH) Slog.i(TAG,
1704 "Activity config changed during resume: " + next
1705 + ", new next: " + nextNext);
1706 if (nextNext != next) {
1707 // Do over!
1708 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1709 }
1710 if (mMainStack) {
1711 mService.setFocusedActivityLocked(next);
1712 }
1713 ensureActivitiesVisibleLocked(null, 0);
1714 mService.mWindowManager.executeAppTransition();
1715 mNoAnimActivities.clear();
1716 return true;
1717 }
1718
1719 try {
1720 // Deliver all pending results.
1721 ArrayList a = next.results;
1722 if (a != null) {
1723 final int N = a.size();
1724 if (!next.finishing && N > 0) {
1725 if (DEBUG_RESULTS) Slog.v(
1726 TAG, "Delivering results to " + next
1727 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001728 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001729 }
1730 }
1731
1732 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001733 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001734 }
1735
1736 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001737 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001738 next.task.taskId, next.shortComponentName);
1739
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001740 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001741 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001742 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001743 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001744 mService.isNextTransitionForward());
1745
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001746 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001747
1748 } catch (Exception e) {
1749 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001750 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1751 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001752 next.state = lastState;
1753 mResumedActivity = lastResumedActivity;
1754 Slog.i(TAG, "Restarting because process died: " + next);
1755 if (!next.hasBeenLaunched) {
1756 next.hasBeenLaunched = true;
1757 } else {
1758 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1759 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001760 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001761 mService.compatibilityInfoForPackageLocked(
1762 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001764 next.labelRes, next.icon, next.windowFlags,
1765 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001766 }
1767 }
1768 startSpecificActivityLocked(next, true, false);
1769 return true;
1770 }
1771
1772 // From this point on, if something goes wrong there is no way
1773 // to recover the activity.
1774 try {
1775 next.visible = true;
1776 completeResumeLocked(next);
1777 } catch (Exception e) {
1778 // If any exception gets thrown, toss away this
1779 // activity and try the next one.
1780 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001781 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001782 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 return true;
1784 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001785 next.stopped = false;
1786
1787 } else {
1788 // Whoops, need to restart this activity!
1789 if (!next.hasBeenLaunched) {
1790 next.hasBeenLaunched = true;
1791 } else {
1792 if (SHOW_APP_STARTING_PREVIEW) {
1793 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001794 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001795 mService.compatibilityInfoForPackageLocked(
1796 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001797 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001798 next.labelRes, next.icon, next.windowFlags,
1799 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001800 }
1801 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1802 }
1803 startSpecificActivityLocked(next, true, true);
1804 }
1805
1806 return true;
1807 }
1808
1809 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001810 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001811 final int NH = mHistory.size();
1812
1813 int addPos = -1;
1814
1815 if (!newTask) {
1816 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001817 boolean startIt = true;
1818 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001819 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820 if (p.finishing) {
1821 continue;
1822 }
1823 if (p.task == r.task) {
1824 // Here it is! Now, if this is not yet visible to the
1825 // user, then just add it without starting; it will
1826 // get started when the user navigates back to it.
1827 addPos = i+1;
1828 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001829 if (DEBUG_ADD_REMOVE) {
1830 RuntimeException here = new RuntimeException("here");
1831 here.fillInStackTrace();
1832 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1833 here);
1834 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001835 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001836 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001837 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07001838 r.info.screenOrientation, r.fullscreen,
1839 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001840 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001841 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001842 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001843 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001844 return;
1845 }
1846 break;
1847 }
1848 if (p.fullscreen) {
1849 startIt = false;
1850 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001851 }
1852 }
1853
1854 // Place a new activity at top of stack, so it is next to interact
1855 // with the user.
1856 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001857 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001858 }
1859
1860 // If we are not placing the new activity frontmost, we do not want
1861 // to deliver the onUserLeaving callback to the actual frontmost
1862 // activity
1863 if (addPos < NH) {
1864 mUserLeaving = false;
1865 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1866 }
1867
1868 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001869 if (DEBUG_ADD_REMOVE) {
1870 RuntimeException here = new RuntimeException("here");
1871 here.fillInStackTrace();
1872 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1873 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001874 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001875 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001877 if (NH > 0) {
1878 // We want to show the starting preview window if we are
1879 // switching to a new task, or the next activity's process is
1880 // not currently running.
1881 boolean showStartingIcon = newTask;
1882 ProcessRecord proc = r.app;
1883 if (proc == null) {
1884 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1885 }
1886 if (proc == null || proc.thread == null) {
1887 showStartingIcon = true;
1888 }
1889 if (DEBUG_TRANSITION) Slog.v(TAG,
1890 "Prepare open transition: starting " + r);
1891 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001892 mService.mWindowManager.prepareAppTransition(
1893 WindowManagerPolicy.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001895 } else {
1896 mService.mWindowManager.prepareAppTransition(newTask
1897 ? WindowManagerPolicy.TRANSIT_TASK_OPEN
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001898 : WindowManagerPolicy.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001899 mNoAnimActivities.remove(r);
1900 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001901 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001902 mService.mWindowManager.addAppToken(
Craig Mautner5962b122012-10-05 14:45:52 -07001903 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
1904 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001905 boolean doShow = true;
1906 if (newTask) {
1907 // Even though this activity is starting fresh, we still need
1908 // to reset it to make sure we apply affinities to move any
1909 // existing activities from other tasks in to it.
1910 // If the caller has requested that the target task be
1911 // reset, then do so.
1912 if ((r.intent.getFlags()
1913 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1914 resetTaskIfNeededLocked(r, r);
1915 doShow = topRunningNonDelayedActivityLocked(null) == r;
1916 }
1917 }
1918 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1919 // Figure out if we are transitioning from another activity that is
1920 // "has the same starting icon" as the next one. This allows the
1921 // window manager to keep the previous window it had previously
1922 // created, if it still had one.
1923 ActivityRecord prev = mResumedActivity;
1924 if (prev != null) {
1925 // We don't want to reuse the previous starting preview if:
1926 // (1) The current activity is in a different task.
1927 if (prev.task != r.task) prev = null;
1928 // (2) The current activity is already displayed.
1929 else if (prev.nowVisible) prev = null;
1930 }
1931 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001932 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001933 mService.compatibilityInfoForPackageLocked(
1934 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001935 r.labelRes, r.icon, r.windowFlags,
1936 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001937 }
1938 } else {
1939 // If this is the first activity, don't do any fancy animations,
1940 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001941 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07001942 r.info.screenOrientation, r.fullscreen,
1943 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001944 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001945 }
1946 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001947 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001948 }
1949
1950 if (doResume) {
1951 resumeTopActivityLocked(null);
1952 }
1953 }
1954
Dianne Hackbornbe707852011-11-11 14:32:10 -08001955 final void validateAppTokensLocked() {
1956 mValidateAppTokens.clear();
1957 mValidateAppTokens.ensureCapacity(mHistory.size());
1958 for (int i=0; i<mHistory.size(); i++) {
1959 mValidateAppTokens.add(mHistory.get(i).appToken);
1960 }
1961 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
1962 }
1963
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001964 /**
1965 * Perform a reset of the given task, if needed as part of launching it.
1966 * Returns the new HistoryRecord at the top of the task.
1967 */
1968 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
1969 ActivityRecord newActivity) {
1970 boolean forceReset = (newActivity.info.flags
1971 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08001972 if (ACTIVITY_INACTIVE_RESET_TIME > 0
1973 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001974 if ((newActivity.info.flags
1975 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
1976 forceReset = true;
1977 }
1978 }
1979
1980 final TaskRecord task = taskTop.task;
1981
1982 // We are going to move through the history list so that we can look
1983 // at each activity 'target' with 'below' either the interesting
1984 // activity immediately below it in the stack or null.
1985 ActivityRecord target = null;
1986 int targetI = 0;
1987 int taskTopI = -1;
1988 int replyChainEnd = -1;
1989 int lastReparentPos = -1;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07001990 ActivityOptions topOptions = null;
1991 boolean canMoveOptions = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001992 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001993 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001994
1995 if (below != null && below.finishing) {
1996 continue;
1997 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08001998 // Don't check any lower in the stack if we're crossing a user boundary.
1999 if (below != null && below.userId != taskTop.userId) {
2000 break;
2001 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002002 if (target == null) {
2003 target = below;
2004 targetI = i;
2005 // If we were in the middle of a reply chain before this
2006 // task, it doesn't appear like the root of the chain wants
2007 // anything interesting, so drop it.
2008 replyChainEnd = -1;
2009 continue;
2010 }
2011
2012 final int flags = target.info.flags;
2013
2014 final boolean finishOnTaskLaunch =
2015 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2016 final boolean allowTaskReparenting =
2017 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2018
2019 if (target.task == task) {
2020 // We are inside of the task being reset... we'll either
2021 // finish this activity, push it out for another task,
2022 // or leave it as-is. We only do this
2023 // for activities that are not the root of the task (since
2024 // if we finish the root, we may no longer have the task!).
2025 if (taskTopI < 0) {
2026 taskTopI = targetI;
2027 }
2028 if (below != null && below.task == task) {
2029 final boolean clearWhenTaskReset =
2030 (target.intent.getFlags()
2031 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2032 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
2033 // If this activity is sending a reply to a previous
2034 // activity, we can't do anything with it now until
2035 // we reach the start of the reply chain.
2036 // XXX note that we are assuming the result is always
2037 // to the previous activity, which is almost always
2038 // the case but we really shouldn't count on.
2039 if (replyChainEnd < 0) {
2040 replyChainEnd = targetI;
2041 }
2042 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2043 && target.taskAffinity != null
2044 && !target.taskAffinity.equals(task.affinity)) {
2045 // If this activity has an affinity for another
2046 // task, then we need to move it out of here. We will
2047 // move it as far out of the way as possible, to the
2048 // bottom of the activity stack. This also keeps it
2049 // correctly ordered with any activities we previously
2050 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002051 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002052 if (target.taskAffinity != null
2053 && target.taskAffinity.equals(p.task.affinity)) {
2054 // If the activity currently at the bottom has the
2055 // same task affinity as the one we are moving,
2056 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002057 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002058 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2059 + " out to bottom task " + p.task);
2060 } else {
2061 mService.mCurTask++;
2062 if (mService.mCurTask <= 0) {
2063 mService.mCurTask = 1;
2064 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002065 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2066 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002067 target.task.affinityIntent = target.intent;
2068 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2069 + " out to new task " + target.task);
2070 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002071 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002072 if (replyChainEnd < 0) {
2073 replyChainEnd = targetI;
2074 }
2075 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002076 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002077 boolean gotOptions = !canMoveOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002078 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002079 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002080 if (p.finishing) {
2081 continue;
2082 }
2083 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2084 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002085 p.setTask(target.task, curThumbHolder, false);
2086 curThumbHolder = p.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002087 canMoveOptions = false;
2088 if (!gotOptions && topOptions == null) {
2089 topOptions = p.takeOptionsLocked();
2090 if (topOptions != null) {
2091 gotOptions = true;
2092 }
2093 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002094 if (DEBUG_ADD_REMOVE) {
2095 RuntimeException here = new RuntimeException("here");
2096 here.fillInStackTrace();
2097 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2098 + dstPos, here);
2099 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002100 mHistory.remove(srcPos);
2101 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002102 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
2103 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002104 dstPos++;
2105 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002106 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002107 }
2108 i++;
2109 }
2110 if (taskTop == p) {
2111 taskTop = below;
2112 }
2113 if (taskTopI == replyChainEnd) {
2114 taskTopI = -1;
2115 }
2116 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 } else if (forceReset || finishOnTaskLaunch
2118 || clearWhenTaskReset) {
2119 // If the activity should just be removed -- either
2120 // because it asks for it, or the task should be
2121 // cleared -- then finish it and anything that is
2122 // part of its reply chain.
2123 if (clearWhenTaskReset) {
2124 // In this case, we want to finish this activity
2125 // and everything above it, so be sneaky and pretend
2126 // like these are all in the reply chain.
2127 replyChainEnd = targetI+1;
2128 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002129 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002130 replyChainEnd)).task == task) {
2131 replyChainEnd++;
2132 }
2133 replyChainEnd--;
2134 } else if (replyChainEnd < 0) {
2135 replyChainEnd = targetI;
2136 }
2137 ActivityRecord p = null;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002138 boolean gotOptions = !canMoveOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002139 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002140 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 if (p.finishing) {
2142 continue;
2143 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002144 canMoveOptions = false;
2145 if (!gotOptions && topOptions == null) {
2146 topOptions = p.takeOptionsLocked();
2147 if (topOptions != null) {
2148 gotOptions = true;
2149 }
2150 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002151 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002152 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002153 replyChainEnd--;
2154 srcPos--;
2155 }
2156 }
2157 if (taskTop == p) {
2158 taskTop = below;
2159 }
2160 if (taskTopI == replyChainEnd) {
2161 taskTopI = -1;
2162 }
2163 replyChainEnd = -1;
2164 } else {
2165 // If we were in the middle of a chain, well the
2166 // activity that started it all doesn't want anything
2167 // special, so leave it all as-is.
2168 replyChainEnd = -1;
2169 }
2170 } else {
2171 // Reached the bottom of the task -- any reply chain
2172 // should be left as-is.
2173 replyChainEnd = -1;
2174 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002175
2176 } else if (target.resultTo != null && (below == null
2177 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002178 // If this activity is sending a reply to a previous
2179 // activity, we can't do anything with it now until
2180 // we reach the start of the reply chain.
2181 // XXX note that we are assuming the result is always
2182 // to the previous activity, which is almost always
2183 // the case but we really shouldn't count on.
2184 if (replyChainEnd < 0) {
2185 replyChainEnd = targetI;
2186 }
2187
2188 } else if (taskTopI >= 0 && allowTaskReparenting
2189 && task.affinity != null
2190 && task.affinity.equals(target.taskAffinity)) {
2191 // We are inside of another task... if this activity has
2192 // an affinity for our task, then either remove it if we are
2193 // clearing or move it over to our task. Note that
2194 // we currently punt on the case where we are resetting a
2195 // task that is not at the top but who has activities above
2196 // with an affinity to it... this is really not a normal
2197 // case, and we will need to later pull that task to the front
2198 // and usually at that point we will do the reset and pick
2199 // up those remaining activities. (This only happens if
2200 // someone starts an activity in a new task from an activity
2201 // in a task that is not currently on top.)
2202 if (forceReset || finishOnTaskLaunch) {
2203 if (replyChainEnd < 0) {
2204 replyChainEnd = targetI;
2205 }
2206 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002207 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2208 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002209 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002210 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002211 if (p.finishing) {
2212 continue;
2213 }
2214 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002215 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002216 taskTopI--;
2217 lastReparentPos--;
2218 replyChainEnd--;
2219 srcPos--;
2220 }
2221 }
2222 replyChainEnd = -1;
2223 } else {
2224 if (replyChainEnd < 0) {
2225 replyChainEnd = targetI;
2226 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002227 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2228 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002230 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002231 if (p.finishing) {
2232 continue;
2233 }
2234 if (lastReparentPos < 0) {
2235 lastReparentPos = taskTopI;
2236 taskTop = p;
2237 } else {
2238 lastReparentPos--;
2239 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002240 if (DEBUG_ADD_REMOVE) {
2241 RuntimeException here = new RuntimeException("here");
2242 here.fillInStackTrace();
2243 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2244 + lastReparentPos, here);
2245 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002246 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002247 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002248 mHistory.add(lastReparentPos, p);
2249 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002250 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002251 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002252 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
2253 mService.mWindowManager.setAppGroupId(p.appToken, p.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002254 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002255 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002256 }
2257 }
2258 replyChainEnd = -1;
2259
2260 // Now we've moved it in to place... but what if this is
2261 // a singleTop activity and we have put it on top of another
2262 // instance of the same activity? Then we drop the instance
2263 // below so it remains singleTop.
2264 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2265 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002266 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002267 if (p.finishing) {
2268 continue;
2269 }
2270 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2271 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002272 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002273 taskTopI--;
2274 lastReparentPos--;
2275 }
2276 }
2277 }
2278 }
2279 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002280
2281 } else if (below != null && below.task != target.task) {
2282 // We hit the botton of a task; the reply chain can't
2283 // pass through it.
2284 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002285 }
2286
2287 target = below;
2288 targetI = i;
2289 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002290
2291 if (topOptions != null) {
2292 // If we got some ActivityOptions from an activity on top that
2293 // was removed from the task, propagate them to the new real top.
2294 if (taskTop != null) {
2295 taskTop.updateOptionsLocked(topOptions);
2296 } else {
2297 topOptions.abort();
2298 }
2299 }
2300
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002301 return taskTop;
2302 }
2303
2304 /**
2305 * Perform clear operation as requested by
2306 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2307 * stack to the given task, then look for
2308 * an instance of that activity in the stack and, if found, finish all
2309 * activities on top of it and return the instance.
2310 *
2311 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002312 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002313 * or null if none was found.
2314 */
2315 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002316 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002317 int i = mHistory.size();
2318
2319 // First find the requested task.
2320 while (i > 0) {
2321 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002322 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002323 if (r.task.taskId == taskId) {
2324 i++;
2325 break;
2326 }
2327 }
2328
2329 // Now clear it.
2330 while (i > 0) {
2331 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002332 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002333 if (r.finishing) {
2334 continue;
2335 }
2336 if (r.task.taskId != taskId) {
2337 return null;
2338 }
2339 if (r.realActivity.equals(newR.realActivity)) {
2340 // Here it is! Now finish everything in front...
2341 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002342 while (i < (mHistory.size()-1)) {
2343 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002344 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002345 if (r.task.taskId != taskId) {
2346 break;
2347 }
2348 if (r.finishing) {
2349 continue;
2350 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002351 ActivityOptions opts = r.takeOptionsLocked();
2352 if (opts != null) {
2353 ret.updateOptionsLocked(opts);
2354 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002355 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002356 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002357 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002358 }
2359 }
2360
2361 // Finally, if this is a normal launch mode (that is, not
2362 // expecting onNewIntent()), then we will finish the current
2363 // instance of the activity so a new fresh one can be started.
2364 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2365 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2366 if (!ret.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002367 int index = indexOfTokenLocked(ret.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002368 if (index >= 0) {
2369 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002370 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002371 }
2372 return null;
2373 }
2374 }
2375
2376 return ret;
2377 }
2378 }
2379
2380 return null;
2381 }
2382
2383 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002384 * Completely remove all activities associated with an existing
2385 * task starting at a specified index.
2386 */
2387 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002388 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002389 ActivityRecord r = mHistory.get(i);
2390 if (r.task.taskId != taskId) {
2391 // Whoops hit the end.
2392 return;
2393 }
2394 if (r.finishing) {
2395 i++;
2396 continue;
2397 }
2398 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002399 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002400 i++;
2401 }
2402 }
2403 }
2404
2405 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002406 * Completely remove all activities associated with an existing task.
2407 */
2408 private final void performClearTaskLocked(int taskId) {
2409 int i = mHistory.size();
2410
2411 // First find the requested task.
2412 while (i > 0) {
2413 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002414 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002415 if (r.task.taskId == taskId) {
2416 i++;
2417 break;
2418 }
2419 }
2420
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002421 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002422 while (i > 0) {
2423 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002424 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002425 if (r.finishing) {
2426 continue;
2427 }
2428 if (r.task.taskId != taskId) {
2429 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002430 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002431 return;
2432 }
2433 }
2434 }
2435
2436 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002437 * Find the activity in the history stack within the given task. Returns
2438 * the index within the history at which it's found, or < 0 if not found.
2439 */
2440 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2441 int i = mHistory.size();
2442 while (i > 0) {
2443 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002444 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002445 if (candidate.finishing) {
2446 continue;
2447 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002448 if (candidate.task.taskId != task) {
2449 break;
2450 }
2451 if (candidate.realActivity.equals(r.realActivity)) {
2452 return i;
2453 }
2454 }
2455
2456 return -1;
2457 }
2458
2459 /**
2460 * Reorder the history stack so that the activity at the given index is
2461 * brought to the front.
2462 */
2463 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002464 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002465 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002466 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002467 if (DEBUG_ADD_REMOVE) {
2468 RuntimeException here = new RuntimeException("here");
2469 here.fillInStackTrace();
2470 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2471 + top, here);
2472 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002473 mHistory.add(top, newTop);
2474 oldTop.frontOfTask = false;
2475 newTop.frontOfTask = true;
2476 return newTop;
2477 }
2478
2479 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002480 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002481 String resultWho, int requestCode,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002482 int callingPid, int callingUid, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002483 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002484
Dianne Hackborna4972e92012-03-14 10:38:05 -07002485 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002486
2487 ProcessRecord callerApp = null;
2488 if (caller != null) {
2489 callerApp = mService.getRecordForAppLocked(caller);
2490 if (callerApp != null) {
2491 callingPid = callerApp.pid;
2492 callingUid = callerApp.info.uid;
2493 } else {
2494 Slog.w(TAG, "Unable to find app for caller " + caller
2495 + " (pid=" + callingPid + ") when starting: "
2496 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002497 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002498 }
2499 }
2500
Dianne Hackborna4972e92012-03-14 10:38:05 -07002501 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002502 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002503 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2504 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002505 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002506
2507 ActivityRecord sourceRecord = null;
2508 ActivityRecord resultRecord = null;
2509 if (resultTo != null) {
2510 int index = indexOfTokenLocked(resultTo);
2511 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002512 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002514 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515 if (requestCode >= 0 && !sourceRecord.finishing) {
2516 resultRecord = sourceRecord;
2517 }
2518 }
2519 }
2520
2521 int launchFlags = intent.getFlags();
2522
2523 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2524 && sourceRecord != null) {
2525 // Transfer the result target from the source activity to the new
2526 // one being started, including any failures.
2527 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002528 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002529 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002530 }
2531 resultRecord = sourceRecord.resultTo;
2532 resultWho = sourceRecord.resultWho;
2533 requestCode = sourceRecord.requestCode;
2534 sourceRecord.resultTo = null;
2535 if (resultRecord != null) {
2536 resultRecord.removeResultsLocked(
2537 sourceRecord, resultWho, requestCode);
2538 }
2539 }
2540
Dianne Hackborna4972e92012-03-14 10:38:05 -07002541 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002542 // We couldn't find a class that can handle the given Intent.
2543 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002544 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002545 }
2546
Dianne Hackborna4972e92012-03-14 10:38:05 -07002547 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002548 // We couldn't find the specific class specified in the Intent.
2549 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002550 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002551 }
2552
Dianne Hackborna4972e92012-03-14 10:38:05 -07002553 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002554 if (resultRecord != null) {
2555 sendActivityResultLocked(-1,
2556 resultRecord, resultWho, requestCode,
2557 Activity.RESULT_CANCELED, null);
2558 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002559 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002560 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002561 return err;
2562 }
2563
Jeff Sharkey35be7562012-04-18 19:16:15 -07002564 final int startAnyPerm = mService.checkPermission(
2565 START_ANY_ACTIVITY, callingPid, callingUid);
2566 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002567 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002568 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002569 if (resultRecord != null) {
2570 sendActivityResultLocked(-1,
2571 resultRecord, resultWho, requestCode,
2572 Activity.RESULT_CANCELED, null);
2573 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002574 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002575 String msg;
2576 if (!aInfo.exported) {
2577 msg = "Permission Denial: starting " + intent.toString()
2578 + " from " + callerApp + " (pid=" + callingPid
2579 + ", uid=" + callingUid + ")"
2580 + " not exported from uid " + aInfo.applicationInfo.uid;
2581 } else {
2582 msg = "Permission Denial: starting " + intent.toString()
2583 + " from " + callerApp + " (pid=" + callingPid
2584 + ", uid=" + callingUid + ")"
2585 + " requires " + aInfo.permission;
2586 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002587 Slog.w(TAG, msg);
2588 throw new SecurityException(msg);
2589 }
2590
2591 if (mMainStack) {
2592 if (mService.mController != null) {
2593 boolean abort = false;
2594 try {
2595 // The Intent we give to the watcher has the extra data
2596 // stripped off, since it can contain private information.
2597 Intent watchIntent = intent.cloneFilter();
2598 abort = !mService.mController.activityStarting(watchIntent,
2599 aInfo.applicationInfo.packageName);
2600 } catch (RemoteException e) {
2601 mService.mController = null;
2602 }
2603
2604 if (abort) {
2605 if (resultRecord != null) {
2606 sendActivityResultLocked(-1,
2607 resultRecord, resultWho, requestCode,
2608 Activity.RESULT_CANCELED, null);
2609 }
2610 // We pretend to the caller that it was really started, but
2611 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002612 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002613 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002614 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002615 }
2616 }
2617 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002618
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002619 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid,
2620 intent, resolvedType, aInfo, mService.mConfiguration,
2621 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002622 if (outActivity != null) {
2623 outActivity[0] = r;
2624 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002625
2626 if (mMainStack) {
2627 if (mResumedActivity == null
2628 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2629 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2630 PendingActivityLaunch pal = new PendingActivityLaunch();
2631 pal.r = r;
2632 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002633 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002634 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002635 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002636 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002637 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002638 }
2639 }
2640
2641 if (mService.mDidAppSwitch) {
2642 // This is the second allowed switch since we stopped switches,
2643 // so now just generally allow switches. Use case: user presses
2644 // home (switches disabled, switch to home, mDidAppSwitch now true);
2645 // user taps a home icon (coming from home so allowed, we hit here
2646 // and now allow anyone to switch again).
2647 mService.mAppSwitchesAllowedTime = 0;
2648 } else {
2649 mService.mDidAppSwitch = true;
2650 }
2651
2652 mService.doPendingActivityLaunchesLocked(false);
2653 }
2654
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002655 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002656 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002657 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002658 // Someone asked to have the keyguard dismissed on the next
2659 // activity start, but we are not actually doing an activity
2660 // switch... just dismiss the keyguard now, because we
2661 // probably want to see whatever is behind it.
2662 mDismissKeyguardOnNextActivity = false;
2663 mService.mWindowManager.dismissKeyguard();
2664 }
2665 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002666 }
2667
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002668 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2669 if ((launchFlags &
2670 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2671 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2672 // Caller wants to appear on home activity, so before starting
2673 // their own activity we will bring home to the front.
2674 moveHomeToFrontLocked();
2675 }
2676 }
2677
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002678 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002679 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2680 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002681 final Intent intent = r.intent;
2682 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002683
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002684 int launchFlags = intent.getFlags();
2685
2686 // We'll invoke onUserLeaving before onPause only if the launching
2687 // activity did not explicitly state that this is an automated launch.
2688 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2689 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2690 "startActivity() => mUserLeaving=" + mUserLeaving);
2691
2692 // If the caller has asked not to resume at this point, we make note
2693 // of this in the record so that we can skip it when trying to find
2694 // the top running activity.
2695 if (!doResume) {
2696 r.delayedResume = true;
2697 }
2698
2699 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2700 != 0 ? r : null;
2701
2702 // If the onlyIfNeeded flag is set, then we can do this if the activity
2703 // being launched is the same as the one making the call... or, as
2704 // a special case, if we do not know the caller then we count the
2705 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002706 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002707 ActivityRecord checkedCaller = sourceRecord;
2708 if (checkedCaller == null) {
2709 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2710 }
2711 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2712 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002713 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002714 }
2715 }
2716
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002717 if (sourceRecord == null) {
2718 // This activity is not being started from another... in this
2719 // case we -always- start a new task.
2720 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2721 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2722 + intent);
2723 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2724 }
2725 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2726 // The original activity who is starting us is running as a single
2727 // instance... this new activity it is starting must go on its
2728 // own task.
2729 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2730 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2731 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2732 // The activity being started is a single instance... it always
2733 // gets launched into its own task.
2734 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2735 }
2736
2737 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2738 // For whatever reason this activity is being launched into a new
2739 // task... yet the caller has requested a result back. Well, that
2740 // is pretty messed up, so instead immediately send back a cancel
2741 // and let the new task continue launched as normal without a
2742 // dependency on its originator.
2743 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2744 sendActivityResultLocked(-1,
2745 r.resultTo, r.resultWho, r.requestCode,
2746 Activity.RESULT_CANCELED, null);
2747 r.resultTo = null;
2748 }
2749
2750 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002751 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002752 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002753 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2754 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2755 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2756 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2757 // If bring to front is requested, and no result is requested, and
2758 // we can find a task that was started with this same
2759 // component, then instead of launching bring that one to the front.
2760 if (r.resultTo == null) {
2761 // See if there is a task to bring to the front. If this is
2762 // a SINGLE_INSTANCE activity, there can be one and only one
2763 // instance of it in the history, and it is always in its own
2764 // unique task, so we do a special search.
2765 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2766 ? findTaskLocked(intent, r.info)
2767 : findActivityLocked(intent, r.info);
2768 if (taskTop != null) {
2769 if (taskTop.task.intent == null) {
2770 // This task was started because of movement of
2771 // the activity based on affinity... now that we
2772 // are actually launching it, we can assign the
2773 // base intent.
2774 taskTop.task.setIntent(intent, r.info);
2775 }
2776 // If the target task is not in the front, then we need
2777 // to bring it to the front... except... well, with
2778 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2779 // to have the same behavior as if a new instance was
2780 // being started, which means not bringing it to the front
2781 // if the caller is not itself in the front.
2782 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002783 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002784 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2785 boolean callerAtFront = sourceRecord == null
2786 || curTop.task == sourceRecord.task;
2787 if (callerAtFront) {
2788 // We really do want to push this one into the
2789 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002790 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002791 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002792 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002793 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002794 }
2795 }
2796 // If the caller has requested that the target task be
2797 // reset, then do so.
2798 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2799 taskTop = resetTaskIfNeededLocked(taskTop, r);
2800 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002801 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002802 // We don't need to start a new activity, and
2803 // the client said not to do anything if that
2804 // is the case, so this is it! And for paranoia, make
2805 // sure we have correctly resumed the top activity.
2806 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002807 resumeTopActivityLocked(null, options);
2808 } else {
2809 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002810 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002811 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002812 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002813 if ((launchFlags &
2814 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2815 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2816 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002817 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002818 // not be too hard...
2819 reuseTask = taskTop.task;
2820 performClearTaskLocked(taskTop.task.taskId);
2821 reuseTask.setIntent(r.intent, r.info);
2822 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002823 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2824 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2825 // In this situation we want to remove all activities
2826 // from the task up to the one being started. In most
2827 // cases this means we are resetting the task to its
2828 // initial state.
2829 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002830 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002831 if (top != null) {
2832 if (top.frontOfTask) {
2833 // Activity aliases may mean we use different
2834 // intents for the top activity, so make sure
2835 // the task now has the identity of the new
2836 // intent.
2837 top.task.setIntent(r.intent, r.info);
2838 }
2839 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002840 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002841 } else {
2842 // A special case: we need to
2843 // start the activity because it is not currently
2844 // running, and the caller has asked to clear the
2845 // current task to have this activity at the top.
2846 addingToTask = true;
2847 // Now pretend like this activity is being started
2848 // by the top of its task, so it is put in the
2849 // right place.
2850 sourceRecord = taskTop;
2851 }
2852 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2853 // In this case the top activity on the task is the
2854 // same as the one being launched, so we take that
2855 // as a request to bring the task to the foreground.
2856 // If the top activity in the task is the root
2857 // activity, deliver this new intent to it if it
2858 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002859 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2860 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002861 && taskTop.realActivity.equals(r.realActivity)) {
2862 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2863 if (taskTop.frontOfTask) {
2864 taskTop.task.setIntent(r.intent, r.info);
2865 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002866 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002867 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2868 // In this case we are launching the root activity
2869 // of the task, but with a different intent. We
2870 // should start a new instance on top.
2871 addingToTask = true;
2872 sourceRecord = taskTop;
2873 }
2874 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2875 // In this case an activity is being launched in to an
2876 // existing task, without resetting that task. This
2877 // is typically the situation of launching an activity
2878 // from a notification or shortcut. We want to place
2879 // the new activity on top of the current task.
2880 addingToTask = true;
2881 sourceRecord = taskTop;
2882 } else if (!taskTop.task.rootWasReset) {
2883 // In this case we are launching in to an existing task
2884 // that has not yet been started from its front door.
2885 // The current task has been brought to the front.
2886 // Ideally, we'd probably like to place this new task
2887 // at the bottom of its stack, but that's a little hard
2888 // to do with the current organization of the code so
2889 // for now we'll just drop it.
2890 taskTop.task.setIntent(r.intent, r.info);
2891 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002892 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002893 // We didn't do anything... but it was needed (a.k.a., client
2894 // don't use that intent!) And for paranoia, make
2895 // sure we have correctly resumed the top activity.
2896 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002897 resumeTopActivityLocked(null, options);
2898 } else {
2899 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002900 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002901 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002902 }
2903 }
2904 }
2905 }
2906
2907 //String uri = r.intent.toURI();
2908 //Intent intent2 = new Intent(uri);
2909 //Slog.i(TAG, "Given intent: " + r.intent);
2910 //Slog.i(TAG, "URI is: " + uri);
2911 //Slog.i(TAG, "To intent: " + intent2);
2912
2913 if (r.packageName != null) {
2914 // If the activity being launched is the same as the one currently
2915 // at the top, then we need to check if it should only be launched
2916 // once.
2917 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2918 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002919 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002920 if (top.app != null && top.app.thread != null) {
2921 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2922 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2923 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2924 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2925 // For paranoia, make sure we have correctly
2926 // resumed the top activity.
2927 if (doResume) {
2928 resumeTopActivityLocked(null);
2929 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002930 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002931 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002932 // We don't need to start a new activity, and
2933 // the client said not to do anything if that
2934 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002935 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002936 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002937 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002938 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002939 }
2940 }
2941 }
2942 }
2943
2944 } else {
2945 if (r.resultTo != null) {
2946 sendActivityResultLocked(-1,
2947 r.resultTo, r.resultWho, r.requestCode,
2948 Activity.RESULT_CANCELED, null);
2949 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002950 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002951 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002952 }
2953
2954 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002955 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002956
2957 // Should this be considered a new task?
2958 if (r.resultTo == null && !addingToTask
2959 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002960 if (reuseTask == null) {
2961 // todo: should do better management of integers.
2962 mService.mCurTask++;
2963 if (mService.mCurTask <= 0) {
2964 mService.mCurTask = 1;
2965 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002966 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002967 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
2968 + " in new task " + r.task);
2969 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002970 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002971 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002972 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002973 if (!movedHome) {
2974 moveHomeToFrontFromLaunchLocked(launchFlags);
2975 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002976
2977 } else if (sourceRecord != null) {
2978 if (!addingToTask &&
2979 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
2980 // In this case, we are adding the activity to an existing
2981 // task, but the caller has asked to clear that task if the
2982 // activity is already running.
2983 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002984 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002985 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002986 if (top != null) {
2987 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002988 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002989 // For paranoia, make sure we have correctly
2990 // resumed the top activity.
2991 if (doResume) {
2992 resumeTopActivityLocked(null);
2993 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002994 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002995 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002996 }
2997 } else if (!addingToTask &&
2998 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
2999 // In this case, we are launching an activity in our own task
3000 // that may already be running somewhere in the history, and
3001 // we want to shuffle it to the front of the stack if so.
3002 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
3003 if (where >= 0) {
3004 ActivityRecord top = moveActivityToFrontLocked(where);
3005 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003006 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003007 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003008 if (doResume) {
3009 resumeTopActivityLocked(null);
3010 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003011 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003012 }
3013 }
3014 // An existing activity is starting this new activity, so we want
3015 // to keep the new one in the same task as the one that is starting
3016 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003017 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003018 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3019 + " in existing task " + r.task);
3020
3021 } else {
3022 // This not being started from an existing activity, and not part
3023 // of a new task... just put it in the top task, though these days
3024 // this case should never happen.
3025 final int N = mHistory.size();
3026 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003027 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003028 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003029 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003030 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003031 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3032 + " in new guessed " + r.task);
3033 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003034
Dianne Hackborn39792d22010-08-19 18:01:52 -07003035 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003036 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07003037
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003038 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003039 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003040 }
3041 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003042 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003043 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003044 }
3045
Dianne Hackborna4972e92012-03-14 10:38:05 -07003046 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003047 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003048 // Collect information about the target of the Intent.
3049 ActivityInfo aInfo;
3050 try {
3051 ResolveInfo rInfo =
3052 AppGlobals.getPackageManager().resolveIntent(
3053 intent, resolvedType,
3054 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003055 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003056 aInfo = rInfo != null ? rInfo.activityInfo : null;
3057 } catch (RemoteException e) {
3058 aInfo = null;
3059 }
3060
3061 if (aInfo != null) {
3062 // Store the found target back into the intent, because now that
3063 // we have it we never want to do this again. For example, if the
3064 // user navigates back to this point in the history, we should
3065 // always restart the exact same activity.
3066 intent.setComponent(new ComponentName(
3067 aInfo.applicationInfo.packageName, aInfo.name));
3068
3069 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003070 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003071 if (!aInfo.processName.equals("system")) {
3072 mService.setDebugApp(aInfo.processName, true, false);
3073 }
3074 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003075
Dianne Hackborna4972e92012-03-14 10:38:05 -07003076 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003077 if (!aInfo.processName.equals("system")) {
3078 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3079 }
3080 }
3081
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003082 if (profileFile != null) {
3083 if (!aInfo.processName.equals("system")) {
3084 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003085 profileFile, profileFd,
3086 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003087 }
3088 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003089 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003090 return aInfo;
3091 }
3092
3093 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003094 Intent intent, String resolvedType, IBinder resultTo,
3095 String resultWho, int requestCode, int startFlags, String profileFile,
3096 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3097 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003098 // Refuse possible leaked file descriptors
3099 if (intent != null && intent.hasFileDescriptors()) {
3100 throw new IllegalArgumentException("File descriptors passed in Intent");
3101 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003102 boolean componentSpecified = intent.getComponent() != null;
3103
3104 // Don't modify the client's object!
3105 intent = new Intent(intent);
3106
3107 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003108 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003109 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003110
3111 synchronized (mService) {
3112 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003113 if (callingUid >= 0) {
3114 callingPid = -1;
3115 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003116 callingPid = Binder.getCallingPid();
3117 callingUid = Binder.getCallingUid();
3118 } else {
3119 callingPid = callingUid = -1;
3120 }
3121
3122 mConfigWillChange = config != null
3123 && mService.mConfiguration.diff(config) != 0;
3124 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3125 "Starting activity when config will change = " + mConfigWillChange);
3126
3127 final long origId = Binder.clearCallingIdentity();
3128
3129 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003130 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003131 // This may be a heavy-weight process! Check to see if we already
3132 // have another, different heavy-weight process running.
3133 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3134 if (mService.mHeavyWeightProcess != null &&
3135 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3136 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3137 int realCallingPid = callingPid;
3138 int realCallingUid = callingUid;
3139 if (caller != null) {
3140 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3141 if (callerApp != null) {
3142 realCallingPid = callerApp.pid;
3143 realCallingUid = callerApp.info.uid;
3144 } else {
3145 Slog.w(TAG, "Unable to find app for caller " + caller
3146 + " (pid=" + realCallingPid + ") when starting: "
3147 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003148 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003149 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003150 }
3151 }
3152
3153 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003154 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003155 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003156 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003157 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158
3159 Intent newIntent = new Intent();
3160 if (requestCode >= 0) {
3161 // Caller is requesting a result.
3162 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3163 }
3164 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3165 new IntentSender(target));
3166 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3167 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3168 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3169 hist.packageName);
3170 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3171 hist.task.taskId);
3172 }
3173 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3174 aInfo.packageName);
3175 newIntent.setFlags(intent.getFlags());
3176 newIntent.setClassName("android",
3177 HeavyWeightSwitcherActivity.class.getName());
3178 intent = newIntent;
3179 resolvedType = null;
3180 caller = null;
3181 callingUid = Binder.getCallingUid();
3182 callingPid = Binder.getCallingPid();
3183 componentSpecified = true;
3184 try {
3185 ResolveInfo rInfo =
3186 AppGlobals.getPackageManager().resolveIntent(
3187 intent, null,
3188 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003189 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003190 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003191 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003192 } catch (RemoteException e) {
3193 aInfo = null;
3194 }
3195 }
3196 }
3197 }
3198
3199 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003200 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
3201 startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003202
3203 if (mConfigWillChange && mMainStack) {
3204 // If the caller also wants to switch to a new configuration,
3205 // do so now. This allows a clean switch, as we are waiting
3206 // for the current activity to pause (so we will not destroy
3207 // it), and have not yet started the next activity.
3208 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3209 "updateConfiguration()");
3210 mConfigWillChange = false;
3211 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3212 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003213 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003214 }
3215
3216 Binder.restoreCallingIdentity(origId);
3217
3218 if (outResult != null) {
3219 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003220 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003221 mWaitingActivityLaunched.add(outResult);
3222 do {
3223 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003224 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003225 } catch (InterruptedException e) {
3226 }
3227 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003228 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229 ActivityRecord r = this.topRunningActivityLocked(null);
3230 if (r.nowVisible) {
3231 outResult.timeout = false;
3232 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3233 outResult.totalTime = 0;
3234 outResult.thisTime = 0;
3235 } else {
3236 outResult.thisTime = SystemClock.uptimeMillis();
3237 mWaitingActivityVisible.add(outResult);
3238 do {
3239 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003240 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003241 } catch (InterruptedException e) {
3242 }
3243 } while (!outResult.timeout && outResult.who == null);
3244 }
3245 }
3246 }
3247
3248 return res;
3249 }
3250 }
3251
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003252 final int startActivities(IApplicationThread caller, int callingUid,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003253 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3254 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003255 if (intents == null) {
3256 throw new NullPointerException("intents is null");
3257 }
3258 if (resolvedTypes == null) {
3259 throw new NullPointerException("resolvedTypes is null");
3260 }
3261 if (intents.length != resolvedTypes.length) {
3262 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3263 }
3264
3265 ActivityRecord[] outActivity = new ActivityRecord[1];
3266
3267 int callingPid;
3268 if (callingUid >= 0) {
3269 callingPid = -1;
3270 } else if (caller == null) {
3271 callingPid = Binder.getCallingPid();
3272 callingUid = Binder.getCallingUid();
3273 } else {
3274 callingPid = callingUid = -1;
3275 }
3276 final long origId = Binder.clearCallingIdentity();
3277 try {
3278 synchronized (mService) {
3279
3280 for (int i=0; i<intents.length; i++) {
3281 Intent intent = intents[i];
3282 if (intent == null) {
3283 continue;
3284 }
3285
3286 // Refuse possible leaked file descriptors
3287 if (intent != null && intent.hasFileDescriptors()) {
3288 throw new IllegalArgumentException("File descriptors passed in Intent");
3289 }
3290
3291 boolean componentSpecified = intent.getComponent() != null;
3292
3293 // Don't modify the client's object!
3294 intent = new Intent(intent);
3295
3296 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003297 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003298 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003299 // TODO: New, check if this is correct
3300 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003301
3302 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3303 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3304 throw new IllegalArgumentException(
3305 "FLAG_CANT_SAVE_STATE not supported here");
3306 }
3307
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003308 Bundle theseOptions;
3309 if (options != null && i == intents.length-1) {
3310 theseOptions = options;
3311 } else {
3312 theseOptions = null;
3313 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003314 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackborna4972e92012-03-14 10:38:05 -07003315 aInfo, resultTo, null, -1, callingPid, callingUid,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003316 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003317 if (res < 0) {
3318 return res;
3319 }
3320
Dianne Hackbornbe707852011-11-11 14:32:10 -08003321 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003322 }
3323 }
3324 } finally {
3325 Binder.restoreCallingIdentity(origId);
3326 }
3327
Dianne Hackborna4972e92012-03-14 10:38:05 -07003328 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003329 }
3330
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003331 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3332 long thisTime, long totalTime) {
3333 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3334 WaitResult w = mWaitingActivityLaunched.get(i);
3335 w.timeout = timeout;
3336 if (r != null) {
3337 w.who = new ComponentName(r.info.packageName, r.info.name);
3338 }
3339 w.thisTime = thisTime;
3340 w.totalTime = totalTime;
3341 }
3342 mService.notifyAll();
3343 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003344
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003345 void reportActivityVisibleLocked(ActivityRecord r) {
3346 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3347 WaitResult w = mWaitingActivityVisible.get(i);
3348 w.timeout = false;
3349 if (r != null) {
3350 w.who = new ComponentName(r.info.packageName, r.info.name);
3351 }
3352 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3353 w.thisTime = w.totalTime;
3354 }
3355 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003356
3357 if (mDismissKeyguardOnNextActivity) {
3358 mDismissKeyguardOnNextActivity = false;
3359 mService.mWindowManager.dismissKeyguard();
3360 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003361 }
3362
3363 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3364 String resultWho, int requestCode, int resultCode, Intent data) {
3365
3366 if (callingUid > 0) {
3367 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003368 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003369 }
3370
3371 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3372 + " : who=" + resultWho + " req=" + requestCode
3373 + " res=" + resultCode + " data=" + data);
3374 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3375 try {
3376 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3377 list.add(new ResultInfo(resultWho, requestCode,
3378 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003379 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003380 return;
3381 } catch (Exception e) {
3382 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3383 }
3384 }
3385
3386 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3387 }
3388
3389 private final void stopActivityLocked(ActivityRecord r) {
3390 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3391 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3392 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3393 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003394 if (!mService.mSleeping) {
3395 if (DEBUG_STATES) {
3396 Slog.d(TAG, "no-history finish of " + r);
3397 }
3398 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003399 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003400 } else {
3401 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3402 + " on stop because we're just sleeping");
3403 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003404 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003405 }
3406
3407 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003408 if (mMainStack) {
3409 if (mService.mFocusedActivity == r) {
3410 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3411 }
3412 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003413 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003414 try {
3415 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003416 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3417 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003418 r.state = ActivityState.STOPPING;
3419 if (DEBUG_VISBILITY) Slog.v(
3420 TAG, "Stopping visible=" + r.visible + " for " + r);
3421 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003422 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003423 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003424 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003425 if (mService.isSleeping()) {
3426 r.setSleeping(true);
3427 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003428 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3429 msg.obj = r;
3430 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003431 } catch (Exception e) {
3432 // Maybe just ignore exceptions here... if the process
3433 // has crashed, our death notification will clean things
3434 // up.
3435 Slog.w(TAG, "Exception thrown during pause", e);
3436 // Just in case, assume it to be stopped.
3437 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003438 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003439 r.state = ActivityState.STOPPED;
3440 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003441 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003442 }
3443 }
3444 }
3445 }
3446
3447 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3448 boolean remove) {
3449 int N = mStoppingActivities.size();
3450 if (N <= 0) return null;
3451
3452 ArrayList<ActivityRecord> stops = null;
3453
3454 final boolean nowVisible = mResumedActivity != null
3455 && mResumedActivity.nowVisible
3456 && !mResumedActivity.waitingVisible;
3457 for (int i=0; i<N; i++) {
3458 ActivityRecord s = mStoppingActivities.get(i);
3459 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3460 + nowVisible + " waitingVisible=" + s.waitingVisible
3461 + " finishing=" + s.finishing);
3462 if (s.waitingVisible && nowVisible) {
3463 mWaitingVisibleActivities.remove(s);
3464 s.waitingVisible = false;
3465 if (s.finishing) {
3466 // If this activity is finishing, it is sitting on top of
3467 // everyone else but we now know it is no longer needed...
3468 // so get rid of it. Otherwise, we need to go through the
3469 // normal flow and hide it once we determine that it is
3470 // hidden by the activities in front of it.
3471 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003472 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003473 }
3474 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003475 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003476 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3477 if (stops == null) {
3478 stops = new ArrayList<ActivityRecord>();
3479 }
3480 stops.add(s);
3481 mStoppingActivities.remove(i);
3482 N--;
3483 i--;
3484 }
3485 }
3486
3487 return stops;
3488 }
3489
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003490 final void scheduleIdleLocked() {
3491 Message msg = Message.obtain();
3492 msg.what = IDLE_NOW_MSG;
3493 mHandler.sendMessage(msg);
3494 }
3495
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003496 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003497 Configuration config) {
3498 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3499
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003500 ActivityRecord res = null;
3501
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003502 ArrayList<ActivityRecord> stops = null;
3503 ArrayList<ActivityRecord> finishes = null;
3504 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003505 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003506 int NS = 0;
3507 int NF = 0;
3508 int NT = 0;
3509 IApplicationThread sendThumbnail = null;
3510 boolean booting = false;
3511 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003512 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003513
3514 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003515 ActivityRecord r = ActivityRecord.forToken(token);
3516 if (r != null) {
3517 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003518 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003519 }
3520
3521 // Get the activity record.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003522 int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003523 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003524 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003525
3526 if (fromTimeout) {
3527 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3528 }
3529
3530 // This is a hack to semi-deal with a race condition
3531 // in the client where it can be constructed with a
3532 // newer configuration from when we asked it to launch.
3533 // We'll update with whatever configuration it now says
3534 // it used to launch.
3535 if (config != null) {
3536 r.configuration = config;
3537 }
3538
3539 // No longer need to keep the device awake.
3540 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3541 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3542 mLaunchingActivity.release();
3543 }
3544
3545 // We are now idle. If someone is waiting for a thumbnail from
3546 // us, we can now deliver.
3547 r.idle = true;
3548 mService.scheduleAppGcsLocked();
3549 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3550 sendThumbnail = r.app.thread;
3551 r.thumbnailNeeded = false;
3552 }
3553
3554 // If this activity is fullscreen, set up to hide those under it.
3555
3556 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3557 ensureActivitiesVisibleLocked(null, 0);
3558
3559 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3560 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003561 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003562 mService.mBooted = true;
3563 enableScreen = true;
3564 }
3565 }
3566
3567 } else if (fromTimeout) {
3568 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3569 }
3570
3571 // Atomically retrieve all of the other things to do.
3572 stops = processStoppingActivitiesLocked(true);
3573 NS = stops != null ? stops.size() : 0;
3574 if ((NF=mFinishingActivities.size()) > 0) {
3575 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3576 mFinishingActivities.clear();
3577 }
3578 if ((NT=mService.mCancelledThumbnails.size()) > 0) {
3579 thumbnails = new ArrayList<ActivityRecord>(mService.mCancelledThumbnails);
3580 mService.mCancelledThumbnails.clear();
3581 }
3582
3583 if (mMainStack) {
3584 booting = mService.mBooting;
3585 mService.mBooting = false;
3586 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003587 if (mStartingUsers.size() > 0) {
3588 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3589 mStartingUsers.clear();
3590 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003591 }
3592
3593 int i;
3594
3595 // Send thumbnail if requested.
3596 if (sendThumbnail != null) {
3597 try {
3598 sendThumbnail.requestThumbnail(token);
3599 } catch (Exception e) {
3600 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3601 mService.sendPendingThumbnail(null, token, null, null, true);
3602 }
3603 }
3604
3605 // Stop any activities that are scheduled to do so but have been
3606 // waiting for the next one to start.
3607 for (i=0; i<NS; i++) {
3608 ActivityRecord r = (ActivityRecord)stops.get(i);
3609 synchronized (mService) {
3610 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003611 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003612 } else {
3613 stopActivityLocked(r);
3614 }
3615 }
3616 }
3617
3618 // Finish any activities that are scheduled to do so but have been
3619 // waiting for the next one to start.
3620 for (i=0; i<NF; i++) {
3621 ActivityRecord r = (ActivityRecord)finishes.get(i);
3622 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003623 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003624 }
3625 }
3626
3627 // Report back to any thumbnail receivers.
3628 for (i=0; i<NT; i++) {
3629 ActivityRecord r = (ActivityRecord)thumbnails.get(i);
3630 mService.sendPendingThumbnail(r, null, null, null, true);
3631 }
3632
3633 if (booting) {
3634 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003635 } else if (startingUsers != null) {
3636 for (i=0; i<startingUsers.size(); i++) {
3637 mService.finishUserSwitch(startingUsers.get(i));
3638 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003639 }
3640
3641 mService.trimApplications();
3642 //dump();
3643 //mWindowManager.dump();
3644
3645 if (enableScreen) {
3646 mService.enableScreenAfterBoot();
3647 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003648
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003649 if (activityRemoved) {
3650 resumeTopActivityLocked(null);
3651 }
3652
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003653 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003654 }
3655
3656 /**
3657 * @return Returns true if the activity is being finished, false if for
3658 * some reason it is being left as-is.
3659 */
3660 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003661 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003662 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003663 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003664 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003665 + ", result=" + resultCode + ", data=" + resultData
3666 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003667 if (index < 0) {
3668 return false;
3669 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003670 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003671
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003672 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003673 return true;
3674 }
3675
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003676 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3677 ActivityRecord self = isInStackLocked(token);
3678 if (self == null) {
3679 return;
3680 }
3681
3682 int i;
3683 for (i=mHistory.size()-1; i>=0; i--) {
3684 ActivityRecord r = (ActivityRecord)mHistory.get(i);
3685 if (r.resultTo == self && r.requestCode == requestCode) {
3686 if ((r.resultWho == null && resultWho == null) ||
3687 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3688 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003689 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003690 }
3691 }
3692 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003693 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003694 }
3695
3696 final boolean finishActivityAffinityLocked(IBinder token) {
3697 int index = indexOfTokenLocked(token);
3698 if (DEBUG_RESULTS) Slog.v(
3699 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3700 if (index < 0) {
3701 return false;
3702 }
3703 ActivityRecord r = mHistory.get(index);
3704
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003705 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003706 ActivityRecord cur = mHistory.get(index);
3707 if (cur.task != r.task) {
3708 break;
3709 }
3710 if (cur.taskAffinity == null && r.taskAffinity != null) {
3711 break;
3712 }
3713 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3714 break;
3715 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003716 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3717 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003718 index--;
3719 }
3720 return true;
3721 }
3722
Dianne Hackborn5c607432012-02-28 14:44:19 -08003723 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3724 // send the result
3725 ActivityRecord resultTo = r.resultTo;
3726 if (resultTo != null) {
3727 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3728 + " who=" + r.resultWho + " req=" + r.requestCode
3729 + " res=" + resultCode + " data=" + resultData);
3730 if (r.info.applicationInfo.uid > 0) {
3731 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3732 resultTo.packageName, resultData,
3733 resultTo.getUriPermissionsLocked());
3734 }
3735 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3736 resultData);
3737 r.resultTo = null;
3738 }
3739 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3740
3741 // Make sure this HistoryRecord is not holding on to other resources,
3742 // because clients have remote IPC references to this object so we
3743 // can't assume that will go away and want to avoid circular IPC refs.
3744 r.results = null;
3745 r.pendingResults = null;
3746 r.newIntents = null;
3747 r.icicle = null;
3748 }
3749
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003750 /**
3751 * @return Returns true if this activity has been removed from the history
3752 * list, or false if it is still in the list and will be removed later.
3753 */
3754 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003755 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3756 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003757 }
3758
3759 /**
3760 * @return Returns true if this activity has been removed from the history
3761 * list, or false if it is still in the list and will be removed later.
3762 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003763 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3764 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003765 if (r.finishing) {
3766 Slog.w(TAG, "Duplicate finish request for " + r);
3767 return false;
3768 }
3769
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003770 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003771 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003772 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003773 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003774 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003775 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003776 if (next.task == r.task) {
3777 if (r.frontOfTask) {
3778 // The next activity is now the front of the task.
3779 next.frontOfTask = true;
3780 }
3781 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3782 // If the caller asked that this activity (and all above it)
3783 // be cleared when the task is reset, don't lose that information,
3784 // but propagate it up to the next activity.
3785 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3786 }
3787 }
3788 }
3789
3790 r.pauseKeyDispatchingLocked();
3791 if (mMainStack) {
3792 if (mService.mFocusedActivity == r) {
3793 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3794 }
3795 }
3796
Dianne Hackborn5c607432012-02-28 14:44:19 -08003797 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003798
3799 if (mService.mPendingThumbnails.size() > 0) {
3800 // There are clients waiting to receive thumbnails so, in case
3801 // this is an activity that someone is waiting for, add it
3802 // to the pending list so we can correctly update the clients.
3803 mService.mCancelledThumbnails.add(r);
3804 }
3805
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003806 if (immediate) {
3807 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003808 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003809 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003810 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003811 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003812 if (DEBUG_TRANSITION) Slog.v(TAG,
3813 "Prepare close transition: finishing " + r);
3814 mService.mWindowManager.prepareAppTransition(endTask
3815 ? WindowManagerPolicy.TRANSIT_TASK_CLOSE
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003816 : WindowManagerPolicy.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003817
3818 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003819 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003820
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003821 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003822 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3823 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3824 startPausingLocked(false, false);
3825 }
3826
3827 } else if (r.state != ActivityState.PAUSING) {
3828 // If the activity is PAUSING, we will complete the finish once
3829 // it is done pausing; else we can just directly finish it here.
3830 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3831 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003832 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003833 } else {
3834 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3835 }
3836
3837 return false;
3838 }
3839
3840 private static final int FINISH_IMMEDIATELY = 0;
3841 private static final int FINISH_AFTER_PAUSE = 1;
3842 private static final int FINISH_AFTER_VISIBLE = 2;
3843
3844 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003845 int mode, boolean oomAdj) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003846 final int index = indexOfActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003847 if (index < 0) {
3848 return null;
3849 }
3850
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003851 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003852 }
3853
3854 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003855 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003856 // First things first: if this activity is currently visible,
3857 // and the resumed activity is not yet visible, then hold off on
3858 // finishing until the resumed one becomes visible.
3859 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3860 if (!mStoppingActivities.contains(r)) {
3861 mStoppingActivities.add(r);
3862 if (mStoppingActivities.size() > 3) {
3863 // If we already have a few activities waiting to stop,
3864 // then give up on things going idle and start clearing
3865 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003866 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003867 } else {
3868 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003869 }
3870 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003871 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3872 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003873 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003874 if (oomAdj) {
3875 mService.updateOomAdjLocked();
3876 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877 return r;
3878 }
3879
3880 // make sure the record is cleaned out of other places.
3881 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003882 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003883 mWaitingVisibleActivities.remove(r);
3884 if (mResumedActivity == r) {
3885 mResumedActivity = null;
3886 }
3887 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003888 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003889 r.state = ActivityState.FINISHING;
3890
3891 if (mode == FINISH_IMMEDIATELY
3892 || prevState == ActivityState.STOPPED
3893 || prevState == ActivityState.INITIALIZING) {
3894 // If this activity is already stopped, we can just finish
3895 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003896 boolean activityRemoved = destroyActivityLocked(r, true,
3897 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003898 if (activityRemoved) {
3899 resumeTopActivityLocked(null);
3900 }
3901 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003902 } else {
3903 // Need to go through the full pause cycle to get this
3904 // activity into the stopped state and then finish it.
3905 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3906 mFinishingActivities.add(r);
3907 resumeTopActivityLocked(null);
3908 }
3909 return r;
3910 }
3911
3912 /**
3913 * Perform the common clean-up of an activity record. This is called both
3914 * as part of destroyActivityLocked() (when destroying the client-side
3915 * representation) and cleaning things up as a result of its hosting
3916 * processing going away, in which case there is no remaining client-side
3917 * state to destroy so only the cleanup here is needed.
3918 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003919 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
3920 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003921 if (mResumedActivity == r) {
3922 mResumedActivity = null;
3923 }
3924 if (mService.mFocusedActivity == r) {
3925 mService.mFocusedActivity = null;
3926 }
3927
3928 r.configDestroy = false;
3929 r.frozenBeforeDestroy = false;
3930
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003931 if (setState) {
3932 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
3933 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003934 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003935 }
3936
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003937 // Make sure this record is no longer in the pending finishes list.
3938 // This could happen, for example, if we are trimming activities
3939 // down to the max limit while they are still waiting to finish.
3940 mFinishingActivities.remove(r);
3941 mWaitingVisibleActivities.remove(r);
3942
3943 // Remove any pending results.
3944 if (r.finishing && r.pendingResults != null) {
3945 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
3946 PendingIntentRecord rec = apr.get();
3947 if (rec != null) {
3948 mService.cancelIntentSenderLocked(rec, false);
3949 }
3950 }
3951 r.pendingResults = null;
3952 }
3953
3954 if (cleanServices) {
3955 cleanUpActivityServicesLocked(r);
3956 }
3957
3958 if (mService.mPendingThumbnails.size() > 0) {
3959 // There are clients waiting to receive thumbnails so, in case
3960 // this is an activity that someone is waiting for, add it
3961 // to the pending list so we can correctly update the clients.
3962 mService.mCancelledThumbnails.add(r);
3963 }
3964
3965 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003966 removeTimeoutsForActivityLocked(r);
3967 }
3968
3969 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003970 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003971 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003972 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003973 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003974 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003975 }
3976
Dianne Hackborn5c607432012-02-28 14:44:19 -08003977 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003978 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
3979 r.makeFinishing();
3980 if (DEBUG_ADD_REMOVE) {
3981 RuntimeException here = new RuntimeException("here");
3982 here.fillInStackTrace();
3983 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003984 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07003985 mHistory.remove(r);
3986 r.takeFromHistory();
3987 removeTimeoutsForActivityLocked(r);
3988 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
3989 + " (removed from history)");
3990 r.state = ActivityState.DESTROYED;
3991 r.app = null;
3992 mService.mWindowManager.removeAppToken(r.appToken);
3993 if (VALIDATE_TOKENS) {
3994 validateAppTokensLocked();
3995 }
3996 cleanUpActivityServicesLocked(r);
3997 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003998 }
3999
4000 /**
4001 * Perform clean-up of service connections in an activity record.
4002 */
4003 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4004 // Throw away any services that have been bound by this activity.
4005 if (r.connections != null) {
4006 Iterator<ConnectionRecord> it = r.connections.iterator();
4007 while (it.hasNext()) {
4008 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004009 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004010 }
4011 r.connections = null;
4012 }
4013 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004014
4015 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4016 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4017 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4018 mHandler.sendMessage(msg);
4019 }
4020
Dianne Hackborn28695e02011-11-02 21:59:51 -07004021 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004022 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004023 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004024 for (int i=mHistory.size()-1; i>=0; i--) {
4025 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004026 if (r.finishing) {
4027 continue;
4028 }
4029 if (r.fullscreen) {
4030 lastIsOpaque = true;
4031 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004032 if (owner != null && r.app != owner) {
4033 continue;
4034 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004035 if (!lastIsOpaque) {
4036 continue;
4037 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004038 // We can destroy this one if we have its icicle saved and
4039 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004040 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4041 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004042 && r.state != ActivityState.DESTROYING
4043 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004044 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4045 + " resumed=" + mResumedActivity
4046 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004047 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4048 activityRemoved = true;
4049 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004050 }
4051 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004052 if (activityRemoved) {
4053 resumeTopActivityLocked(null);
4054 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004055 }
4056
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004057 /**
4058 * Destroy the current CLIENT SIDE instance of an activity. This may be
4059 * called both when actually finishing an activity, or when performing
4060 * a configuration switch where we destroy the current client-side object
4061 * but then create a new client-side object for this same HistoryRecord.
4062 */
4063 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004064 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004065 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004066 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004067 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4068 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004069 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004070 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004071
4072 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004073
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004074 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004075
4076 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004077
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004078 if (hadApp) {
4079 if (removeFromApp) {
4080 int idx = r.app.activities.indexOf(r);
4081 if (idx >= 0) {
4082 r.app.activities.remove(idx);
4083 }
4084 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4085 mService.mHeavyWeightProcess = null;
4086 mService.mHandler.sendEmptyMessage(
4087 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4088 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004089 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004090 // No longer have activities, so update oom adj.
4091 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004092 }
4093 }
4094
4095 boolean skipDestroy = false;
4096
4097 try {
4098 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004099 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004100 r.configChangeFlags);
4101 } catch (Exception e) {
4102 // We can just ignore exceptions here... if the process
4103 // has crashed, our death notification will clean things
4104 // up.
4105 //Slog.w(TAG, "Exception thrown during finish", e);
4106 if (r.finishing) {
4107 removeActivityFromHistoryLocked(r);
4108 removedFromHistory = true;
4109 skipDestroy = true;
4110 }
4111 }
4112
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004113 r.nowVisible = false;
4114
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004115 // If the activity is finishing, we need to wait on removing it
4116 // from the list to give it a chance to do its cleanup. During
4117 // that time it may make calls back with its token so we need to
4118 // be able to find it on the list and so we don't want to remove
4119 // it from the list yet. Otherwise, we can just immediately put
4120 // it in the destroyed state since we are not removing it from the
4121 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004122 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004123 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4124 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004125 r.state = ActivityState.DESTROYING;
4126 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4127 msg.obj = r;
4128 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4129 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004130 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4131 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004132 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004133 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004134 }
4135 } else {
4136 // remove this record from the history.
4137 if (r.finishing) {
4138 removeActivityFromHistoryLocked(r);
4139 removedFromHistory = true;
4140 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004141 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4142 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004143 r.state = ActivityState.DESTROYED;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004144 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004145 }
4146 }
4147
4148 r.configChangeFlags = 0;
4149
4150 if (!mLRUActivities.remove(r) && hadApp) {
4151 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4152 }
4153
4154 return removedFromHistory;
4155 }
4156
4157 final void activityDestroyed(IBinder token) {
4158 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004159 final long origId = Binder.clearCallingIdentity();
4160 try {
4161 ActivityRecord r = ActivityRecord.forToken(token);
4162 if (r != null) {
4163 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004164 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004165
4166 int index = indexOfActivityLocked(r);
4167 if (index >= 0) {
4168 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004169 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004170 removeActivityFromHistoryLocked(r);
4171 }
4172 }
4173 resumeTopActivityLocked(null);
4174 } finally {
4175 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004176 }
4177 }
4178 }
4179
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004180 private void removeHistoryRecordsForAppLocked(ArrayList list, ProcessRecord app,
4181 String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004182 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004183 if (DEBUG_CLEANUP) Slog.v(
4184 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004185 + " with " + i + " entries");
4186 while (i > 0) {
4187 i--;
4188 ActivityRecord r = (ActivityRecord)list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004189 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004190 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004191 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004192 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004193 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004194 }
4195 }
4196 }
4197
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004198 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4199 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4200 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4201 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4202 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4203 "mWaitingVisibleActivities");
4204 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4205
4206 boolean hasVisibleActivities = false;
4207
4208 // Clean out the history list.
4209 int i = mHistory.size();
4210 if (DEBUG_CLEANUP) Slog.v(
4211 TAG, "Removing app " + app + " from history with " + i + " entries");
4212 while (i > 0) {
4213 i--;
4214 ActivityRecord r = (ActivityRecord)mHistory.get(i);
4215 if (DEBUG_CLEANUP) Slog.v(
4216 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4217 if (r.app == app) {
4218 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4219 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4220 RuntimeException here = new RuntimeException("here");
4221 here.fillInStackTrace();
4222 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4223 + ": haveState=" + r.haveState
4224 + " stateNotNeeded=" + r.stateNotNeeded
4225 + " finishing=" + r.finishing
4226 + " state=" + r.state, here);
4227 }
4228 if (!r.finishing) {
4229 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4230 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4231 r.userId, System.identityHashCode(r),
4232 r.task.taskId, r.shortComponentName,
4233 "proc died without state saved");
4234 }
4235 removeActivityFromHistoryLocked(r);
4236
4237 } else {
4238 // We have the current state for this activity, so
4239 // it can be restarted later when needed.
4240 if (localLOGV) Slog.v(
4241 TAG, "Keeping entry, setting app to null");
4242 if (r.visible) {
4243 hasVisibleActivities = true;
4244 }
4245 r.app = null;
4246 r.nowVisible = false;
4247 if (!r.haveState) {
4248 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4249 "App died, clearing saved state of " + r);
4250 r.icicle = null;
4251 }
4252 }
4253
4254 r.stack.cleanUpActivityLocked(r, true, true);
4255 }
4256 }
4257
4258 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004259 }
4260
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004261 /**
4262 * Move the current home activity's task (if one exists) to the front
4263 * of the stack.
4264 */
4265 final void moveHomeToFrontLocked() {
4266 TaskRecord homeTask = null;
4267 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004268 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004269 if (hr.isHomeActivity) {
4270 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004271 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004272 }
4273 }
4274 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004275 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004276 }
4277 }
4278
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004279 final void updateTransitLocked(int transit, Bundle options) {
4280 if (options != null) {
4281 ActivityRecord r = topRunningActivityLocked(null);
4282 if (r != null && r.state != ActivityState.RESUMED) {
4283 r.updateOptionsLocked(options);
4284 } else {
4285 ActivityOptions.abort(options);
4286 }
4287 }
4288 mService.mWindowManager.prepareAppTransition(transit, false);
4289 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004290
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004291 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004292 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4293
4294 final int task = tr.taskId;
4295 int top = mHistory.size()-1;
4296
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004297 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004298 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004299 if (reason != null &&
4300 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4301 ActivityOptions.abort(options);
4302 } else {
4303 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
4304 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004305 return;
4306 }
4307
Dianne Hackbornbe707852011-11-11 14:32:10 -08004308 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004309
4310 // Applying the affinities may have removed entries from the history,
4311 // so get the size again.
4312 top = mHistory.size()-1;
4313 int pos = top;
4314
4315 // Shift all activities with this task up to the top
4316 // of the stack, keeping them in the same internal order.
4317 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004318 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004319 if (localLOGV) Slog.v(
4320 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004321 if (r.task.taskId == task) {
4322 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004323 if (DEBUG_ADD_REMOVE) {
4324 RuntimeException here = new RuntimeException("here");
4325 here.fillInStackTrace();
4326 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4327 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004328 mHistory.remove(pos);
4329 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004330 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004331 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004332 }
4333 pos--;
4334 }
4335
4336 if (DEBUG_TRANSITION) Slog.v(TAG,
4337 "Prepare to front transition: task=" + tr);
4338 if (reason != null &&
4339 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004340 mService.mWindowManager.prepareAppTransition(
4341 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004342 ActivityRecord r = topRunningActivityLocked(null);
4343 if (r != null) {
4344 mNoAnimActivities.add(r);
4345 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004346 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004347 } else {
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004348 updateTransitLocked(WindowManagerPolicy.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004349 }
4350
4351 mService.mWindowManager.moveAppTokensToTop(moved);
4352 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004353 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004354 }
4355
4356 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004357 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004358 }
4359
4360 private final void finishTaskMoveLocked(int task) {
4361 resumeTopActivityLocked(null);
4362 }
4363
4364 /**
4365 * Worker method for rearranging history stack. Implements the function of moving all
4366 * activities for a specific task (gathering them if disjoint) into a single group at the
4367 * bottom of the stack.
4368 *
4369 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4370 * to premeptively cancel the move.
4371 *
4372 * @param task The taskId to collect and move to the bottom.
4373 * @return Returns true if the move completed, false if not.
4374 */
4375 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4376 Slog.i(TAG, "moveTaskToBack: " + task);
4377
4378 // If we have a watcher, preflight the move before committing to it. First check
4379 // for *other* available tasks, but if none are available, then try again allowing the
4380 // current task to be selected.
4381 if (mMainStack && mService.mController != null) {
4382 ActivityRecord next = topRunningActivityLocked(null, task);
4383 if (next == null) {
4384 next = topRunningActivityLocked(null, 0);
4385 }
4386 if (next != null) {
4387 // ask watcher if this is allowed
4388 boolean moveOK = true;
4389 try {
4390 moveOK = mService.mController.activityResuming(next.packageName);
4391 } catch (RemoteException e) {
4392 mService.mController = null;
4393 }
4394 if (!moveOK) {
4395 return false;
4396 }
4397 }
4398 }
4399
Dianne Hackbornbe707852011-11-11 14:32:10 -08004400 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004401
4402 if (DEBUG_TRANSITION) Slog.v(TAG,
4403 "Prepare to back transition: task=" + task);
4404
4405 final int N = mHistory.size();
4406 int bottom = 0;
4407 int pos = 0;
4408
4409 // Shift all activities with this task down to the bottom
4410 // of the stack, keeping them in the same internal order.
4411 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004412 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004413 if (localLOGV) Slog.v(
4414 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4415 if (r.task.taskId == task) {
4416 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004417 if (DEBUG_ADD_REMOVE) {
4418 RuntimeException here = new RuntimeException("here");
4419 here.fillInStackTrace();
4420 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4421 + bottom, here);
4422 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004423 mHistory.remove(pos);
4424 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004425 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004426 bottom++;
4427 }
4428 pos++;
4429 }
4430
4431 if (reason != null &&
4432 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004433 mService.mWindowManager.prepareAppTransition(
4434 WindowManagerPolicy.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004435 ActivityRecord r = topRunningActivityLocked(null);
4436 if (r != null) {
4437 mNoAnimActivities.add(r);
4438 }
4439 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004440 mService.mWindowManager.prepareAppTransition(
4441 WindowManagerPolicy.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004442 }
4443 mService.mWindowManager.moveAppTokensToBottom(moved);
4444 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004445 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004446 }
4447
4448 finishTaskMoveLocked(task);
4449 return true;
4450 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004451
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004452 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4453 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4454 ActivityRecord resumed = mResumedActivity;
4455 if (resumed != null && resumed.thumbHolder == tr) {
4456 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004457 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004458 if (info.mainThumbnail == null) {
4459 info.mainThumbnail = tr.lastThumbnail;
4460 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004461 return info;
4462 }
4463
Dianne Hackborn15491c62012-09-19 10:59:14 -07004464 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4465 ActivityRecord resumed = mResumedActivity;
4466 if (resumed != null && resumed.task == tr) {
4467 // This task is the current resumed task, we just need to take
4468 // a screenshot of it and return that.
4469 return resumed.stack.screenshotActivities(resumed);
4470 }
4471 // Return the information about the task, to figure out the top
4472 // thumbnail to return.
4473 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4474 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004475 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004476 } else {
4477 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
4478 }
4479 }
4480
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004481 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4482 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004483 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4484 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004485 if (taskRequired) {
4486 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4487 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004488 return null;
4489 }
4490
4491 if (subTaskIndex < 0) {
4492 // Just remove the entire task.
4493 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4494 return info.root;
4495 }
4496
4497 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004498 if (taskRequired) {
4499 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4500 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004501 return null;
4502 }
4503
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004504 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004505 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4506 performClearTaskAtIndexLocked(taskId, subtask.index);
4507 return subtask.activity;
4508 }
4509
4510 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004511 final TaskAccessInfo thumbs = new TaskAccessInfo();
4512 // How many different sub-thumbnails?
4513 final int NA = mHistory.size();
4514 int j = 0;
4515 ThumbnailHolder holder = null;
4516 while (j < NA) {
4517 ActivityRecord ar = mHistory.get(j);
4518 if (!ar.finishing && ar.task.taskId == taskId) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004519 thumbs.root = ar;
4520 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004521 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004522 if (holder != null) {
4523 thumbs.mainThumbnail = holder.lastThumbnail;
4524 }
4525 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004526 break;
4527 }
4528 j++;
4529 }
4530
4531 if (j >= NA) {
4532 return thumbs;
4533 }
4534
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004535 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4536 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004537 while (j < NA) {
4538 ActivityRecord ar = mHistory.get(j);
4539 j++;
4540 if (ar.finishing) {
4541 continue;
4542 }
4543 if (ar.task.taskId != taskId) {
4544 break;
4545 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004546 if (ar.thumbHolder != holder && holder != null) {
4547 thumbs.numSubThumbbails++;
4548 holder = ar.thumbHolder;
4549 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004550 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004551 sub.activity = ar;
4552 sub.index = j-1;
4553 subtasks.add(sub);
4554 }
4555 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004556 if (thumbs.numSubThumbbails > 0) {
4557 thumbs.retriever = new IThumbnailRetriever.Stub() {
4558 public Bitmap getThumbnail(int index) {
4559 if (index < 0 || index >= thumbs.subtasks.size()) {
4560 return null;
4561 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004562 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4563 ActivityRecord resumed = mResumedActivity;
4564 if (resumed != null && resumed.thumbHolder == sub.holder) {
4565 return resumed.stack.screenshotActivities(resumed);
4566 }
4567 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004568 }
4569 };
4570 }
4571 return thumbs;
4572 }
4573
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004574 private final void logStartActivity(int tag, ActivityRecord r,
4575 TaskRecord task) {
4576 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004577 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004578 r.shortComponentName, r.intent.getAction(),
4579 r.intent.getType(), r.intent.getDataString(),
4580 r.intent.getFlags());
4581 }
4582
4583 /**
4584 * Make sure the given activity matches the current configuration. Returns
4585 * false if the activity had to be destroyed. Returns true if the
4586 * configuration is the same, or the activity will remain running as-is
4587 * for whatever reason. Ensures the HistoryRecord is updated with the
4588 * correct configuration and all other bookkeeping is handled.
4589 */
4590 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4591 int globalChanges) {
4592 if (mConfigWillChange) {
4593 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4594 "Skipping config check (will change): " + r);
4595 return true;
4596 }
4597
4598 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4599 "Ensuring correct configuration: " + r);
4600
4601 // Short circuit: if the two configurations are the exact same
4602 // object (the common case), then there is nothing to do.
4603 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004604 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004605 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4606 "Configuration unchanged in " + r);
4607 return true;
4608 }
4609
4610 // We don't worry about activities that are finishing.
4611 if (r.finishing) {
4612 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4613 "Configuration doesn't matter in finishing " + r);
4614 r.stopFreezingScreenLocked(false);
4615 return true;
4616 }
4617
4618 // Okay we now are going to make this activity have the new config.
4619 // But then we need to figure out how it needs to deal with that.
4620 Configuration oldConfig = r.configuration;
4621 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004622
4623 // Determine what has changed. May be nothing, if this is a config
4624 // that has come back from the app after going idle. In that case
4625 // we just want to leave the official config object now in the
4626 // activity and do nothing else.
4627 final int changes = oldConfig.diff(newConfig);
4628 if (changes == 0 && !r.forceNewConfig) {
4629 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4630 "Configuration no differences in " + r);
4631 return true;
4632 }
4633
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004634 // If the activity isn't currently running, just leave the new
4635 // configuration and it will pick that up next time it starts.
4636 if (r.app == null || r.app.thread == null) {
4637 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4638 "Configuration doesn't matter not running " + r);
4639 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004640 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004641 return true;
4642 }
4643
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004644 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004645 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4646 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4647 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004648 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004649 + ", newConfig=" + newConfig);
4650 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004651 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004652 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4653 r.configChangeFlags |= changes;
4654 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004655 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004656 if (r.app == null || r.app.thread == null) {
4657 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004658 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004659 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004660 } else if (r.state == ActivityState.PAUSING) {
4661 // A little annoying: we are waiting for this activity to
4662 // finish pausing. Let's not do anything now, but just
4663 // flag that it needs to be restarted when done pausing.
4664 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004665 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004666 r.configDestroy = true;
4667 return true;
4668 } else if (r.state == ActivityState.RESUMED) {
4669 // Try to optimize this case: the configuration is changing
4670 // and we need to restart the top, resumed activity.
4671 // Instead of doing the normal handshaking, just say
4672 // "restart!".
4673 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004674 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004675 relaunchActivityLocked(r, r.configChangeFlags, true);
4676 r.configChangeFlags = 0;
4677 } else {
4678 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004679 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004680 relaunchActivityLocked(r, r.configChangeFlags, false);
4681 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004682 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004683
4684 // All done... tell the caller we weren't able to keep this
4685 // activity around.
4686 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004687 }
4688
4689 // Default case: the activity can handle this new configuration, so
4690 // hand it over. Note that we don't need to give it the new
4691 // configuration, since we always send configuration changes to all
4692 // process when they happen so it can just use whatever configuration
4693 // it last got.
4694 if (r.app != null && r.app.thread != null) {
4695 try {
4696 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004697 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004698 } catch (RemoteException e) {
4699 // If process died, whatever.
4700 }
4701 }
4702 r.stopFreezingScreenLocked(false);
4703
4704 return true;
4705 }
4706
4707 private final boolean relaunchActivityLocked(ActivityRecord r,
4708 int changes, boolean andResume) {
4709 List<ResultInfo> results = null;
4710 List<Intent> newIntents = null;
4711 if (andResume) {
4712 results = r.results;
4713 newIntents = r.newIntents;
4714 }
4715 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4716 + " with results=" + results + " newIntents=" + newIntents
4717 + " andResume=" + andResume);
4718 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004719 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004720 r.task.taskId, r.shortComponentName);
4721
4722 r.startFreezingScreenLocked(r.app, 0);
4723
4724 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004725 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4726 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4727 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004728 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004729 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004730 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004731 // Note: don't need to call pauseIfSleepingLocked() here, because
4732 // the caller will only pass in 'andResume' if this activity is
4733 // currently resumed, which implies we aren't sleeping.
4734 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004735 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004736 }
4737
4738 if (andResume) {
4739 r.results = null;
4740 r.newIntents = null;
4741 if (mMainStack) {
4742 mService.reportResumedActivityLocked(r);
4743 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004744 r.state = ActivityState.RESUMED;
4745 } else {
4746 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4747 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004748 }
4749
4750 return true;
4751 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004752
4753 public void dismissKeyguardOnNextActivityLocked() {
4754 mDismissKeyguardOnNextActivity = true;
4755 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004756}