blob: b4ded2ecf187e4ab19a63ca5b405775fc3d0bc60 [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;
Craig Mautnerd74f7d72013-02-26 13:41:02 -080024import com.android.internal.util.Objects;
Craig Mautnercae015f2013-02-08 14:31:27 -080025import com.android.server.am.ActivityManagerService.ItemMatcher;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070026import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
Craig Mautner4b71aa12012-12-27 17:20:01 -080027import com.android.server.wm.AppTransition;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080028import com.android.server.wm.TaskGroup;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070029
30import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070031import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070032import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070033import android.app.AppGlobals;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080034import android.app.IActivityController;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070035import android.app.IActivityManager;
Craig Mautnercae015f2013-02-08 14:31:27 -080036import android.app.IThumbnailReceiver;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070037import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070038import android.app.IApplicationThread;
39import android.app.PendingIntent;
40import android.app.ResultInfo;
Craig Mautnercae015f2013-02-08 14:31:27 -080041import android.app.ActivityManager.RunningTaskInfo;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070042import android.app.IActivityManager.WaitResult;
43import android.content.ComponentName;
44import android.content.Context;
45import android.content.IIntentSender;
46import android.content.Intent;
47import android.content.IntentSender;
48import android.content.pm.ActivityInfo;
49import android.content.pm.ApplicationInfo;
50import android.content.pm.PackageManager;
51import android.content.pm.ResolveInfo;
52import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080053import android.content.res.Resources;
54import android.graphics.Bitmap;
Craig Mautnerb12428a2012-12-20 16:07:06 -080055import android.graphics.Bitmap.Config;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070056import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070057import android.os.Bundle;
Craig Mautner5d9c7be2013-02-15 14:02:56 -080058import android.os.Debug;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070059import android.os.Handler;
60import android.os.IBinder;
Zoran Marcetaf958b322012-08-09 20:27:12 +090061import android.os.Looper;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070062import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070063import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070064import android.os.PowerManager;
65import android.os.RemoteException;
66import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070067import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070068import android.util.EventLog;
69import android.util.Log;
70import android.util.Slog;
Craig Mautner5d9c7be2013-02-15 14:02:56 -080071import android.util.SparseArray;
Craig Mautner59c00972012-07-30 12:10:24 -070072import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070073
Craig Mautnercae015f2013-02-08 14:31:27 -080074import java.io.FileDescriptor;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070075import java.io.IOException;
Craig Mautnercae015f2013-02-08 14:31:27 -080076import java.io.PrintWriter;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070077import java.lang.ref.WeakReference;
78import java.util.ArrayList;
79import java.util.Iterator;
80import java.util.List;
81
82/**
83 * State and management of a single stack of activities.
84 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070085final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070086 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070087 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070088 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
89 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
90 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
91 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
92 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
93 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
94 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
95 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
Dianne Hackborncc5a0552012-10-01 16:32:39 -070096 static final boolean DEBUG_CLEANUP = ActivityManagerService.DEBUG_CLEANUP;
Craig Mautner9658b312013-02-28 10:55:59 -080097
Dianne Hackbornce86ba82011-07-13 19:33:41 -070098 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070099 static final boolean DEBUG_ADD_REMOVE = false;
100 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackborn07981492013-01-28 11:36:23 -0800101 static final boolean DEBUG_APP = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700102
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700103 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800104 static final boolean VALIDATE_TASK_REPLACE = true;
105
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700106 // How long we wait until giving up on the last activity telling us it
107 // is idle.
108 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700109
110 // Ticks during which we check progress while waiting for an app to launch.
111 static final int LAUNCH_TICK = 500;
112
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700113 // How long we wait until giving up on the last activity to pause. This
114 // is short because it directly impacts the responsiveness of starting the
115 // next activity.
116 static final int PAUSE_TIMEOUT = 500;
117
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700118 // How long we wait for the activity to tell us it has stopped before
119 // giving up. This is a good amount of time because we really need this
120 // from the application in order to get its saved state.
121 static final int STOP_TIMEOUT = 10*1000;
122
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800123 // How long we can hold the sleep wake lock before giving up.
124 static final int SLEEP_TIMEOUT = 5*1000;
125
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700126 // How long we can hold the launch wake lock before giving up.
127 static final int LAUNCH_TIMEOUT = 10*1000;
128
129 // How long we wait until giving up on an activity telling us it has
130 // finished destroying itself.
131 static final int DESTROY_TIMEOUT = 10*1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800132
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700133 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800134 // disabled.
135 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800136
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700137 // How long between activity launches that we consider safe to not warn
138 // the user about an unexpected activity being launched on top.
139 static final long START_WARN_TIME = 5*1000;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800140
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700141 // Set to false to disable the preview that is shown while a new activity
142 // is being started.
143 static final boolean SHOW_APP_STARTING_PREVIEW = true;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800144
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700145 enum ActivityState {
146 INITIALIZING,
147 RESUMED,
148 PAUSING,
149 PAUSED,
150 STOPPING,
151 STOPPED,
152 FINISHING,
153 DESTROYING,
154 DESTROYED
155 }
156
157 final ActivityManagerService mService;
158 final boolean mMainStack;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800159
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700160 final Context mContext;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800161
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700162 /**
163 * The back history of all previous (and possibly still
Craig Mautnercae015f2013-02-08 14:31:27 -0800164 * running) activities. It contains #ActivityRecord objects.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700165 */
Craig Mautnercae015f2013-02-08 14:31:27 -0800166 private final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800167
168 /**
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800169 * The back history of all previous (and possibly still
170 * running) activities. It contains #TaskRecord objects.
171 */
172 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();
173
174 /**
175 * Mapping from taskId to TaskRecord
176 */
177 private SparseArray<TaskRecord> mTaskIdToTaskRecord = new SparseArray<TaskRecord>();
178
179 /**
Dianne Hackbornbe707852011-11-11 14:32:10 -0800180 * Used for validating app tokens with window manager.
181 */
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800182 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800183
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700184 /**
185 * List of running activities, sorted by recent usage.
186 * The first entry in the list is the least recently used.
187 * It contains HistoryRecord objects.
188 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700189 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700190
191 /**
192 * List of activities that are waiting for a new activity
193 * to become visible before completing whatever operation they are
194 * supposed to do.
195 */
196 final ArrayList<ActivityRecord> mWaitingVisibleActivities
197 = new ArrayList<ActivityRecord>();
198
199 /**
200 * List of activities that are ready to be stopped, but waiting
201 * for the next activity to settle down before doing so. It contains
202 * HistoryRecord objects.
203 */
204 final ArrayList<ActivityRecord> mStoppingActivities
205 = new ArrayList<ActivityRecord>();
206
207 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800208 * List of activities that are in the process of going to sleep.
209 */
210 final ArrayList<ActivityRecord> mGoingToSleepActivities
211 = new ArrayList<ActivityRecord>();
212
213 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700214 * Animations that for the current transition have requested not to
215 * be considered for the transition animation.
216 */
217 final ArrayList<ActivityRecord> mNoAnimActivities
218 = new ArrayList<ActivityRecord>();
219
220 /**
221 * List of activities that are ready to be finished, but waiting
222 * for the previous activity to settle down before doing so. It contains
223 * HistoryRecord objects.
224 */
225 final ArrayList<ActivityRecord> mFinishingActivities
226 = new ArrayList<ActivityRecord>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800227
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700228 /**
229 * List of people waiting to find out about the next launched activity.
230 */
231 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
232 = new ArrayList<IActivityManager.WaitResult>();
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800233
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700234 /**
235 * List of people waiting to find out about the next visible activity.
236 */
237 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
238 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700239
240 final ArrayList<UserStartedState> mStartingUsers
241 = new ArrayList<UserStartedState>();
242
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700243 /**
244 * Set when the system is going to sleep, until we have
245 * successfully paused the current activity and released our wake lock.
246 * At that point the system is allowed to actually sleep.
247 */
248 final PowerManager.WakeLock mGoingToSleep;
249
250 /**
251 * We don't want to allow the device to go to sleep while in the process
252 * of launching an activity. This is primarily to allow alarm intent
253 * receivers to launch an activity and get that to run before the device
254 * goes back to sleep.
255 */
256 final PowerManager.WakeLock mLaunchingActivity;
257
258 /**
259 * When we are in the process of pausing an activity, before starting the
260 * next one, this variable holds the activity that is currently being paused.
261 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800262 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700263
264 /**
265 * This is the last activity that we put into the paused state. This is
266 * used to determine if we need to do an activity transition while sleeping,
267 * when we normally hold the top activity paused.
268 */
269 ActivityRecord mLastPausedActivity = null;
270
271 /**
272 * Current activity that is resumed, or null if there is none.
273 */
274 ActivityRecord mResumedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800275
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700276 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700277 * This is the last activity that has been started. It is only used to
278 * identify when multiple activities are started at once so that the user
279 * can be warned they may not be in the activity they think they are.
280 */
281 ActivityRecord mLastStartedActivity = null;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800282
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700283 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700284 * Set when we know we are going to be calling updateConfiguration()
285 * soon, so want to skip intermediate config checks.
286 */
287 boolean mConfigWillChange;
288
289 /**
290 * Set to indicate whether to issue an onUserLeaving callback when a
291 * newly launched activity is being brought in front of us.
292 */
293 boolean mUserLeaving = false;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800294
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700295 long mInitialStartTime = 0;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800296
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800297 /**
298 * Set when we have taken too long waiting to go to sleep.
299 */
300 boolean mSleepTimeout = false;
301
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700302 /**
303 * Dismiss the keyguard after the next activity is displayed?
304 */
305 boolean mDismissKeyguardOnNextActivity = false;
306
Craig Mautnerb12428a2012-12-20 16:07:06 -0800307 /**
308 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
309 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
310 */
311 private ActivityRecord mLastScreenshotActivity = null;
312 private Bitmap mLastScreenshotBitmap = null;
313
Craig Mautnercae015f2013-02-08 14:31:27 -0800314 /**
315 * List of ActivityRecord objects that have been finished and must
316 * still report back to a pending thumbnail receiver.
317 */
318 private final ArrayList<ActivityRecord> mCancelledThumbnails = new ArrayList<ActivityRecord>();
319
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800320 int mThumbnailWidth = -1;
321 int mThumbnailHeight = -1;
322
Amith Yamasani742a6712011-05-04 14:49:28 -0700323 private int mCurrentUser;
324
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800325 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
326 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
327 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
328 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
329 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
330 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
331 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700332 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700333 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700334 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
335
336 static class ScheduleDestroyArgs {
337 final ProcessRecord mOwner;
338 final boolean mOomAdj;
339 final String mReason;
340 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
341 mOwner = owner;
342 mOomAdj = oomAdj;
343 mReason = reason;
344 }
345 }
346
Zoran Marcetaf958b322012-08-09 20:27:12 +0900347 final Handler mHandler;
348
Craig Mautner11bf9a52013-02-19 14:08:51 -0800349 String mLastHistoryModifier;
350
Zoran Marcetaf958b322012-08-09 20:27:12 +0900351 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700352 //public Handler() {
353 // if (localLOGV) Slog.v(TAG, "Handler started!");
354 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900355 public ActivityStackHandler(Looper looper) {
356 super(looper);
357 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700358
Zoran Marcetaf958b322012-08-09 20:27:12 +0900359 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700360 public void handleMessage(Message msg) {
361 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800362 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700363 synchronized (mService) {
364 if (mService.isSleeping()) {
365 Slog.w(TAG, "Sleep timeout! Sleeping now.");
366 mSleepTimeout = true;
367 checkReadyForSleepLocked();
368 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800369 }
370 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700371 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800372 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700373 // We don't at this point know if the activity is fullscreen,
374 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800375 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700376 synchronized (mService) {
377 if (r.app != null) {
378 mService.logAppTooSlow(r.app, r.pauseTime,
379 "pausing " + r);
380 }
381 }
382
Dianne Hackbornbe707852011-11-11 14:32:10 -0800383 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700384 } break;
385 case IDLE_TIMEOUT_MSG: {
386 if (mService.mDidDexOpt) {
387 mService.mDidDexOpt = false;
388 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
389 nmsg.obj = msg.obj;
390 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
391 return;
392 }
393 // We don't at this point know if the activity is fullscreen,
394 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800395 ActivityRecord r = (ActivityRecord)msg.obj;
396 Slog.w(TAG, "Activity idle timeout for " + r);
397 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700398 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700399 case LAUNCH_TICK_MSG: {
400 ActivityRecord r = (ActivityRecord)msg.obj;
401 synchronized (mService) {
402 if (r.continueLaunchTickingLocked()) {
403 mService.logAppTooSlow(r.app, r.launchTickTime,
404 "launching " + r);
405 }
406 }
407 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700408 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800409 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700410 // We don't at this point know if the activity is fullscreen,
411 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800412 Slog.w(TAG, "Activity destroy timeout for " + r);
413 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700414 } break;
415 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800416 ActivityRecord r = (ActivityRecord)msg.obj;
417 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700418 } break;
419 case LAUNCH_TIMEOUT_MSG: {
420 if (mService.mDidDexOpt) {
421 mService.mDidDexOpt = false;
422 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
423 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
424 return;
425 }
426 synchronized (mService) {
427 if (mLaunchingActivity.isHeld()) {
428 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
429 mLaunchingActivity.release();
430 }
431 }
432 } break;
433 case RESUME_TOP_ACTIVITY_MSG: {
434 synchronized (mService) {
435 resumeTopActivityLocked(null);
436 }
437 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700438 case STOP_TIMEOUT_MSG: {
439 ActivityRecord r = (ActivityRecord)msg.obj;
440 // We don't at this point know if the activity is fullscreen,
441 // so we need to be conservative and assume it isn't.
442 Slog.w(TAG, "Activity stop timeout for " + r);
443 synchronized (mService) {
444 if (r.isInHistory()) {
445 activityStoppedLocked(r, null, null, null);
446 }
447 }
448 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700449 case DESTROY_ACTIVITIES_MSG: {
450 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
451 synchronized (mService) {
452 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
453 }
454 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700455 }
456 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800457 }
458
Craig Mautner000f0022013-02-26 15:04:29 -0800459 private int numActivities() {
460 int count = 0;
461 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
462 count += mTaskHistory.get(taskNdx).mActivities.size();
463 }
464 return count;
465 }
466
Zoran Marcetaf958b322012-08-09 20:27:12 +0900467 ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper) {
468 mHandler = new ActivityStackHandler(looper);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700469 mService = service;
470 mContext = context;
471 mMainStack = mainStack;
472 PowerManager pm =
473 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
474 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
475 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
476 mLaunchingActivity.setReferenceCounted(false);
477 }
Craig Mautner5962b122012-10-05 14:45:52 -0700478
479 private boolean okToShow(ActivityRecord r) {
480 return r.userId == mCurrentUser
481 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
482 }
483
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700484 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800485 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
486 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800487 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800488 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
489 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800490 if (!r.finishing && r != notTop && okToShow(r)) {
491 return r;
492 }
493 }
494 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700495 return null;
496 }
497
498 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800499 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
500 final TaskRecord task = mTaskHistory.get(taskNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800501 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautnerd74f7d72013-02-26 13:41:02 -0800502 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
503 ActivityRecord r = activities.get(activityNdx);
Craig Mautner11bf9a52013-02-19 14:08:51 -0800504 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
505 return r;
506 }
507 }
508 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700509 return null;
510 }
511
512 /**
513 * This is a simplified version of topRunningActivityLocked that provides a number of
514 * optional skip-over modes. It is intended for use with the ActivityController hook only.
Craig Mautner9658b312013-02-28 10:55:59 -0800515 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700516 * @param token If non-null, any history records matching this token will be skipped.
517 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
Craig Mautner9658b312013-02-28 10:55:59 -0800518 *
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700519 * @return Returns the HistoryRecord of the next activity on the stack.
520 */
521 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
Craig Mautner11bf9a52013-02-19 14:08:51 -0800522 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
523 TaskRecord task = mTaskHistory.get(taskNdx);
524 if (task.taskId == taskId) {
525 continue;
526 }
527 ArrayList<ActivityRecord> activities = task.mActivities;
528 for (int i = activities.size() - 1; i >= 0; --i) {
529 final ActivityRecord r = activities.get(i);
530 // Note: the taskId check depends on real taskId fields being non-zero
531 if (!r.finishing && (token != r.appToken) && okToShow(r)) {
532 return r;
533 }
534 }
535 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700536 return null;
537 }
538
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700539 final ActivityRecord isInStackLocked(IBinder token) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800540 final ActivityRecord r = ActivityRecord.forToken(token);
541 if (r != null) {
542 final TaskRecord task = r.task;
543 if (mTaskHistory.contains(task) && task.mActivities.contains(r)) {
544 return r;
545 }
546 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700547 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700548 }
549
Craig Mautnercae015f2013-02-08 14:31:27 -0800550 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800551 final ActivityRecord r = ActivityRecord.forToken(token);
552 if (r == null) {
553 return -1;
554 }
555 final TaskRecord task = r.task;
556 switch (task.mActivities.indexOf(r)) {
557 case -1: return -1;
558 case 0: return task.taskId;
559 default: return onlyRoot ? -1 : task.taskId;
560 }
561 }
562
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700563 private final boolean updateLRUListLocked(ActivityRecord r) {
564 final boolean hadit = mLRUActivities.remove(r);
565 mLRUActivities.add(r);
566 return hadit;
567 }
568
569 /**
570 * Returns the top activity in any existing task matching the given
571 * Intent. Returns null if no such task is found.
572 */
573 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
574 ComponentName cls = intent.getComponent();
575 if (info.targetActivity != null) {
576 cls = new ComponentName(info.packageName, info.targetActivity);
577 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700578 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Craig Mautner000f0022013-02-26 15:04:29 -0800579
580 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
581 final TaskRecord task = mTaskHistory.get(taskNdx);
582 final ActivityRecord r = task.getTopActivity();
583 if (r == null || r.finishing || r.userId != userId ||
584 r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
585 continue;
586 }
587
588 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
589 // + "/aff=" + r.task.affinity + " to new cls="
590 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
591 if (task.affinity != null) {
592 if (task.affinity.equals(info.taskAffinity)) {
593 //Slog.i(TAG, "Found matching affinity!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700594 return r;
595 }
Craig Mautner000f0022013-02-26 15:04:29 -0800596 } else if (task.intent != null && task.intent.getComponent().equals(cls)) {
597 //Slog.i(TAG, "Found matching class!");
598 //dump();
599 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
600 return r;
601 } else if (task.affinityIntent != null
602 && task.affinityIntent.getComponent().equals(cls)) {
603 //Slog.i(TAG, "Found matching class!");
604 //dump();
605 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
606 return r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700607 }
608 }
609
610 return null;
611 }
612
613 /**
614 * Returns the first activity (starting from the top of the stack) that
615 * is the same as the given activity. Returns null if no such activity
616 * is found.
617 */
618 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
619 ComponentName cls = intent.getComponent();
620 if (info.targetActivity != null) {
621 cls = new ComponentName(info.packageName, info.targetActivity);
622 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700623 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700624
Craig Mautner000f0022013-02-26 15:04:29 -0800625 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
626 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
627 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
628 ActivityRecord r = activities.get(activityNdx);
629 if (!r.finishing && r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700630 //Slog.i(TAG, "Found matching class!");
631 //dump();
632 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
633 return r;
634 }
635 }
636 }
637
638 return null;
639 }
640
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700641 final void showAskCompatModeDialogLocked(ActivityRecord r) {
642 Message msg = Message.obtain();
643 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
644 msg.obj = r.task.askedCompatMode ? null : r;
645 mService.mHandler.sendMessage(msg);
646 }
647
Amith Yamasani742a6712011-05-04 14:49:28 -0700648 /*
649 * Move the activities around in the stack to bring a user to the foreground.
650 * @return whether there are any activities for the specified user.
651 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700652 final boolean switchUserLocked(int userId, UserStartedState uss) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800653 if (VALIDATE_TOKENS) {
654 validateAppTokensLocked();
655 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700656 mStartingUsers.add(uss);
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800657 if (mCurrentUser == userId) {
658 return true;
659 }
660 mCurrentUser = userId;
661
662 // Move userId's tasks to the top.
663 boolean haveActivities = false;
664 TaskRecord task = null;
665 int index = mTaskHistory.size();
666 for (int i = 0; i < index; ++i) {
667 task = mTaskHistory.get(i);
668 if (task.userId == userId) {
669 haveActivities = true;
670 mTaskHistory.remove(i);
671 mTaskHistory.add(task);
672 --index;
673 }
674 }
675
Craig Mautner000f0022013-02-26 15:04:29 -0800676 { // TODO: Remove when mHistory order no longer matters.
677 // Otherwise, move the user's activities to the top.
678 int N = mHistory.size();
679 int i = 0;
680 while (i < N) {
681 ActivityRecord r = mHistory.get(i);
682 if (r.userId == userId) {
683 ActivityRecord moveToTop = mHistory.remove(i);
684 mHistory.add(moveToTop);
685 // No need to check the top one now
686 N--;
687 haveActivities = true;
688 } else {
689 i++;
690 }
691 }
692 if (VALIDATE_TASK_REPLACE) {
693 verifyActivityRecords(true);
694 }
695 }
696
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800697 // task is now the original topmost TaskRecord. Transition from the old top to the new top.
698 ActivityRecord top = task != null ? task.getTopActivity() : null;
699 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
700 "newSwitchUserLocked: would call resumeTopActivity " + top);
Craig Mautner000f0022013-02-26 15:04:29 -0800701 resumeTopActivityLocked(top);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700702 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700703 }
704
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700705 final boolean realStartActivityLocked(ActivityRecord r,
706 ProcessRecord app, boolean andResume, boolean checkConfig)
707 throws RemoteException {
708
709 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800710 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700711
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700712 // schedule launch ticks to collect information about slow apps.
713 r.startLaunchTickingLocked();
714
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700715 // Have the window manager re-evaluate the orientation of
716 // the screen based on the new activity order. Note that
717 // as a result of this, it can call back into the activity
718 // manager with a new orientation. We don't care about that,
719 // because the activity is not currently running so we are
720 // just restarting it anyway.
721 if (checkConfig) {
722 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
723 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800724 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800725 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700726 }
727
728 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700729 app.waitingToKill = null;
Dianne Hackborn07981492013-01-28 11:36:23 -0800730 r.launchCount++;
731 r.lastLaunchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700732
733 if (localLOGV) Slog.v(TAG, "Launching: " + r);
734
735 int idx = app.activities.indexOf(r);
736 if (idx < 0) {
737 app.activities.add(r);
738 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700739 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700740
741 try {
742 if (app.thread == null) {
743 throw new RemoteException();
744 }
745 List<ResultInfo> results = null;
746 List<Intent> newIntents = null;
747 if (andResume) {
748 results = r.results;
749 newIntents = r.newIntents;
750 }
751 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
752 + " icicle=" + r.icicle
753 + " with results=" + results + " newIntents=" + newIntents
754 + " andResume=" + andResume);
755 if (andResume) {
756 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700757 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700758 r.task.taskId, r.shortComponentName);
759 }
760 if (r.isHomeActivity) {
761 mService.mHomeProcess = app;
762 }
763 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800764 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400765 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700766 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700767 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700768 String profileFile = null;
769 ParcelFileDescriptor profileFd = null;
770 boolean profileAutoStop = false;
771 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
772 if (mService.mProfileProc == null || mService.mProfileProc == app) {
773 mService.mProfileProc = app;
774 profileFile = mService.mProfileFile;
775 profileFd = mService.mProfileFd;
776 profileAutoStop = mService.mAutoStopProfiler;
777 }
778 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700779 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700780 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700781 if (profileFd != null) {
782 try {
783 profileFd = profileFd.dup();
784 } catch (IOException e) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800785 if (profileFd != null) {
786 try {
787 profileFd.close();
788 } catch (IOException o) {
789 }
790 profileFd = null;
791 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700792 }
793 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800794 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800795 System.identityHashCode(r), r.info,
796 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700797 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700798 mService.isNextTransitionForward(), profileFile, profileFd,
799 profileAutoStop);
Craig Mautner9658b312013-02-28 10:55:59 -0800800
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700801 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700802 // This may be a heavy-weight process! Note that the package
803 // manager will ensure that only activity can run in the main
804 // process of the .apk, which is the only thing that will be
805 // considered heavy-weight.
806 if (app.processName.equals(app.info.packageName)) {
807 if (mService.mHeavyWeightProcess != null
808 && mService.mHeavyWeightProcess != app) {
809 Log.w(TAG, "Starting new heavy weight process " + app
810 + " when already running "
811 + mService.mHeavyWeightProcess);
812 }
813 mService.mHeavyWeightProcess = app;
814 Message msg = mService.mHandler.obtainMessage(
815 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
816 msg.obj = r;
817 mService.mHandler.sendMessage(msg);
818 }
819 }
Craig Mautner9658b312013-02-28 10:55:59 -0800820
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700821 } catch (RemoteException e) {
822 if (r.launchFailed) {
823 // This is the second time we failed -- finish activity
824 // and give up.
825 Slog.e(TAG, "Second failure launching "
826 + r.intent.getComponent().flattenToShortString()
827 + ", giving up", e);
828 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800829 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700830 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700831 return false;
832 }
833
834 // This is the first time we failed -- restart process and
835 // retry.
836 app.activities.remove(r);
837 throw e;
838 }
839
840 r.launchFailed = false;
841 if (updateLRUListLocked(r)) {
842 Slog.w(TAG, "Activity " + r
843 + " being launched, but already in LRU list");
844 }
845
846 if (andResume) {
847 // As part of the process of launching, ActivityThread also performs
848 // a resume.
849 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700850 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
851 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700852 r.stopped = false;
853 mResumedActivity = r;
854 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800855 if (mMainStack) {
856 mService.addRecentTaskLocked(r.task);
857 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700858 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800859 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700860 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700861 } else {
862 // This activity is not starting in the resumed state... which
863 // should look like we asked it to pause+stop (but remain visible),
864 // and it has done so and reported back the current icicle and
865 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700866 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
867 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700868 r.state = ActivityState.STOPPED;
869 r.stopped = true;
870 }
871
872 // Launch the new version setup screen if needed. We do this -after-
873 // launching the initial activity (that is, home), so that it can have
874 // a chance to initialize itself while in the background, making the
875 // switch back to it faster and look better.
876 if (mMainStack) {
877 mService.startSetupActivityLocked();
878 }
Craig Mautner9658b312013-02-28 10:55:59 -0800879
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700880 return true;
881 }
882
883 private final void startSpecificActivityLocked(ActivityRecord r,
884 boolean andResume, boolean checkConfig) {
885 // Is this activity's application already running?
886 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
887 r.info.applicationInfo.uid);
Dianne Hackborn07981492013-01-28 11:36:23 -0800888
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700889 if (r.launchTime == 0) {
890 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700891 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700892 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700893 }
894 } else if (mInitialStartTime == 0) {
895 mInitialStartTime = SystemClock.uptimeMillis();
896 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800897
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700898 if (app != null && app.thread != null) {
899 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700900 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700901 realStartActivityLocked(r, app, andResume, checkConfig);
902 return;
903 } catch (RemoteException e) {
904 Slog.w(TAG, "Exception when starting activity "
905 + r.intent.getComponent().flattenToShortString(), e);
906 }
907
908 // If a dead object exception was thrown -- fall through to
909 // restart the application.
910 }
911
912 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800913 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700914 }
Craig Mautneraab647e2013-02-28 16:31:36 -0800915
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800916 void stopIfSleepingLocked() {
917 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700918 if (!mGoingToSleep.isHeld()) {
919 mGoingToSleep.acquire();
920 if (mLaunchingActivity.isHeld()) {
921 mLaunchingActivity.release();
922 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
923 }
924 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800925 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
926 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
927 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
928 checkReadyForSleepLocked();
929 }
930 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700931
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800932 void awakeFromSleepingLocked() {
933 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
934 mSleepTimeout = false;
935 if (mGoingToSleep.isHeld()) {
936 mGoingToSleep.release();
937 }
938 // Ensure activities are no longer sleeping.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800939 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
940 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
941 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
942 activities.get(activityNdx).setSleeping(false);
943 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800944 }
945 mGoingToSleepActivities.clear();
946 }
947
948 void activitySleptLocked(ActivityRecord r) {
949 mGoingToSleepActivities.remove(r);
950 checkReadyForSleepLocked();
951 }
952
953 void checkReadyForSleepLocked() {
954 if (!mService.isSleeping()) {
955 // Do not care.
956 return;
957 }
958
959 if (!mSleepTimeout) {
960 if (mResumedActivity != null) {
961 // Still have something resumed; can't sleep until it is paused.
962 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700963 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
964 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800965 return;
966 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800967 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800968 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800969 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800970 return;
971 }
972
973 if (mStoppingActivities.size() > 0) {
974 // Still need to tell some activities to stop; can't sleep yet.
975 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
976 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700977 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800978 return;
979 }
980
981 ensureActivitiesVisibleLocked(null, 0);
982
983 // Make sure any stopped but visible activities are now sleeping.
984 // This ensures that the activity's onStop() is called.
Craig Mautnerd44711d2013-02-23 11:24:36 -0800985 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
986 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
987 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
988 final ActivityRecord r = activities.get(activityNdx);
989 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
990 r.setSleeping(true);
991 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800992 }
993 }
994
995 if (mGoingToSleepActivities.size() > 0) {
996 // Still need to tell some activities to sleep; can't sleep yet.
997 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
998 + mGoingToSleepActivities.size() + " activities");
999 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001000 }
1001 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001002
1003 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
1004
1005 if (mGoingToSleep.isHeld()) {
1006 mGoingToSleep.release();
1007 }
1008 if (mService.mShuttingDown) {
1009 mService.notifyAll();
1010 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001011 }
Craig Mautner59c00972012-07-30 12:10:24 -07001012
Dianne Hackbornd2835932010-12-13 16:28:46 -08001013 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001014 if (who.noDisplay) {
1015 return null;
1016 }
Craig Mautneraab647e2013-02-28 16:31:36 -08001017
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001018 Resources res = mService.mContext.getResources();
1019 int w = mThumbnailWidth;
1020 int h = mThumbnailHeight;
1021 if (w < 0) {
1022 mThumbnailWidth = w =
1023 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
1024 mThumbnailHeight = h =
1025 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
1026 }
1027
1028 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -08001029 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
1030 || mLastScreenshotBitmap.getWidth() != w
1031 || mLastScreenshotBitmap.getHeight() != h) {
1032 mLastScreenshotActivity = who;
1033 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
1034 who.appToken, Display.DEFAULT_DISPLAY, w, h);
1035 }
1036 if (mLastScreenshotBitmap != null) {
1037 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
1038 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001039 }
1040 return null;
1041 }
1042
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001043 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001044 if (mPausingActivity != null) {
1045 RuntimeException e = new RuntimeException();
1046 Slog.e(TAG, "Trying to pause when pause is already pending for "
1047 + mPausingActivity, e);
1048 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001049 ActivityRecord prev = mResumedActivity;
1050 if (prev == null) {
1051 RuntimeException e = new RuntimeException();
1052 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
1053 resumeTopActivityLocked(null);
1054 return;
1055 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001056 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
1057 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001058 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001059 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001060 mLastPausedActivity = prev;
1061 prev.state = ActivityState.PAUSING;
1062 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001063 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001064
1065 mService.updateCpuStats();
Craig Mautneraab647e2013-02-28 16:31:36 -08001066
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001067 if (prev.app != null && prev.app.thread != null) {
1068 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
1069 try {
1070 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001071 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001072 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001073 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1074 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001075 if (mMainStack) {
1076 mService.updateUsageStats(prev, false);
1077 }
1078 } catch (Exception e) {
1079 // Ignore exception, if process died other code will cleanup.
1080 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001081 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001082 mLastPausedActivity = null;
1083 }
1084 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001085 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001086 mLastPausedActivity = null;
1087 }
1088
1089 // If we are not going to sleep, we want to ensure the device is
1090 // awake until the next activity is started.
1091 if (!mService.mSleeping && !mService.mShuttingDown) {
1092 mLaunchingActivity.acquire();
1093 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1094 // To be safe, don't allow the wake lock to be held for too long.
1095 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1096 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1097 }
1098 }
1099
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001100
1101 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001102 // Have the window manager pause its key dispatching until the new
1103 // activity has started. If we're pausing the activity just because
1104 // the screen is being turned off and the UI is sleeping, don't interrupt
1105 // key dispatch; the same activity will pick it up again on wakeup.
1106 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001107 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001108 } else {
1109 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1110 }
1111
1112 // Schedule a pause timeout in case the app doesn't respond.
1113 // We don't give it much time because this directly impacts the
1114 // responsiveness seen by the user.
1115 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1116 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001117 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001118 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1119 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1120 } else {
1121 // This activity failed to schedule the
1122 // pause, so just treat it as being paused now.
1123 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001124 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001125 }
1126 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001127
1128 final void activityResumed(IBinder token) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001129 synchronized (mService) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08001130 final ActivityRecord r = isInStackLocked(token);
1131 if (r != null) {
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001132 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1133 r.icicle = null;
1134 r.haveState = false;
1135 }
1136 }
1137 }
1138
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001139 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001140 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001141 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001142
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001143 synchronized (mService) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08001144 final ActivityRecord r = isInStackLocked(token);
1145 if (r != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001146 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001147 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001148 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1149 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001150 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001151 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001152 } else {
1153 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Craig Mautneraab647e2013-02-28 16:31:36 -08001154 r.userId, System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001155 mPausingActivity != null
1156 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001157 }
1158 }
1159 }
1160 }
1161
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001162 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1163 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001164 if (r.state != ActivityState.STOPPING) {
1165 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1166 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1167 return;
1168 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001169 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001170 if (icicle != null) {
1171 // If icicle is null, this is happening due to a timeout, so we
1172 // haven't really saved the state.
1173 r.icicle = icicle;
1174 r.haveState = true;
Dianne Hackborn07981492013-01-28 11:36:23 -08001175 r.launchCount = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001176 r.updateThumbnail(thumbnail, description);
1177 }
1178 if (!r.stopped) {
1179 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1180 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1181 r.stopped = true;
1182 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001183 if (r.finishing) {
1184 r.clearOptionsLocked();
1185 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001186 if (r.configDestroy) {
1187 destroyActivityLocked(r, true, false, "stop-config");
1188 resumeTopActivityLocked(null);
1189 } else {
1190 // Now that this process has stopped, we may want to consider
1191 // it to be the previous app to try to keep around in case
1192 // the user wants to return to it.
1193 ProcessRecord fgApp = null;
1194 if (mResumedActivity != null) {
1195 fgApp = mResumedActivity.app;
1196 } else if (mPausingActivity != null) {
1197 fgApp = mPausingActivity.app;
1198 }
1199 if (r.app != null && fgApp != null && r.app != fgApp
1200 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1201 && r.app != mService.mHomeProcess) {
1202 mService.mPreviousProcess = r.app;
1203 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1204 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001205 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001206 }
1207 }
1208 }
1209
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001210 private final void completePauseLocked() {
1211 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001212 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
Craig Mautneraab647e2013-02-28 16:31:36 -08001213
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001214 if (prev != null) {
1215 if (prev.finishing) {
1216 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001217 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001218 } else if (prev.app != null) {
1219 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1220 if (prev.waitingVisible) {
1221 prev.waitingVisible = false;
1222 mWaitingVisibleActivities.remove(prev);
1223 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1224 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001225 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001226 if (prev.configDestroy) {
1227 // The previous is being paused because the configuration
1228 // is changing, which means it is actually stopping...
1229 // To juggle the fact that we are also starting a new
1230 // instance right now, we need to first completely stop
1231 // the current instance before starting the new one.
1232 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1233 destroyActivityLocked(prev, true, false, "pause-config");
1234 } else {
1235 mStoppingActivities.add(prev);
1236 if (mStoppingActivities.size() > 3) {
1237 // If we already have a few activities waiting to stop,
1238 // then give up on things going idle and start clearing
1239 // them out.
1240 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1241 scheduleIdleLocked();
1242 } else {
1243 checkReadyForSleepLocked();
1244 }
1245 }
1246 } else {
1247 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1248 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001249 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001250 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001251 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001252
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001253 if (!mService.isSleeping()) {
1254 resumeTopActivityLocked(prev);
1255 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001256 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001257 ActivityRecord top = topRunningActivityLocked(null);
1258 if (top == null || (prev != null && top != prev)) {
1259 // If there are no more activities available to run,
1260 // do resume anyway to start something. Also if the top
1261 // activity on the stack is not the just paused activity,
1262 // we need to go ahead and resume it to ensure we complete
1263 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001264 resumeTopActivityLocked(null);
1265 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001266 }
Craig Mautneraab647e2013-02-28 16:31:36 -08001267
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001268 if (prev != null) {
1269 prev.resumeKeyDispatchingLocked();
1270 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001271
1272 if (prev.app != null && prev.cpuTimeAtResume > 0
1273 && mService.mBatteryStatsService.isOnBattery()) {
1274 long diff = 0;
1275 synchronized (mService.mProcessStatsThread) {
1276 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1277 - prev.cpuTimeAtResume;
1278 }
1279 if (diff > 0) {
1280 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1281 synchronized (bsi) {
1282 BatteryStatsImpl.Uid.Proc ps =
1283 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1284 prev.info.packageName);
1285 if (ps != null) {
1286 ps.addForegroundTimeLocked(diff);
1287 }
1288 }
1289 }
1290 }
1291 prev.cpuTimeAtResume = 0; // reset it
1292 }
1293
1294 /**
1295 * Once we know that we have asked an application to put an activity in
1296 * the resumed state (either by launching it or explicitly telling it),
1297 * this function updates the rest of our state to match that fact.
1298 */
1299 private final void completeResumeLocked(ActivityRecord next) {
1300 next.idle = false;
1301 next.results = null;
1302 next.newIntents = null;
1303
1304 // schedule an idle timeout in case the app doesn't do it for us.
1305 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1306 msg.obj = next;
1307 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1308
1309 if (false) {
1310 // The activity was never told to pause, so just keep
1311 // things going as-is. To maintain our own state,
1312 // we need to emulate it coming back and saying it is
1313 // idle.
1314 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1315 msg.obj = next;
1316 mHandler.sendMessage(msg);
1317 }
1318
1319 if (mMainStack) {
1320 mService.reportResumedActivityLocked(next);
1321 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001322
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001323 if (mMainStack) {
1324 mService.setFocusedActivityLocked(next);
1325 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001326 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001327 ensureActivitiesVisibleLocked(null, 0);
1328 mService.mWindowManager.executeAppTransition();
1329 mNoAnimActivities.clear();
1330
1331 // Mark the point when the activity is resuming
1332 // TODO: To be more accurate, the mark should be before the onCreate,
1333 // not after the onResume. But for subsequent starts, onResume is fine.
1334 if (next.app != null) {
1335 synchronized (mService.mProcessStatsThread) {
1336 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1337 }
1338 } else {
1339 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1340 }
1341 }
1342
1343 /**
1344 * Make sure that all activities that need to be visible (that is, they
1345 * currently can be seen by the user) actually are.
1346 */
1347 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1348 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1349 if (DEBUG_VISBILITY) Slog.v(
1350 TAG, "ensureActivitiesVisible behind " + top
1351 + " configChanges=0x" + Integer.toHexString(configChanges));
1352
1353 // If the top activity is not fullscreen, then we need to
1354 // make sure any activities under it are now visible.
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001355 if (VALIDATE_TASK_REPLACE) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08001356 verifyActivityRecords(true);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001357 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08001358 boolean aboveTop = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001359 boolean behindFullscreen = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08001360 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
1361 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
1362 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
1363 final ActivityRecord r = activities.get(activityNdx);
1364 if (r.finishing) {
1365 continue;
1366 }
1367 if (aboveTop && r != top) {
1368 continue;
1369 }
1370 aboveTop = false;
1371 if (!behindFullscreen) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001372 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001373 TAG, "Make visible? " + r + " finishing=" + r.finishing
1374 + " state=" + r.state);
1375
1376 final boolean doThisProcess = onlyThisProcess == null
1377 || onlyThisProcess.equals(r.processName);
1378
1379 // First: if this is not the current activity being started, make
1380 // sure it matches the current configuration.
1381 if (r != starting && doThisProcess) {
1382 ensureActivityConfigurationLocked(r, 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001383 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08001384
1385 if (r.app == null || r.app.thread == null) {
1386 if (onlyThisProcess == null
1387 || onlyThisProcess.equals(r.processName)) {
1388 // This activity needs to be visible, but isn't even
1389 // running... get it started, but don't resume it
1390 // at this point.
1391 if (DEBUG_VISBILITY) Slog.v(
1392 TAG, "Start and freeze screen for " + r);
1393 if (r != starting) {
1394 r.startFreezingScreenLocked(r.app, configChanges);
1395 }
1396 if (!r.visible) {
1397 if (DEBUG_VISBILITY) Slog.v(
1398 TAG, "Starting and making visible: " + r);
1399 mService.mWindowManager.setAppVisibility(r.appToken, true);
1400 }
1401 if (r != starting) {
1402 startSpecificActivityLocked(r, false, false);
1403 }
1404 }
1405
1406 } else if (r.visible) {
1407 // If this activity is already visible, then there is nothing
1408 // else to do here.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001409 if (DEBUG_VISBILITY) Slog.v(
Craig Mautnerd44711d2013-02-23 11:24:36 -08001410 TAG, "Skipping: already visible at " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001411 r.stopFreezingScreenLocked(false);
Craig Mautnerd44711d2013-02-23 11:24:36 -08001412
1413 } else if (onlyThisProcess == null) {
1414 // This activity is not currently visible, but is running.
1415 // Tell it to become visible.
1416 r.visible = true;
1417 if (r.state != ActivityState.RESUMED && r != starting) {
1418 // If this activity is paused, tell it
1419 // to now show its window.
1420 if (DEBUG_VISBILITY) Slog.v(
1421 TAG, "Making visible and scheduling visibility: " + r);
1422 try {
1423 mService.mWindowManager.setAppVisibility(r.appToken, true);
1424 r.sleeping = false;
1425 r.app.pendingUiClean = true;
1426 r.app.thread.scheduleWindowVisibility(r.appToken, true);
1427 r.stopFreezingScreenLocked(false);
1428 } catch (Exception e) {
1429 // Just skip on any failure; we'll make it
1430 // visible when it next restarts.
1431 Slog.w(TAG, "Exception thrown making visibile: "
1432 + r.intent.getComponent(), e);
1433 }
1434 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001435 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001436
Craig Mautnerd44711d2013-02-23 11:24:36 -08001437 // Aggregate current change flags.
1438 configChanges |= r.configChangeFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001439
Craig Mautnerd44711d2013-02-23 11:24:36 -08001440 if (r.fullscreen) {
1441 // At this point, nothing else needs to be shown
1442 if (DEBUG_VISBILITY) Slog.v(
1443 TAG, "Stopping: fullscreen at " + r);
1444 behindFullscreen = true;
1445 }
1446 } else {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001447 if (r.visible) {
1448 if (DEBUG_VISBILITY) Slog.v(
1449 TAG, "Making invisible: " + r);
1450 r.visible = false;
1451 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001452 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001453 if ((r.state == ActivityState.STOPPING
1454 || r.state == ActivityState.STOPPED)
1455 && r.app != null && r.app.thread != null) {
1456 if (DEBUG_VISBILITY) Slog.v(
1457 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001458 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001459 }
1460 } catch (Exception e) {
1461 // Just skip on any failure; we'll make it
1462 // visible when it next restarts.
1463 Slog.w(TAG, "Exception thrown making hidden: "
1464 + r.intent.getComponent(), e);
1465 }
1466 } else {
1467 if (DEBUG_VISBILITY) Slog.v(
1468 TAG, "Already invisible: " + r);
1469 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001470 }
1471 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001472 }
1473 }
1474
1475 /**
1476 * Version of ensureActivitiesVisible that can easily be called anywhere.
1477 */
1478 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1479 int configChanges) {
1480 ActivityRecord r = topRunningActivityLocked(null);
1481 if (r != null) {
1482 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1483 }
1484 }
1485
1486 /**
1487 * Ensure that the top activity in the stack is resumed.
1488 *
1489 * @param prev The previously resumed activity, for when in the process
1490 * of pausing; can be null to call from elsewhere.
1491 *
1492 * @return Returns true if something is being resumed, or false if
1493 * nothing happened.
1494 */
1495 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001496 return resumeTopActivityLocked(prev, null);
1497 }
1498
1499 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001500 // Find the first activity that is not finishing.
1501 ActivityRecord next = topRunningActivityLocked(null);
1502
1503 // Remember how we'll process this pause/resume situation, and ensure
1504 // that the state is reset however we wind up proceeding.
1505 final boolean userLeaving = mUserLeaving;
1506 mUserLeaving = false;
1507
1508 if (next == null) {
1509 // There are no more activities! Let's just start up the
1510 // Launcher...
1511 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001512 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001513 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001514 }
1515 }
1516
1517 next.delayedResume = false;
1518
1519 // If the top activity is the resumed one, nothing to do.
1520 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1521 // Make sure we have executed any pending transitions, since there
1522 // should be nothing left to do at this point.
1523 mService.mWindowManager.executeAppTransition();
1524 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001525 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001526 return false;
1527 }
1528
1529 // If we are sleeping, and there is no resumed activity, and the top
1530 // activity is paused, well that is the state we want.
1531 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001532 && mLastPausedActivity == next
1533 && (next.state == ActivityState.PAUSED
1534 || next.state == ActivityState.STOPPED
1535 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001536 // Make sure we have executed any pending transitions, since there
1537 // should be nothing left to do at this point.
1538 mService.mWindowManager.executeAppTransition();
1539 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001540 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001541 return false;
1542 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001543
1544 // Make sure that the user who owns this activity is started. If not,
1545 // we will just leave it as is because someone should be bringing
1546 // another user's activities to the top of the stack.
1547 if (mService.mStartedUsers.get(next.userId) == null) {
1548 Slog.w(TAG, "Skipping resume of top activity " + next
1549 + ": user " + next.userId + " is stopped");
1550 return false;
1551 }
1552
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001553 // The activity may be waiting for stop, but that is no longer
1554 // appropriate for it.
1555 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001556 mGoingToSleepActivities.remove(next);
1557 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001558 mWaitingVisibleActivities.remove(next);
1559
Dianne Hackborn84375872012-06-01 19:03:50 -07001560 next.updateOptionsLocked(options);
1561
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001562 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1563
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001564 // If we are currently pausing an activity, then don't do anything
1565 // until that is done.
1566 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001567 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1568 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001569 return false;
1570 }
1571
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001572 // Okay we are now going to start a switch, to 'next'. We may first
1573 // have to pause the current activity, but this is an important point
1574 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001575 // XXX "App Redirected" dialog is getting too many false positives
1576 // at this point, so turn off for now.
1577 if (false) {
1578 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1579 long now = SystemClock.uptimeMillis();
1580 final boolean inTime = mLastStartedActivity.startTime != 0
1581 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1582 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1583 final int nextUid = next.info.applicationInfo.uid;
1584 if (inTime && lastUid != nextUid
1585 && lastUid != next.launchedFromUid
1586 && mService.checkPermission(
1587 android.Manifest.permission.STOP_APP_SWITCHES,
1588 -1, next.launchedFromUid)
1589 != PackageManager.PERMISSION_GRANTED) {
1590 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1591 } else {
1592 next.startTime = now;
1593 mLastStartedActivity = next;
1594 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001595 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001596 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001597 mLastStartedActivity = next;
1598 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001599 }
1600
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001601 // We need to start pausing the current activity so the top one
1602 // can be resumed...
1603 if (mResumedActivity != null) {
1604 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001605 // At this point we want to put the upcoming activity's process
1606 // at the top of the LRU list, since we know we will be needing it
1607 // very soon and it would be a waste to let it get killed if it
1608 // happens to be sitting towards the end.
1609 if (next.app != null && next.app.thread != null) {
1610 // No reason to do full oom adj update here; we'll let that
1611 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001612 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001613 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001614 startPausingLocked(userLeaving, false);
1615 return true;
1616 }
1617
Christopher Tated3f175c2012-06-14 14:16:54 -07001618 // If the most recent activity was noHistory but was only stopped rather
1619 // than stopped+finished because the device went to sleep, we need to make
1620 // sure to finish it as we're making a new activity topmost.
1621 final ActivityRecord last = mLastPausedActivity;
1622 if (mService.mSleeping && last != null && !last.finishing) {
1623 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1624 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1625 if (DEBUG_STATES) {
1626 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1627 }
1628 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001629 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001630 }
1631 }
1632
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001633 if (prev != null && prev != next) {
1634 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1635 prev.waitingVisible = true;
1636 mWaitingVisibleActivities.add(prev);
1637 if (DEBUG_SWITCH) Slog.v(
1638 TAG, "Resuming top, waiting visible to hide: " + prev);
1639 } else {
1640 // The next activity is already visible, so hide the previous
1641 // activity's windows right now so we can show the new one ASAP.
1642 // We only do this if the previous is finishing, which should mean
1643 // it is on top of the one being resumed so hiding it quickly
1644 // is good. Otherwise, we want to do the normal route of allowing
1645 // the resumed activity to be shown so we can decide if the
1646 // previous should actually be hidden depending on whether the
1647 // new one is found to be full-screen or not.
1648 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001649 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001650 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1651 + prev + ", waitingVisible="
1652 + (prev != null ? prev.waitingVisible : null)
1653 + ", nowVisible=" + next.nowVisible);
1654 } else {
1655 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1656 + prev + ", waitingVisible="
1657 + (prev != null ? prev.waitingVisible : null)
1658 + ", nowVisible=" + next.nowVisible);
1659 }
1660 }
1661 }
1662
Dianne Hackborne7f97212011-02-24 14:40:20 -08001663 // Launching this app's activity, make sure the app is no longer
1664 // considered stopped.
1665 try {
1666 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001667 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001668 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001669 } catch (IllegalArgumentException e) {
1670 Slog.w(TAG, "Failed trying to unstop package "
1671 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001672 }
1673
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001674 // We are starting up the next activity, so tell the window manager
1675 // that the previous one will be hidden soon. This way it can know
1676 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001677 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001678 if (prev != null) {
1679 if (prev.finishing) {
1680 if (DEBUG_TRANSITION) Slog.v(TAG,
1681 "Prepare close transition: prev=" + prev);
1682 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001683 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001684 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001685 } else {
1686 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001687 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1688 : AppTransition.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001689 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001690 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1691 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001692 } else {
1693 if (DEBUG_TRANSITION) Slog.v(TAG,
1694 "Prepare open transition: prev=" + prev);
1695 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001696 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001697 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001698 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699 } else {
1700 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001701 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1702 : AppTransition.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001703 }
1704 }
1705 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001706 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1707 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001708 }
Craig Mautner000f0022013-02-26 15:04:29 -08001709 } else if (numActivities() > 1) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001710 if (DEBUG_TRANSITION) Slog.v(TAG,
1711 "Prepare open transition: no previous");
1712 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001713 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001714 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001715 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001716 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001717 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001718 AppTransition.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001719 }
1720 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001721 if (!noAnim) {
1722 next.applyOptionsLocked();
1723 } else {
1724 next.clearOptionsLocked();
1725 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001726
1727 if (next.app != null && next.app.thread != null) {
1728 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1729
1730 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001731 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001732
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001733 // schedule launch ticks to collect information about slow apps.
1734 next.startLaunchTickingLocked();
1735
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001736 ActivityRecord lastResumedActivity = mResumedActivity;
1737 ActivityState lastState = next.state;
1738
1739 mService.updateCpuStats();
1740
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001741 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001742 next.state = ActivityState.RESUMED;
1743 mResumedActivity = next;
1744 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001745 if (mMainStack) {
1746 mService.addRecentTaskLocked(next.task);
1747 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001748 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001749 updateLRUListLocked(next);
1750
1751 // Have the window manager re-evaluate the orientation of
1752 // the screen based on the new activity order.
1753 boolean updated = false;
1754 if (mMainStack) {
1755 synchronized (mService) {
1756 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1757 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001758 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001759 if (config != null) {
1760 next.frozenBeforeDestroy = true;
1761 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001762 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001763 }
1764 }
1765 if (!updated) {
1766 // The configuration update wasn't able to keep the existing
1767 // instance of the activity, and instead started a new one.
1768 // We should be all done, but let's just make sure our activity
1769 // is still at the top and schedule another run if something
1770 // weird happened.
1771 ActivityRecord nextNext = topRunningActivityLocked(null);
1772 if (DEBUG_SWITCH) Slog.i(TAG,
1773 "Activity config changed during resume: " + next
1774 + ", new next: " + nextNext);
1775 if (nextNext != next) {
1776 // Do over!
1777 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1778 }
1779 if (mMainStack) {
1780 mService.setFocusedActivityLocked(next);
1781 }
1782 ensureActivitiesVisibleLocked(null, 0);
1783 mService.mWindowManager.executeAppTransition();
1784 mNoAnimActivities.clear();
1785 return true;
1786 }
1787
1788 try {
1789 // Deliver all pending results.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08001790 ArrayList<ResultInfo> a = next.results;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001791 if (a != null) {
1792 final int N = a.size();
1793 if (!next.finishing && N > 0) {
1794 if (DEBUG_RESULTS) Slog.v(
1795 TAG, "Delivering results to " + next
1796 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001797 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001798 }
1799 }
1800
1801 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001802 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001803 }
1804
1805 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001806 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001807 next.task.taskId, next.shortComponentName);
1808
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001809 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001810 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001811 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001812 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 mService.isNextTransitionForward());
1814
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001815 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001816
1817 } catch (Exception e) {
1818 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001819 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1820 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 next.state = lastState;
1822 mResumedActivity = lastResumedActivity;
1823 Slog.i(TAG, "Restarting because process died: " + next);
1824 if (!next.hasBeenLaunched) {
1825 next.hasBeenLaunched = true;
1826 } else {
1827 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1828 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001829 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001830 mService.compatibilityInfoForPackageLocked(
1831 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001832 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001833 next.labelRes, next.icon, next.windowFlags,
1834 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001835 }
1836 }
1837 startSpecificActivityLocked(next, true, false);
1838 return true;
1839 }
1840
1841 // From this point on, if something goes wrong there is no way
1842 // to recover the activity.
1843 try {
1844 next.visible = true;
1845 completeResumeLocked(next);
1846 } catch (Exception e) {
1847 // If any exception gets thrown, toss away this
1848 // activity and try the next one.
1849 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001850 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001851 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001852 return true;
1853 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001854 next.stopped = false;
1855
1856 } else {
1857 // Whoops, need to restart this activity!
1858 if (!next.hasBeenLaunched) {
1859 next.hasBeenLaunched = true;
1860 } else {
1861 if (SHOW_APP_STARTING_PREVIEW) {
1862 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001863 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001864 mService.compatibilityInfoForPackageLocked(
1865 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001866 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001867 next.labelRes, next.icon, next.windowFlags,
1868 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001869 }
1870 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1871 }
1872 startSpecificActivityLocked(next, true, true);
1873 }
1874
1875 return true;
1876 }
1877
Craig Mautner11bf9a52013-02-19 14:08:51 -08001878 /** Temporary until startActivityLocked is rewritten for tasks. */
1879 private int convertAddPos(int addPos) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08001880 final ActivityRecord r = mHistory.get(addPos);
1881 return r.task.mActivities.indexOf(r);
Craig Mautner11bf9a52013-02-19 14:08:51 -08001882 }
1883
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001884 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001885 boolean doResume, boolean keepCurTransition, Bundle options) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08001886 mLastHistoryModifier = "startActivityLocked";
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 final int NH = mHistory.size();
1888
1889 int addPos = -1;
Craig Mautner0247fc82013-02-28 14:32:06 -08001890 if (VALIDATE_TASK_REPLACE) {
1891 verifyActivityRecords(true);
1892 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001893 if (!newTask) {
1894 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001895 boolean startIt = true;
1896 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001897 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001898 if (p.task == r.task) {
1899 // Here it is! Now, if this is not yet visible to the
1900 // user, then just add it without starting; it will
1901 // get started when the user navigates back to it.
1902 addPos = i+1;
1903 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001904 if (DEBUG_ADD_REMOVE) {
1905 RuntimeException here = new RuntimeException("here");
1906 here.fillInStackTrace();
1907 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1908 here);
1909 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001910 r.task.addActivityToTop(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001911 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001912 r.putInHistory();
Craig Mautner11bf9a52013-02-19 14:08:51 -08001913 mService.mWindowManager.addAppToken(convertAddPos(addPos), r.appToken,
1914 r.task.taskId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001915 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Craig Mautner0247fc82013-02-28 14:32:06 -08001916 if (VALIDATE_TASK_REPLACE) {
1917 verifyActivityRecords(true);
1918 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001919 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001920 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001921 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001922 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001923 return;
1924 }
1925 break;
1926 }
1927 if (p.fullscreen) {
1928 startIt = false;
1929 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001930 }
1931 }
1932
1933 // Place a new activity at top of stack, so it is next to interact
1934 // with the user.
1935 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001936 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001937 }
1938
1939 // If we are not placing the new activity frontmost, we do not want
1940 // to deliver the onUserLeaving callback to the actual frontmost
1941 // activity
1942 if (addPos < NH) {
1943 mUserLeaving = false;
1944 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1945 }
1946
1947 // Slot the activity into the history stack and proceed
Craig Mautner56f52db2013-02-25 10:03:01 -08001948 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1949 new RuntimeException("here").fillInStackTrace());
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001950 r.task.addActivityToTop(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001951 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001952 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001953 r.frontOfTask = newTask;
Craig Mautner11bf9a52013-02-19 14:08:51 -08001954 if (VALIDATE_TASK_REPLACE) {
1955 if (verifyActivityRecords(false)) {
1956 Slog.w(TAG, "startActivityLocked: addPos=" + addPos);
1957 }
1958 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001959 if (NH > 0) {
1960 // We want to show the starting preview window if we are
1961 // switching to a new task, or the next activity's process is
1962 // not currently running.
1963 boolean showStartingIcon = newTask;
1964 ProcessRecord proc = r.app;
1965 if (proc == null) {
1966 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1967 }
1968 if (proc == null || proc.thread == null) {
1969 showStartingIcon = true;
1970 }
1971 if (DEBUG_TRANSITION) Slog.v(TAG,
1972 "Prepare open transition: starting " + r);
1973 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001974 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001975 AppTransition.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001976 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001977 } else {
1978 mService.mWindowManager.prepareAppTransition(newTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08001979 ? AppTransition.TRANSIT_TASK_OPEN
1980 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001981 mNoAnimActivities.remove(r);
1982 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001983 r.updateOptionsLocked(options);
Craig Mautner11bf9a52013-02-19 14:08:51 -08001984 mService.mWindowManager.addAppToken(convertAddPos(addPos),
1985 r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
Craig Mautner5962b122012-10-05 14:45:52 -07001986 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001987 boolean doShow = true;
1988 if (newTask) {
1989 // Even though this activity is starting fresh, we still need
1990 // to reset it to make sure we apply affinities to move any
1991 // existing activities from other tasks in to it.
1992 // If the caller has requested that the target task be
1993 // reset, then do so.
1994 if ((r.intent.getFlags()
1995 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1996 resetTaskIfNeededLocked(r, r);
1997 doShow = topRunningNonDelayedActivityLocked(null) == r;
1998 }
1999 }
2000 if (SHOW_APP_STARTING_PREVIEW && doShow) {
2001 // Figure out if we are transitioning from another activity that is
2002 // "has the same starting icon" as the next one. This allows the
2003 // window manager to keep the previous window it had previously
2004 // created, if it still had one.
2005 ActivityRecord prev = mResumedActivity;
2006 if (prev != null) {
2007 // We don't want to reuse the previous starting preview if:
2008 // (1) The current activity is in a different task.
2009 if (prev.task != r.task) prev = null;
2010 // (2) The current activity is already displayed.
2011 else if (prev.nowVisible) prev = null;
2012 }
2013 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08002014 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07002015 mService.compatibilityInfoForPackageLocked(
2016 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002017 r.labelRes, r.icon, r.windowFlags,
2018 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 }
2020 } else {
2021 // If this is the first activity, don't do any fancy animations,
2022 // because there is nothing for it to animate on top of.
Craig Mautner11bf9a52013-02-19 14:08:51 -08002023 mService.mWindowManager.addAppToken(convertAddPos(addPos), r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07002024 r.info.screenOrientation, r.fullscreen,
2025 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002026 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002027 }
2028 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002029 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002030 }
2031
2032 if (doResume) {
2033 resumeTopActivityLocked(null);
2034 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002035 if (VALIDATE_TASK_REPLACE) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08002036 if (verifyActivityRecords(true)) {
2037 Slog.w(TAG, "startActivityLocked: addPos=" + addPos);
2038 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002039 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002040 }
2041
Dianne Hackbornbe707852011-11-11 14:32:10 -08002042 final void validateAppTokensLocked() {
Craig Mautner000f0022013-02-26 15:04:29 -08002043 verifyActivityRecords(true);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002044 mValidateAppTokens.clear();
Craig Mautner000f0022013-02-26 15:04:29 -08002045 mValidateAppTokens.ensureCapacity(numActivities());
2046 final int numTasks = mTaskHistory.size();
2047 for (int taskNdx = 0; taskNdx < numTasks; ++taskNdx) {
2048 TaskRecord task = mTaskHistory.get(taskNdx);
2049 final ArrayList<ActivityRecord> activities = task.mActivities;
2050 if (activities.size() == 0) {
2051 continue;
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08002052 }
Craig Mautner000f0022013-02-26 15:04:29 -08002053 TaskGroup group = new TaskGroup();
2054 group.taskId = task.taskId;
2055 mValidateAppTokens.add(group);
2056 final int numActivities = activities.size();
2057 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
2058 final ActivityRecord r = activities.get(activityNdx);
2059 group.tokens.add(r.appToken);
2060 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002061 }
2062 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
2063 }
2064
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002065 /**
2066 * Perform a reset of the given task, if needed as part of launching it.
2067 * Returns the new HistoryRecord at the top of the task.
2068 */
Craig Mautnere3a74d52013-02-22 14:14:58 -08002069 /**
2070 * Helper method for #resetTaskIfNeededLocked.
2071 * We are inside of the task being reset... we'll either finish this activity, push it out
2072 * for another task, or leave it as-is.
2073 * @param task The task containing the Activity (taskTop) that might be reset.
2074 * @param forceReset
2075 * @return An ActivityOptions that needs to be processed.
2076 */
2077 private final ActivityOptions resetTargetTaskIfNeededLocked(TaskRecord task,
2078 boolean forceReset) {
2079 ActivityOptions topOptions = null;
2080
2081 int replyChainEnd = -1;
2082 boolean canMoveOptions = true;
Craig Mautner0247fc82013-02-28 14:32:06 -08002083 if (VALIDATE_TASK_REPLACE) {
2084 verifyActivityRecords(true);
2085 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002086
2087 // We only do this for activities that are not the root of the task (since if we finish
2088 // the root, we may no longer have the task!).
2089 final ArrayList<ActivityRecord> activities = task.mActivities;
2090 final int numActivities = activities.size();
2091 for (int i = numActivities - 1; i > 0; --i ) {
2092 ActivityRecord target = activities.get(i);
2093
2094 final int flags = target.info.flags;
2095 final boolean finishOnTaskLaunch =
2096 (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2097 final boolean allowTaskReparenting =
2098 (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2099 final boolean clearWhenTaskReset =
2100 (target.intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2101
2102 if (!finishOnTaskLaunch
2103 && !clearWhenTaskReset
2104 && target.resultTo != null) {
2105 // If this activity is sending a reply to a previous
2106 // activity, we can't do anything with it now until
2107 // we reach the start of the reply chain.
2108 // XXX note that we are assuming the result is always
2109 // to the previous activity, which is almost always
2110 // the case but we really shouldn't count on.
2111 if (replyChainEnd < 0) {
2112 replyChainEnd = i;
2113 }
2114 } else if (!finishOnTaskLaunch
2115 && !clearWhenTaskReset
2116 && allowTaskReparenting
2117 && target.taskAffinity != null
2118 && !target.taskAffinity.equals(task.affinity)) {
2119 // If this activity has an affinity for another
2120 // task, then we need to move it out of here. We will
2121 // move it as far out of the way as possible, to the
2122 // bottom of the activity stack. This also keeps it
2123 // correctly ordered with any activities we previously
2124 // moved.
2125 TaskRecord bottomTask = mTaskHistory.get(0);
2126 ActivityRecord p = bottomTask.mActivities.get(0);
2127 if (target.taskAffinity != null
2128 && target.taskAffinity.equals(p.task.affinity)) {
2129 // If the activity currently at the bottom has the
2130 // same task affinity as the one we are moving,
2131 // then merge it into the same task.
2132 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
2133 "resetTaskFoundIntended: would reparenting " + target + " to bottom " + p.task);
Craig Mautner0247fc82013-02-28 14:32:06 -08002134 setTask(target, p.task, p.thumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002135 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2136 + " out to bottom task " + p.task);
2137 } else {
2138 do {
2139 mService.mCurTask++;
2140 if (mService.mCurTask <= 0) {
2141 mService.mCurTask = 1;
2142 }
2143 } while (mTaskIdToTaskRecord.get(mService.mCurTask) != null);
Craig Mautner0247fc82013-02-28 14:32:06 -08002144 setTask(target, createTaskRecord(mService.mCurTask, target.info, null, false),
Craig Mautnere3a74d52013-02-22 14:14:58 -08002145 null, false);
2146 target.task.affinityIntent = target.intent;
2147 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2148 + " out to new task " + target.task);
2149 }
2150
2151 final TaskRecord targetTask = target.task;
2152 final int targetTaskId = targetTask.taskId;
2153 mService.mWindowManager.setAppGroupId(target.appToken, targetTaskId);
2154
2155 ThumbnailHolder curThumbHolder = target.thumbHolder;
2156 boolean gotOptions = !canMoveOptions;
2157
2158 final int start = replyChainEnd < 0 ? i : replyChainEnd;
2159 for (int srcPos = start; srcPos >= i; --srcPos) {
2160 p = activities.get(srcPos);
2161 if (p.finishing) {
2162 continue;
2163 }
2164
2165 curThumbHolder = p.thumbHolder;
2166 canMoveOptions = false;
2167 if (!gotOptions && topOptions == null) {
2168 topOptions = p.takeOptionsLocked();
2169 if (topOptions != null) {
2170 gotOptions = true;
2171 }
2172 }
2173 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing activity " + p + " from task="
2174 + task + " adding to task=" + targetTask,
2175 new RuntimeException("here").fillInStackTrace());
2176 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2177 + " out to target's task " + target.task);
Craig Mautner0247fc82013-02-28 14:32:06 -08002178 setTask(p, targetTask, curThumbHolder, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002179 targetTask.addActivityAtBottom(p);
Craig Mautner0247fc82013-02-28 14:32:06 -08002180
2181 { // TODO: remove when mHistory no longer used.
2182 mHistory.remove(p);
2183 mHistory.add(0, p);
2184 }
2185
Craig Mautnere3a74d52013-02-22 14:14:58 -08002186 mService.mWindowManager.setAppGroupId(p.appToken, targetTaskId);
2187 }
Craig Mautner0247fc82013-02-28 14:32:06 -08002188 if (VALIDATE_TASK_REPLACE) {
2189 verifyActivityRecords(true);
2190 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002191
2192 mService.mWindowManager.moveTaskToBottom(targetTaskId);
2193 if (VALIDATE_TOKENS) {
2194 validateAppTokensLocked();
2195 }
2196
2197 replyChainEnd = -1;
2198 } else if (forceReset || finishOnTaskLaunch || clearWhenTaskReset) {
2199 // If the activity should just be removed -- either
2200 // because it asks for it, or the task should be
2201 // cleared -- then finish it and anything that is
2202 // part of its reply chain.
2203 int end;
2204 if (clearWhenTaskReset) {
2205 // In this case, we want to finish this activity
2206 // and everything above it, so be sneaky and pretend
2207 // like these are all in the reply chain.
2208 end = numActivities - 1;
2209 } else if (replyChainEnd < 0) {
2210 end = i;
2211 } else {
2212 end = replyChainEnd;
2213 }
2214 ActivityRecord p = null;
2215 boolean gotOptions = !canMoveOptions;
2216 for (int srcPos = i; srcPos <= end; srcPos++) {
2217 p = activities.get(srcPos);
2218 if (p.finishing) {
2219 continue;
2220 }
2221 canMoveOptions = false;
2222 if (!gotOptions && topOptions == null) {
2223 topOptions = p.takeOptionsLocked();
2224 if (topOptions != null) {
2225 gotOptions = true;
2226 }
2227 }
2228 if (DEBUG_TASKS || VALIDATE_TASK_REPLACE) Slog.w(TAG,
2229 "resetTaskIntendedTask: would call finishActivity on " + p);
Craig Mautnerd44711d2013-02-23 11:24:36 -08002230 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false)) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002231 end--;
2232 srcPos--;
2233 }
2234 }
2235 replyChainEnd = -1;
2236 } else {
2237 // If we were in the middle of a chain, well the
2238 // activity that started it all doesn't want anything
2239 // special, so leave it all as-is.
2240 replyChainEnd = -1;
2241 }
2242 }
2243
2244 return topOptions;
2245 }
2246
2247 /**
2248 * Helper method for #resetTaskIfNeededLocked. Processes all of the activities in a given
2249 * TaskRecord looking for an affinity with the task of resetTaskIfNeededLocked.taskTop.
2250 * @param affinityTask The task we are looking for an affinity to.
2251 * @param task Task that resetTaskIfNeededLocked.taskTop belongs to.
2252 * @param topTaskIsHigher True if #task has already been processed by resetTaskIfNeededLocked.
2253 * @param forceReset Flag passed in to resetTaskIfNeededLocked.
2254 */
2255 private final void resetAffinityTaskIfNeededLocked(TaskRecord affinityTask, TaskRecord task,
2256 boolean topTaskIsHigher, boolean forceReset
2257 , ActivityRecord taskTop
2258 ) {
2259 int replyChainEnd = -1;
2260 final int taskId = task.taskId;
2261 final String taskAffinity = task.affinity;
2262
2263 final ArrayList<ActivityRecord> activities = affinityTask.mActivities;
2264 final int numActivities = activities.size();
2265 // Do not operate on the root Activity.
2266 for (int i = numActivities - 1; i > 0; --i) {
2267 ActivityRecord target = activities.get(i);
2268
2269 final int flags = target.info.flags;
2270 boolean finishOnTaskLaunch = (flags & ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2271 boolean allowTaskReparenting = (flags & ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2272
2273 if (target.resultTo != null) {
2274 // If this activity is sending a reply to a previous
2275 // activity, we can't do anything with it now until
2276 // we reach the start of the reply chain.
2277 // XXX note that we are assuming the result is always
2278 // to the previous activity, which is almost always
2279 // the case but we really shouldn't count on.
2280 if (replyChainEnd < 0) {
2281 replyChainEnd = i;
2282 }
2283 } else if (topTaskIsHigher
2284 && allowTaskReparenting
2285 && taskAffinity != null
2286 && taskAffinity.equals(target.taskAffinity)) {
2287 // This activity has an affinity for our task. Either remove it if we are
2288 // clearing or move it over to our task. Note that
2289 // we currently punt on the case where we are resetting a
2290 // task that is not at the top but who has activities above
2291 // with an affinity to it... this is really not a normal
2292 // case, and we will need to later pull that task to the front
2293 // and usually at that point we will do the reset and pick
2294 // up those remaining activities. (This only happens if
2295 // someone starts an activity in a new task from an activity
2296 // in a task that is not currently on top.)
2297 if (forceReset || finishOnTaskLaunch) {
2298 final int start = replyChainEnd >= 0 ? replyChainEnd : i;
2299 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index " + start + " to " + i);
2300 for (int srcPos = start; srcPos >= i; --srcPos) {
2301 final ActivityRecord p = activities.get(srcPos);
2302 if (p.finishing) {
2303 continue;
2304 }
2305 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
2306 "resetAffinityTaskIfNeededLocked: calling finishActivity on " + p);
Craig Mautnerd44711d2013-02-23 11:24:36 -08002307 finishActivityLocked(p, Activity.RESULT_CANCELED, null, "reset", false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002308 }
2309 } else {
2310 int taskTopI = mHistory.indexOf(taskTop);
2311 final int end = replyChainEnd >= 0 ? replyChainEnd : i;
2312 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index " + i + " to " + end);
2313 for (int srcPos = i; srcPos <= end; ++srcPos) {
2314 final ActivityRecord p = activities.get(srcPos);
Craig Mautner0247fc82013-02-28 14:32:06 -08002315 setTask(p, task, null, false);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002316 task.addActivityToTop(p);
2317
Craig Mautner0247fc82013-02-28 14:32:06 -08002318 { // TODO: remove when mHistory no longer used.
2319 mHistory.remove(p);
2320 mHistory.add(taskTopI, p);
2321 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002322
2323 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + p
2324 + " to stack at " + task,
2325 new RuntimeException("here").fillInStackTrace());
2326 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p + " from " + srcPos
2327 + " in to resetting task " + task);
2328 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
2329 }
2330 mService.mWindowManager.moveTaskToTop(taskId);
Craig Mautnere3a74d52013-02-22 14:14:58 -08002331 if (VALIDATE_TASK_REPLACE) {
2332 verifyActivityRecords(false);
2333 }
Craig Mautner9658b312013-02-28 10:55:59 -08002334 if (VALIDATE_TOKENS) {
2335 validateAppTokensLocked();
2336 }
Craig Mautnere3a74d52013-02-22 14:14:58 -08002337
2338 // Now we've moved it in to place... but what if this is
2339 // a singleTop activity and we have put it on top of another
2340 // instance of the same activity? Then we drop the instance
2341 // below so it remains singleTop.
2342 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2343 ArrayList<ActivityRecord> taskActivities = task.mActivities;
2344 boolean found = false;
2345 int targetNdx = taskActivities.indexOf(target);
2346 if (targetNdx > 0) {
2347 ActivityRecord p = taskActivities.get(targetNdx - 1);
2348 if (p.intent.getComponent().equals(target.intent.getComponent())) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08002349 if (finishActivityLocked(p, Activity.RESULT_CANCELED, null, "replace",
2350 false)) {
Craig Mautnere3a74d52013-02-22 14:14:58 -08002351 taskTopI--;
2352 }
2353 }
2354 }
2355 }
2356 }
2357
2358 replyChainEnd = -1;
2359 }
2360 }
2361 }
2362
2363 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2364 ActivityRecord newActivity) {
2365 boolean forceReset =
2366 (newActivity.info.flags & ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
2367 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2368 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
2369 if ((newActivity.info.flags & ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2370 forceReset = true;
2371 }
2372 }
2373
2374 final TaskRecord task = taskTop.task;
2375
2376 /** False until we evaluate the TaskRecord associated with taskTop. Switches to true
2377 * for remaining tasks. Used for later tasks to reparent to task. */
2378 boolean taskFound = false;
2379
2380 /** If ActivityOptions are moved out and need to be aborted or moved to taskTop. */
2381 ActivityOptions topOptions = null;
2382
2383 for (int i = mTaskHistory.size() - 1; i >= 0; --i) {
2384 final TaskRecord targetTask = mTaskHistory.get(i);
2385
2386 if (targetTask == task) {
2387 topOptions = resetTargetTaskIfNeededLocked(task, forceReset);
2388 taskFound = true;
2389 } else {
2390 resetAffinityTaskIfNeededLocked(targetTask, task, taskFound, forceReset, taskTop);
2391 }
2392 }
2393
2394 taskTop = task.getTopActivity();
2395 if (topOptions != null) {
2396 // If we got some ActivityOptions from an activity on top that
2397 // was removed from the task, propagate them to the new real top.
2398 if (taskTop != null) {
2399 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
2400 "newResetTaskIfNeededLocked: would call updateOptionsLocked " + topOptions);
2401 taskTop.updateOptionsLocked(topOptions);
2402 } else {
2403 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
2404 "newResetTaskIfNeededLocked: would call " + topOptions + " abort");
2405 topOptions.abort();
2406 }
2407 }
2408
2409 return taskTop;
2410 }
2411
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002412 /**
2413 * Perform clear operation as requested by
2414 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2415 * stack to the given task, then look for
2416 * an instance of that activity in the stack and, if found, finish all
2417 * activities on top of it and return the instance.
2418 *
2419 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002420 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002421 * or null if none was found.
2422 */
Craig Mautner16030772013-02-26 16:05:47 -08002423 private final ActivityRecord performClearTaskLocked(TaskRecord task,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002424 ActivityRecord newR, int launchFlags) {
Craig Mautner16030772013-02-26 16:05:47 -08002425
2426 final ArrayList<ActivityRecord> activities = task.mActivities;
2427 int numActivities = activities.size();
2428 for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) {
2429 ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002430 if (r.finishing) {
2431 continue;
2432 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002433 if (r.realActivity.equals(newR.realActivity)) {
2434 // Here it is! Now finish everything in front...
2435 ActivityRecord ret = r;
Craig Mautner16030772013-02-26 16:05:47 -08002436
2437 for (++activityNdx; activityNdx < numActivities; ++activityNdx) {
2438 r = activities.get(activityNdx);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002439 if (r.finishing) {
2440 continue;
2441 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002442 ActivityOptions opts = r.takeOptionsLocked();
2443 if (opts != null) {
2444 ret.updateOptionsLocked(opts);
2445 }
Craig Mautner16030772013-02-26 16:05:47 -08002446 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
Craig Mautner9658b312013-02-28 10:55:59 -08002447 --activityNdx;
Craig Mautner16030772013-02-26 16:05:47 -08002448 --numActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002449 }
2450 }
Craig Mautner16030772013-02-26 16:05:47 -08002451
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002452 // Finally, if this is a normal launch mode (that is, not
2453 // expecting onNewIntent()), then we will finish the current
2454 // instance of the activity so a new fresh one can be started.
2455 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
Craig Mautner16030772013-02-26 16:05:47 -08002456 && (launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002457 if (!ret.finishing) {
Craig Mautner16030772013-02-26 16:05:47 -08002458 if (activities.contains(ret)) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08002459 finishActivityLocked(ret, Activity.RESULT_CANCELED, null,
2460 "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002461 }
2462 return null;
2463 }
2464 }
Craig Mautner16030772013-02-26 16:05:47 -08002465
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002466 return ret;
2467 }
2468 }
2469
2470 return null;
2471 }
2472
2473 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002474 * Completely remove all activities associated with an existing
2475 * task starting at a specified index.
2476 */
Craig Mautner16030772013-02-26 16:05:47 -08002477 private final void performClearTaskAtIndexLocked(TaskRecord task, int activityNdx) {
2478 final ArrayList<ActivityRecord> activities = task.mActivities;
2479 int numActivities = activities.size();
2480 for ( ; activityNdx < numActivities; ++activityNdx) {
2481 final ActivityRecord r = activities.get(activityNdx);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002482 if (r.finishing) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002483 continue;
2484 }
Craig Mautner16030772013-02-26 16:05:47 -08002485 if (finishActivityLocked(r, Activity.RESULT_CANCELED, null, "clear", false)) {
2486 --activityNdx;
2487 --numActivities;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002488 }
2489 }
2490 }
2491
2492 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002493 * Completely remove all activities associated with an existing task.
2494 */
Craig Mautner16030772013-02-26 16:05:47 -08002495 private final void performClearTaskLocked(TaskRecord task) {
2496 performClearTaskAtIndexLocked(task, 0);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002497 }
2498
2499 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002500 * Find the activity in the history stack within the given task. Returns
2501 * the index within the history at which it's found, or < 0 if not found.
2502 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002503 private final ActivityRecord findActivityInHistoryLocked(ActivityRecord r, TaskRecord task) {
2504 final ComponentName realActivity = r.realActivity;
2505 ArrayList<ActivityRecord> activities = task.mActivities;
2506 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
2507 ActivityRecord candidate = activities.get(activityNdx);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002508 if (candidate.finishing) {
2509 continue;
2510 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002511 if (candidate.realActivity.equals(realActivity)) {
2512 return candidate;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002513 }
2514 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002515 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002516 }
2517
2518 /**
2519 * Reorder the history stack so that the activity at the given index is
2520 * brought to the front.
2521 */
Craig Mautner56f52db2013-02-25 10:03:01 -08002522 private final void moveActivityToFrontLocked(ActivityRecord newTop) {
2523 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Removing and adding activity " + newTop
2524 + " to stack at top", new RuntimeException("here").fillInStackTrace());
Craig Mautner0247fc82013-02-28 14:32:06 -08002525 if (VALIDATE_TASK_REPLACE) {
2526 verifyActivityRecords(true);
2527 }
Craig Mautner56f52db2013-02-25 10:03:01 -08002528
2529 final TaskRecord task = newTop.task;
2530 task.getTopActivity().frontOfTask = false;
2531 task.mActivities.remove(newTop);
2532 task.mActivities.add(newTop);
2533 newTop.frontOfTask = true;
2534
Craig Mautner0247fc82013-02-28 14:32:06 -08002535 { // TODO: remove when mHistory no longer used.
2536 mHistory.remove(newTop);
2537 mHistory.add(newTop);
2538 }
2539
Craig Mautner11bf9a52013-02-19 14:08:51 -08002540 if (VALIDATE_TASK_REPLACE) {
2541 verifyActivityRecords(true);
2542 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002543 }
2544
2545 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002546 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002547 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002548 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002549 boolean componentSpecified, ActivityRecord[] outActivity) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08002550 mLastHistoryModifier = "startActivityLocked(IApplicationThread)";
Dianne Hackbornefb58102010-10-14 16:47:34 -07002551
Dianne Hackborna4972e92012-03-14 10:38:05 -07002552 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002553
2554 ProcessRecord callerApp = null;
2555 if (caller != null) {
2556 callerApp = mService.getRecordForAppLocked(caller);
2557 if (callerApp != null) {
2558 callingPid = callerApp.pid;
2559 callingUid = callerApp.info.uid;
2560 } else {
2561 Slog.w(TAG, "Unable to find app for caller " + caller
2562 + " (pid=" + callingPid + ") when starting: "
2563 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002564 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002565 }
2566 }
2567
Dianne Hackborna4972e92012-03-14 10:38:05 -07002568 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002569 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002570 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2571 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002572 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002573
2574 ActivityRecord sourceRecord = null;
2575 ActivityRecord resultRecord = null;
2576 if (resultTo != null) {
Craig Mautner56f52db2013-02-25 10:03:01 -08002577 sourceRecord = isInStackLocked(resultTo);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002578 if (DEBUG_RESULTS) Slog.v(
Craig Mautner56f52db2013-02-25 10:03:01 -08002579 TAG, "Will send result to " + resultTo + " " + sourceRecord);
2580 if (sourceRecord != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002581 if (requestCode >= 0 && !sourceRecord.finishing) {
2582 resultRecord = sourceRecord;
2583 }
2584 }
2585 }
2586
2587 int launchFlags = intent.getFlags();
2588
2589 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2590 && sourceRecord != null) {
2591 // Transfer the result target from the source activity to the new
2592 // one being started, including any failures.
2593 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002594 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002595 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002596 }
2597 resultRecord = sourceRecord.resultTo;
2598 resultWho = sourceRecord.resultWho;
2599 requestCode = sourceRecord.requestCode;
2600 sourceRecord.resultTo = null;
2601 if (resultRecord != null) {
2602 resultRecord.removeResultsLocked(
2603 sourceRecord, resultWho, requestCode);
2604 }
2605 }
2606
Dianne Hackborna4972e92012-03-14 10:38:05 -07002607 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002608 // We couldn't find a class that can handle the given Intent.
2609 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002610 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 }
2612
Dianne Hackborna4972e92012-03-14 10:38:05 -07002613 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002614 // We couldn't find the specific class specified in the Intent.
2615 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002616 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002617 }
2618
Dianne Hackborna4972e92012-03-14 10:38:05 -07002619 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002620 if (resultRecord != null) {
2621 sendActivityResultLocked(-1,
2622 resultRecord, resultWho, requestCode,
2623 Activity.RESULT_CANCELED, null);
2624 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002625 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002626 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002627 return err;
2628 }
2629
Jeff Sharkey35be7562012-04-18 19:16:15 -07002630 final int startAnyPerm = mService.checkPermission(
2631 START_ANY_ACTIVITY, callingPid, callingUid);
2632 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002633 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002634 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002635 if (resultRecord != null) {
2636 sendActivityResultLocked(-1,
2637 resultRecord, resultWho, requestCode,
2638 Activity.RESULT_CANCELED, null);
2639 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002640 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002641 String msg;
2642 if (!aInfo.exported) {
2643 msg = "Permission Denial: starting " + intent.toString()
2644 + " from " + callerApp + " (pid=" + callingPid
2645 + ", uid=" + callingUid + ")"
2646 + " not exported from uid " + aInfo.applicationInfo.uid;
2647 } else {
2648 msg = "Permission Denial: starting " + intent.toString()
2649 + " from " + callerApp + " (pid=" + callingPid
2650 + ", uid=" + callingUid + ")"
2651 + " requires " + aInfo.permission;
2652 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002653 Slog.w(TAG, msg);
2654 throw new SecurityException(msg);
2655 }
2656
2657 if (mMainStack) {
2658 if (mService.mController != null) {
2659 boolean abort = false;
2660 try {
2661 // The Intent we give to the watcher has the extra data
2662 // stripped off, since it can contain private information.
2663 Intent watchIntent = intent.cloneFilter();
2664 abort = !mService.mController.activityStarting(watchIntent,
2665 aInfo.applicationInfo.packageName);
2666 } catch (RemoteException e) {
2667 mService.mController = null;
2668 }
2669
2670 if (abort) {
2671 if (resultRecord != null) {
2672 sendActivityResultLocked(-1,
2673 resultRecord, resultWho, requestCode,
2674 Activity.RESULT_CANCELED, null);
2675 }
2676 // We pretend to the caller that it was really started, but
2677 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002678 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002679 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002680 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002681 }
2682 }
2683 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002684
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002685 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002686 intent, resolvedType, aInfo, mService.mConfiguration,
2687 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002688 if (outActivity != null) {
2689 outActivity[0] = r;
2690 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002691
2692 if (mMainStack) {
2693 if (mResumedActivity == null
2694 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2695 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2696 PendingActivityLaunch pal = new PendingActivityLaunch();
2697 pal.r = r;
2698 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002699 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002700 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002701 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002702 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002703 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002704 }
2705 }
2706
2707 if (mService.mDidAppSwitch) {
2708 // This is the second allowed switch since we stopped switches,
2709 // so now just generally allow switches. Use case: user presses
2710 // home (switches disabled, switch to home, mDidAppSwitch now true);
2711 // user taps a home icon (coming from home so allowed, we hit here
2712 // and now allow anyone to switch again).
2713 mService.mAppSwitchesAllowedTime = 0;
2714 } else {
2715 mService.mDidAppSwitch = true;
2716 }
2717
2718 mService.doPendingActivityLaunchesLocked(false);
2719 }
2720
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002721 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002722 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002723 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002724 // Someone asked to have the keyguard dismissed on the next
2725 // activity start, but we are not actually doing an activity
2726 // switch... just dismiss the keyguard now, because we
2727 // probably want to see whatever is behind it.
2728 mDismissKeyguardOnNextActivity = false;
2729 mService.mWindowManager.dismissKeyguard();
2730 }
2731 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002732 }
2733
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002734 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2735 if ((launchFlags &
2736 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2737 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2738 // Caller wants to appear on home activity, so before starting
2739 // their own activity we will bring home to the front.
2740 moveHomeToFrontLocked();
2741 }
2742 }
2743
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002744 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002745 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2746 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002747 final Intent intent = r.intent;
2748 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002749
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002750 int launchFlags = intent.getFlags();
2751
2752 // We'll invoke onUserLeaving before onPause only if the launching
2753 // activity did not explicitly state that this is an automated launch.
2754 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2755 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2756 "startActivity() => mUserLeaving=" + mUserLeaving);
2757
2758 // If the caller has asked not to resume at this point, we make note
2759 // of this in the record so that we can skip it when trying to find
2760 // the top running activity.
2761 if (!doResume) {
2762 r.delayedResume = true;
2763 }
2764
2765 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2766 != 0 ? r : null;
2767
2768 // If the onlyIfNeeded flag is set, then we can do this if the activity
2769 // being launched is the same as the one making the call... or, as
2770 // a special case, if we do not know the caller then we count the
2771 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002772 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002773 ActivityRecord checkedCaller = sourceRecord;
2774 if (checkedCaller == null) {
2775 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2776 }
2777 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2778 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002779 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002780 }
2781 }
2782
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002783 if (sourceRecord == null) {
2784 // This activity is not being started from another... in this
2785 // case we -always- start a new task.
2786 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2787 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2788 + intent);
2789 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2790 }
2791 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2792 // The original activity who is starting us is running as a single
2793 // instance... this new activity it is starting must go on its
2794 // own task.
2795 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2796 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2797 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2798 // The activity being started is a single instance... it always
2799 // gets launched into its own task.
2800 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2801 }
2802
2803 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2804 // For whatever reason this activity is being launched into a new
2805 // task... yet the caller has requested a result back. Well, that
2806 // is pretty messed up, so instead immediately send back a cancel
2807 // and let the new task continue launched as normal without a
2808 // dependency on its originator.
2809 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2810 sendActivityResultLocked(-1,
2811 r.resultTo, r.resultWho, r.requestCode,
2812 Activity.RESULT_CANCELED, null);
2813 r.resultTo = null;
2814 }
2815
2816 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002817 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002818 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002819 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2820 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2821 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2822 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2823 // If bring to front is requested, and no result is requested, and
2824 // we can find a task that was started with this same
2825 // component, then instead of launching bring that one to the front.
2826 if (r.resultTo == null) {
2827 // See if there is a task to bring to the front. If this is
2828 // a SINGLE_INSTANCE activity, there can be one and only one
2829 // instance of it in the history, and it is always in its own
2830 // unique task, so we do a special search.
2831 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2832 ? findTaskLocked(intent, r.info)
2833 : findActivityLocked(intent, r.info);
2834 if (taskTop != null) {
2835 if (taskTop.task.intent == null) {
2836 // This task was started because of movement of
2837 // the activity based on affinity... now that we
2838 // are actually launching it, we can assign the
2839 // base intent.
2840 taskTop.task.setIntent(intent, r.info);
2841 }
2842 // If the target task is not in the front, then we need
2843 // to bring it to the front... except... well, with
2844 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2845 // to have the same behavior as if a new instance was
2846 // being started, which means not bringing it to the front
2847 // if the caller is not itself in the front.
2848 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002849 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002850 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2851 boolean callerAtFront = sourceRecord == null
2852 || curTop.task == sourceRecord.task;
2853 if (callerAtFront) {
2854 // We really do want to push this one into the
2855 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002856 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002857 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002858 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002859 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 }
2861 }
2862 // If the caller has requested that the target task be
2863 // reset, then do so.
2864 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2865 taskTop = resetTaskIfNeededLocked(taskTop, r);
2866 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002867 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002868 // We don't need to start a new activity, and
2869 // the client said not to do anything if that
2870 // is the case, so this is it! And for paranoia, make
2871 // sure we have correctly resumed the top activity.
2872 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002873 resumeTopActivityLocked(null, options);
2874 } else {
2875 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002876 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002877 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002878 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002879 if ((launchFlags &
2880 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2881 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2882 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002883 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002884 // not be too hard...
2885 reuseTask = taskTop.task;
Craig Mautner16030772013-02-26 16:05:47 -08002886 performClearTaskLocked(taskTop.task);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002887 reuseTask.setIntent(r.intent, r.info);
2888 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2890 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2891 // In this situation we want to remove all activities
2892 // from the task up to the one being started. In most
2893 // cases this means we are resetting the task to its
2894 // initial state.
Craig Mautner16030772013-02-26 16:05:47 -08002895 ActivityRecord top = performClearTaskLocked(taskTop.task, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002896 if (top != null) {
2897 if (top.frontOfTask) {
2898 // Activity aliases may mean we use different
2899 // intents for the top activity, so make sure
2900 // the task now has the identity of the new
2901 // intent.
2902 top.task.setIntent(r.intent, r.info);
2903 }
2904 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002905 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002906 } else {
2907 // A special case: we need to
2908 // start the activity because it is not currently
2909 // running, and the caller has asked to clear the
2910 // current task to have this activity at the top.
2911 addingToTask = true;
2912 // Now pretend like this activity is being started
2913 // by the top of its task, so it is put in the
2914 // right place.
2915 sourceRecord = taskTop;
2916 }
2917 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2918 // In this case the top activity on the task is the
2919 // same as the one being launched, so we take that
2920 // as a request to bring the task to the foreground.
2921 // If the top activity in the task is the root
2922 // activity, deliver this new intent to it if it
2923 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002924 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2925 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002926 && taskTop.realActivity.equals(r.realActivity)) {
2927 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2928 if (taskTop.frontOfTask) {
2929 taskTop.task.setIntent(r.intent, r.info);
2930 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002931 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002932 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2933 // In this case we are launching the root activity
2934 // of the task, but with a different intent. We
2935 // should start a new instance on top.
2936 addingToTask = true;
2937 sourceRecord = taskTop;
2938 }
2939 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2940 // In this case an activity is being launched in to an
2941 // existing task, without resetting that task. This
2942 // is typically the situation of launching an activity
2943 // from a notification or shortcut. We want to place
2944 // the new activity on top of the current task.
2945 addingToTask = true;
2946 sourceRecord = taskTop;
2947 } else if (!taskTop.task.rootWasReset) {
2948 // In this case we are launching in to an existing task
2949 // that has not yet been started from its front door.
2950 // The current task has been brought to the front.
2951 // Ideally, we'd probably like to place this new task
2952 // at the bottom of its stack, but that's a little hard
2953 // to do with the current organization of the code so
2954 // for now we'll just drop it.
2955 taskTop.task.setIntent(r.intent, r.info);
2956 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002957 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002958 // We didn't do anything... but it was needed (a.k.a., client
2959 // don't use that intent!) And for paranoia, make
2960 // sure we have correctly resumed the top activity.
2961 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002962 resumeTopActivityLocked(null, options);
2963 } else {
2964 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002965 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002966 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002967 }
2968 }
2969 }
2970 }
2971
2972 //String uri = r.intent.toURI();
2973 //Intent intent2 = new Intent(uri);
2974 //Slog.i(TAG, "Given intent: " + r.intent);
2975 //Slog.i(TAG, "URI is: " + uri);
2976 //Slog.i(TAG, "To intent: " + intent2);
2977
2978 if (r.packageName != null) {
2979 // If the activity being launched is the same as the one currently
2980 // at the top, then we need to check if it should only be launched
2981 // once.
2982 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2983 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002984 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002985 if (top.app != null && top.app.thread != null) {
2986 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2987 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2988 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2989 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2990 // For paranoia, make sure we have correctly
2991 // resumed the top activity.
2992 if (doResume) {
2993 resumeTopActivityLocked(null);
2994 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002995 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002996 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002997 // We don't need to start a new activity, and
2998 // the client said not to do anything if that
2999 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07003000 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003001 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003002 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003003 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003004 }
3005 }
3006 }
3007 }
3008
3009 } else {
3010 if (r.resultTo != null) {
3011 sendActivityResultLocked(-1,
3012 r.resultTo, r.resultWho, r.requestCode,
3013 Activity.RESULT_CANCELED, null);
3014 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003015 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003016 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003017 }
3018
3019 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003020 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003021
3022 // Should this be considered a new task?
3023 if (r.resultTo == null && !addingToTask
3024 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003025 if (reuseTask == null) {
3026 // todo: should do better management of integers.
3027 mService.mCurTask++;
3028 if (mService.mCurTask <= 0) {
3029 mService.mCurTask = 1;
3030 }
Craig Mautner0247fc82013-02-28 14:32:06 -08003031 setTask(r, createTaskRecord(mService.mCurTask, r.info, intent, true), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003032 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3033 + " in new task " + r.task);
3034 } else {
Craig Mautner0247fc82013-02-28 14:32:06 -08003035 setTask(r, reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003036 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003037 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07003038 if (!movedHome) {
3039 moveHomeToFrontFromLaunchLocked(launchFlags);
3040 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003041
3042 } else if (sourceRecord != null) {
3043 if (!addingToTask &&
3044 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3045 // In this case, we are adding the activity to an existing
3046 // task, but the caller has asked to clear that task if the
3047 // activity is already running.
Craig Mautner16030772013-02-26 16:05:47 -08003048 ActivityRecord top = performClearTaskLocked(sourceRecord.task, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003049 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003050 if (top != null) {
3051 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003052 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003053 // For paranoia, make sure we have correctly
3054 // resumed the top activity.
3055 if (doResume) {
3056 resumeTopActivityLocked(null);
3057 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003058 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003059 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003060 }
3061 } else if (!addingToTask &&
3062 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
3063 // In this case, we are launching an activity in our own task
3064 // that may already be running somewhere in the history, and
3065 // we want to shuffle it to the front of the stack if so.
Craig Mautner56f52db2013-02-25 10:03:01 -08003066 final ActivityRecord top = findActivityInHistoryLocked(r, sourceRecord.task);
3067 if (top != null) {
3068 moveActivityToFrontLocked(top);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003069 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003070 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003071 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003072 if (doResume) {
3073 resumeTopActivityLocked(null);
3074 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003075 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003076 }
3077 }
3078 // An existing activity is starting this new activity, so we want
3079 // to keep the new one in the same task as the one that is starting
3080 // it.
Craig Mautner0247fc82013-02-28 14:32:06 -08003081 setTask(r, sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003082 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3083 + " in existing task " + r.task);
3084
3085 } else {
3086 // This not being started from an existing activity, and not part
3087 // of a new task... just put it in the top task, though these days
3088 // this case should never happen.
Craig Mautner9658b312013-02-28 10:55:59 -08003089 ActivityRecord prev = null;
3090 // Iterate to find the first non-empty task stack. Note that this code can
3091 // go away once we stop storing tasks with empty mActivities lists.
3092 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3093 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3094 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3095 prev = activities.get(activityNdx);
3096 break;
3097 }
3098 }
Craig Mautner0247fc82013-02-28 14:32:06 -08003099 setTask(r, prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003100 ? prev.task
Craig Mautner5d9c7be2013-02-15 14:02:56 -08003101 : createTaskRecord(mService.mCurTask, r.info, intent, true), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003102 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3103 + " in new guessed " + r.task);
3104 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003105
Dianne Hackborn39792d22010-08-19 18:01:52 -07003106 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003107 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07003108
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003109 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003110 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003111 }
3112 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003113 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003114 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003115 }
3116
Dianne Hackborna4972e92012-03-14 10:38:05 -07003117 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003118 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003119 // Collect information about the target of the Intent.
3120 ActivityInfo aInfo;
3121 try {
3122 ResolveInfo rInfo =
3123 AppGlobals.getPackageManager().resolveIntent(
3124 intent, resolvedType,
3125 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003126 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003127 aInfo = rInfo != null ? rInfo.activityInfo : null;
3128 } catch (RemoteException e) {
3129 aInfo = null;
3130 }
3131
3132 if (aInfo != null) {
3133 // Store the found target back into the intent, because now that
3134 // we have it we never want to do this again. For example, if the
3135 // user navigates back to this point in the history, we should
3136 // always restart the exact same activity.
3137 intent.setComponent(new ComponentName(
3138 aInfo.applicationInfo.packageName, aInfo.name));
3139
3140 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003141 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003142 if (!aInfo.processName.equals("system")) {
3143 mService.setDebugApp(aInfo.processName, true, false);
3144 }
3145 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003146
Dianne Hackborna4972e92012-03-14 10:38:05 -07003147 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003148 if (!aInfo.processName.equals("system")) {
3149 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3150 }
3151 }
3152
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003153 if (profileFile != null) {
3154 if (!aInfo.processName.equals("system")) {
3155 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003156 profileFile, profileFd,
3157 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003158 }
3159 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003160 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003161 return aInfo;
3162 }
3163
3164 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003165 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003166 String resultWho, int requestCode, int startFlags, String profileFile,
3167 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3168 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003169 // Refuse possible leaked file descriptors
3170 if (intent != null && intent.hasFileDescriptors()) {
3171 throw new IllegalArgumentException("File descriptors passed in Intent");
3172 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003173 boolean componentSpecified = intent.getComponent() != null;
3174
3175 // Don't modify the client's object!
3176 intent = new Intent(intent);
3177
3178 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003179 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003180 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003181
3182 synchronized (mService) {
3183 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003184 if (callingUid >= 0) {
3185 callingPid = -1;
3186 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003187 callingPid = Binder.getCallingPid();
3188 callingUid = Binder.getCallingUid();
3189 } else {
3190 callingPid = callingUid = -1;
3191 }
3192
3193 mConfigWillChange = config != null
3194 && mService.mConfiguration.diff(config) != 0;
3195 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3196 "Starting activity when config will change = " + mConfigWillChange);
3197
3198 final long origId = Binder.clearCallingIdentity();
3199
3200 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003201 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003202 // This may be a heavy-weight process! Check to see if we already
3203 // have another, different heavy-weight process running.
3204 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3205 if (mService.mHeavyWeightProcess != null &&
3206 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3207 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3208 int realCallingPid = callingPid;
3209 int realCallingUid = callingUid;
3210 if (caller != null) {
3211 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3212 if (callerApp != null) {
3213 realCallingPid = callerApp.pid;
3214 realCallingUid = callerApp.info.uid;
3215 } else {
3216 Slog.w(TAG, "Unable to find app for caller " + caller
3217 + " (pid=" + realCallingPid + ") when starting: "
3218 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003219 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003220 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003221 }
3222 }
3223
3224 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003225 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003226 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003227 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003228 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003229
3230 Intent newIntent = new Intent();
3231 if (requestCode >= 0) {
3232 // Caller is requesting a result.
3233 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3234 }
3235 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3236 new IntentSender(target));
3237 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3238 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3239 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3240 hist.packageName);
3241 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3242 hist.task.taskId);
3243 }
3244 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3245 aInfo.packageName);
3246 newIntent.setFlags(intent.getFlags());
3247 newIntent.setClassName("android",
3248 HeavyWeightSwitcherActivity.class.getName());
3249 intent = newIntent;
3250 resolvedType = null;
3251 caller = null;
3252 callingUid = Binder.getCallingUid();
3253 callingPid = Binder.getCallingPid();
3254 componentSpecified = true;
3255 try {
3256 ResolveInfo rInfo =
3257 AppGlobals.getPackageManager().resolveIntent(
3258 intent, null,
3259 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003260 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003261 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003262 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003263 } catch (RemoteException e) {
3264 aInfo = null;
3265 }
3266 }
3267 }
3268 }
3269
3270 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003271 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003272 callingPackage, startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003273
3274 if (mConfigWillChange && mMainStack) {
3275 // If the caller also wants to switch to a new configuration,
3276 // do so now. This allows a clean switch, as we are waiting
3277 // for the current activity to pause (so we will not destroy
3278 // it), and have not yet started the next activity.
3279 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3280 "updateConfiguration()");
3281 mConfigWillChange = false;
3282 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3283 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003284 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003285 }
3286
3287 Binder.restoreCallingIdentity(origId);
3288
3289 if (outResult != null) {
3290 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003291 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003292 mWaitingActivityLaunched.add(outResult);
3293 do {
3294 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003295 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003296 } catch (InterruptedException e) {
3297 }
3298 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003299 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003300 ActivityRecord r = this.topRunningActivityLocked(null);
3301 if (r.nowVisible) {
3302 outResult.timeout = false;
3303 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3304 outResult.totalTime = 0;
3305 outResult.thisTime = 0;
3306 } else {
3307 outResult.thisTime = SystemClock.uptimeMillis();
3308 mWaitingActivityVisible.add(outResult);
3309 do {
3310 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003311 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003312 } catch (InterruptedException e) {
3313 }
3314 } while (!outResult.timeout && outResult.who == null);
3315 }
3316 }
3317 }
3318
3319 return res;
3320 }
3321 }
3322
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003323 final int startActivities(IApplicationThread caller, int callingUid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003324 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3325 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003326 if (intents == null) {
3327 throw new NullPointerException("intents is null");
3328 }
3329 if (resolvedTypes == null) {
3330 throw new NullPointerException("resolvedTypes is null");
3331 }
3332 if (intents.length != resolvedTypes.length) {
3333 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3334 }
3335
3336 ActivityRecord[] outActivity = new ActivityRecord[1];
3337
3338 int callingPid;
3339 if (callingUid >= 0) {
3340 callingPid = -1;
3341 } else if (caller == null) {
3342 callingPid = Binder.getCallingPid();
3343 callingUid = Binder.getCallingUid();
3344 } else {
3345 callingPid = callingUid = -1;
3346 }
3347 final long origId = Binder.clearCallingIdentity();
3348 try {
3349 synchronized (mService) {
3350
3351 for (int i=0; i<intents.length; i++) {
3352 Intent intent = intents[i];
3353 if (intent == null) {
3354 continue;
3355 }
3356
3357 // Refuse possible leaked file descriptors
3358 if (intent != null && intent.hasFileDescriptors()) {
3359 throw new IllegalArgumentException("File descriptors passed in Intent");
3360 }
3361
3362 boolean componentSpecified = intent.getComponent() != null;
3363
3364 // Don't modify the client's object!
3365 intent = new Intent(intent);
3366
3367 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003368 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003369 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003370 // TODO: New, check if this is correct
3371 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003372
3373 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3374 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3375 throw new IllegalArgumentException(
3376 "FLAG_CANT_SAVE_STATE not supported here");
3377 }
3378
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003379 Bundle theseOptions;
3380 if (options != null && i == intents.length-1) {
3381 theseOptions = options;
3382 } else {
3383 theseOptions = null;
3384 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003385 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003386 aInfo, resultTo, null, -1, callingPid, callingUid, callingPackage,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003387 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003388 if (res < 0) {
3389 return res;
3390 }
3391
Dianne Hackbornbe707852011-11-11 14:32:10 -08003392 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003393 }
3394 }
3395 } finally {
3396 Binder.restoreCallingIdentity(origId);
3397 }
3398
Dianne Hackborna4972e92012-03-14 10:38:05 -07003399 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003400 }
3401
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003402 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3403 long thisTime, long totalTime) {
3404 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3405 WaitResult w = mWaitingActivityLaunched.get(i);
3406 w.timeout = timeout;
3407 if (r != null) {
3408 w.who = new ComponentName(r.info.packageName, r.info.name);
3409 }
3410 w.thisTime = thisTime;
3411 w.totalTime = totalTime;
3412 }
3413 mService.notifyAll();
3414 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003415
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003416 void reportActivityVisibleLocked(ActivityRecord r) {
3417 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3418 WaitResult w = mWaitingActivityVisible.get(i);
3419 w.timeout = false;
3420 if (r != null) {
3421 w.who = new ComponentName(r.info.packageName, r.info.name);
3422 }
3423 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3424 w.thisTime = w.totalTime;
3425 }
3426 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003427
3428 if (mDismissKeyguardOnNextActivity) {
3429 mDismissKeyguardOnNextActivity = false;
3430 mService.mWindowManager.dismissKeyguard();
3431 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003432 }
3433
3434 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3435 String resultWho, int requestCode, int resultCode, Intent data) {
3436
3437 if (callingUid > 0) {
3438 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003439 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003440 }
3441
3442 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3443 + " : who=" + resultWho + " req=" + requestCode
3444 + " res=" + resultCode + " data=" + data);
3445 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3446 try {
3447 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3448 list.add(new ResultInfo(resultWho, requestCode,
3449 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003450 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003451 return;
3452 } catch (Exception e) {
3453 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3454 }
3455 }
3456
3457 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3458 }
3459
3460 private final void stopActivityLocked(ActivityRecord r) {
3461 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3462 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3463 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3464 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003465 if (!mService.mSleeping) {
3466 if (DEBUG_STATES) {
3467 Slog.d(TAG, "no-history finish of " + r);
3468 }
3469 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003470 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003471 } else {
3472 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3473 + " on stop because we're just sleeping");
3474 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003475 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003476 }
3477
3478 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003479 if (mMainStack) {
3480 if (mService.mFocusedActivity == r) {
3481 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3482 }
3483 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003484 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003485 try {
3486 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003487 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3488 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003489 r.state = ActivityState.STOPPING;
3490 if (DEBUG_VISBILITY) Slog.v(
3491 TAG, "Stopping visible=" + r.visible + " for " + r);
3492 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003493 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003494 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003495 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003496 if (mService.isSleeping()) {
3497 r.setSleeping(true);
3498 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003499 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3500 msg.obj = r;
3501 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003502 } catch (Exception e) {
3503 // Maybe just ignore exceptions here... if the process
3504 // has crashed, our death notification will clean things
3505 // up.
3506 Slog.w(TAG, "Exception thrown during pause", e);
3507 // Just in case, assume it to be stopped.
3508 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003509 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003510 r.state = ActivityState.STOPPED;
3511 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003512 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003513 }
3514 }
3515 }
3516 }
3517
3518 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3519 boolean remove) {
3520 int N = mStoppingActivities.size();
3521 if (N <= 0) return null;
3522
3523 ArrayList<ActivityRecord> stops = null;
3524
3525 final boolean nowVisible = mResumedActivity != null
3526 && mResumedActivity.nowVisible
3527 && !mResumedActivity.waitingVisible;
3528 for (int i=0; i<N; i++) {
3529 ActivityRecord s = mStoppingActivities.get(i);
3530 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3531 + nowVisible + " waitingVisible=" + s.waitingVisible
3532 + " finishing=" + s.finishing);
3533 if (s.waitingVisible && nowVisible) {
3534 mWaitingVisibleActivities.remove(s);
3535 s.waitingVisible = false;
3536 if (s.finishing) {
3537 // If this activity is finishing, it is sitting on top of
3538 // everyone else but we now know it is no longer needed...
3539 // so get rid of it. Otherwise, we need to go through the
3540 // normal flow and hide it once we determine that it is
3541 // hidden by the activities in front of it.
3542 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003543 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003544 }
3545 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003546 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003547 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3548 if (stops == null) {
3549 stops = new ArrayList<ActivityRecord>();
3550 }
3551 stops.add(s);
3552 mStoppingActivities.remove(i);
3553 N--;
3554 i--;
3555 }
3556 }
3557
3558 return stops;
3559 }
3560
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003561 final void scheduleIdleLocked() {
3562 Message msg = Message.obtain();
3563 msg.what = IDLE_NOW_MSG;
3564 mHandler.sendMessage(msg);
3565 }
3566
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003567 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003568 Configuration config) {
3569 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3570
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003571 ActivityRecord res = null;
3572
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003573 ArrayList<ActivityRecord> stops = null;
3574 ArrayList<ActivityRecord> finishes = null;
3575 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003576 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003577 int NS = 0;
3578 int NF = 0;
3579 int NT = 0;
3580 IApplicationThread sendThumbnail = null;
3581 boolean booting = false;
3582 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003583 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003584
3585 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003586 ActivityRecord r = ActivityRecord.forToken(token);
3587 if (r != null) {
3588 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003589 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 }
3591
3592 // Get the activity record.
Craig Mautnerd44711d2013-02-23 11:24:36 -08003593 if (isInStackLocked(token) != null) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003594 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003595
3596 if (fromTimeout) {
3597 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3598 }
3599
3600 // This is a hack to semi-deal with a race condition
3601 // in the client where it can be constructed with a
3602 // newer configuration from when we asked it to launch.
3603 // We'll update with whatever configuration it now says
3604 // it used to launch.
3605 if (config != null) {
3606 r.configuration = config;
3607 }
3608
3609 // No longer need to keep the device awake.
3610 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3611 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3612 mLaunchingActivity.release();
3613 }
3614
3615 // We are now idle. If someone is waiting for a thumbnail from
3616 // us, we can now deliver.
3617 r.idle = true;
3618 mService.scheduleAppGcsLocked();
3619 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3620 sendThumbnail = r.app.thread;
3621 r.thumbnailNeeded = false;
3622 }
3623
3624 // If this activity is fullscreen, set up to hide those under it.
3625
3626 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3627 ensureActivitiesVisibleLocked(null, 0);
3628
3629 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3630 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003631 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003632 mService.mBooted = true;
3633 enableScreen = true;
3634 }
3635 }
3636
3637 } else if (fromTimeout) {
3638 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3639 }
3640
3641 // Atomically retrieve all of the other things to do.
3642 stops = processStoppingActivitiesLocked(true);
3643 NS = stops != null ? stops.size() : 0;
3644 if ((NF=mFinishingActivities.size()) > 0) {
3645 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3646 mFinishingActivities.clear();
3647 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003648 if ((NT=mCancelledThumbnails.size()) > 0) {
3649 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3650 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003651 }
3652
3653 if (mMainStack) {
3654 booting = mService.mBooting;
3655 mService.mBooting = false;
3656 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003657 if (mStartingUsers.size() > 0) {
3658 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3659 mStartingUsers.clear();
3660 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003661 }
3662
3663 int i;
3664
3665 // Send thumbnail if requested.
3666 if (sendThumbnail != null) {
3667 try {
3668 sendThumbnail.requestThumbnail(token);
3669 } catch (Exception e) {
3670 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3671 mService.sendPendingThumbnail(null, token, null, null, true);
3672 }
3673 }
3674
3675 // Stop any activities that are scheduled to do so but have been
3676 // waiting for the next one to start.
3677 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003678 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003679 synchronized (mService) {
3680 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003681 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003682 } else {
3683 stopActivityLocked(r);
3684 }
3685 }
3686 }
3687
3688 // Finish any activities that are scheduled to do so but have been
3689 // waiting for the next one to start.
3690 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003691 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003692 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003693 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003694 }
3695 }
3696
3697 // Report back to any thumbnail receivers.
3698 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003699 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003700 mService.sendPendingThumbnail(r, null, null, null, true);
3701 }
3702
3703 if (booting) {
3704 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003705 } else if (startingUsers != null) {
3706 for (i=0; i<startingUsers.size(); i++) {
3707 mService.finishUserSwitch(startingUsers.get(i));
3708 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003709 }
3710
3711 mService.trimApplications();
3712 //dump();
3713 //mWindowManager.dump();
3714
3715 if (enableScreen) {
3716 mService.enableScreenAfterBoot();
3717 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003718
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003719 if (activityRemoved) {
3720 resumeTopActivityLocked(null);
3721 }
3722
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003723 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003724 }
3725
3726 /**
3727 * @return Returns true if the activity is being finished, false if for
3728 * some reason it is being left as-is.
3729 */
3730 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003731 Intent resultData, String reason, boolean oomAdj) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003732 ActivityRecord r = isInStackLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003733 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003734 TAG, "Finishing activity token=" + token + " r="
Christopher Tated3f175c2012-06-14 14:16:54 -07003735 + ", result=" + resultCode + ", data=" + resultData
3736 + ", reason=" + reason);
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003737 if (r == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003738 return false;
3739 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003740
Craig Mautnerd44711d2013-02-23 11:24:36 -08003741 finishActivityLocked(r, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003742 return true;
3743 }
3744
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003745 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3746 ActivityRecord self = isInStackLocked(token);
3747 if (self == null) {
3748 return;
3749 }
3750
Craig Mautner9658b312013-02-28 10:55:59 -08003751 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
3752 ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
3753 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
3754 ActivityRecord r = activities.get(activityNdx);
3755 if (r.resultTo == self && r.requestCode == requestCode) {
3756 if ((r.resultWho == null && resultWho == null) ||
3757 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3758 finishActivityLocked(r, Activity.RESULT_CANCELED, null, "request-sub",
3759 false);
3760 }
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003761 }
3762 }
3763 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003764 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003765 }
3766
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003767 final void finishTopRunningActivityLocked(ProcessRecord app) {
3768 ActivityRecord r = topRunningActivityLocked(null);
3769 if (r != null && r.app == app) {
3770 // If the top running activity is from this crashing
3771 // process, then terminate it to avoid getting in a loop.
3772 Slog.w(TAG, " Force finishing activity "
3773 + r.intent.getComponent().flattenToShortString());
Craig Mautner9658b312013-02-28 10:55:59 -08003774 int taskNdx = mTaskHistory.indexOf(r.task);
3775 int activityNdx = r.task.mActivities.indexOf(r);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003776 r.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
3777 null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003778 // Also terminate any activities below it that aren't yet
3779 // stopped, to avoid a situation where one will get
3780 // re-start our crashing activity once it gets resumed again.
Craig Mautner9658b312013-02-28 10:55:59 -08003781 --activityNdx;
3782 if (activityNdx < 0) {
3783 do {
3784 --taskNdx;
3785 if (taskNdx < 0) {
3786 break;
3787 }
3788 activityNdx = mTaskHistory.get(taskNdx).mActivities.size() - 1;
3789 } while (activityNdx < 0);
3790 }
3791 if (activityNdx >= 0) {
3792 r = mTaskHistory.get(taskNdx).mActivities.get(activityNdx);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003793 if (r.state == ActivityState.RESUMED
3794 || r.state == ActivityState.PAUSING
3795 || r.state == ActivityState.PAUSED) {
3796 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3797 Slog.w(TAG, " Force finishing activity "
3798 + r.intent.getComponent().flattenToShortString());
Craig Mautnerd44711d2013-02-23 11:24:36 -08003799 r.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
3800 null, "crashed", false);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003801 }
3802 }
3803 }
3804 }
3805 }
3806
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003807 final boolean finishActivityAffinityLocked(IBinder token) {
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003808 ActivityRecord r = isInStackLocked(token);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003809 if (DEBUG_RESULTS) Slog.v(
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003810 TAG, "Finishing activity affinity token=" + token + " r=" + r);
3811 if (r == null) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003812 return false;
3813 }
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003814
Craig Mautnerd74f7d72013-02-26 13:41:02 -08003815 ArrayList<ActivityRecord> activities = r.task.mActivities;
3816 for (int index = activities.indexOf(r); index >= 0; --index) {
3817 ActivityRecord cur = activities.get(index);
3818 if (!Objects.equal(cur.taskAffinity, r.taskAffinity)) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003819 break;
3820 }
Craig Mautnerd44711d2013-02-23 11:24:36 -08003821 finishActivityLocked(cur, Activity.RESULT_CANCELED, null, "request-affinity",
3822 true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003823 }
3824 return true;
3825 }
3826
Dianne Hackborn5c607432012-02-28 14:44:19 -08003827 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3828 // send the result
3829 ActivityRecord resultTo = r.resultTo;
3830 if (resultTo != null) {
3831 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3832 + " who=" + r.resultWho + " req=" + r.requestCode
3833 + " res=" + resultCode + " data=" + resultData);
3834 if (r.info.applicationInfo.uid > 0) {
3835 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3836 resultTo.packageName, resultData,
3837 resultTo.getUriPermissionsLocked());
3838 }
3839 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3840 resultData);
3841 r.resultTo = null;
3842 }
3843 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3844
3845 // Make sure this HistoryRecord is not holding on to other resources,
3846 // because clients have remote IPC references to this object so we
3847 // can't assume that will go away and want to avoid circular IPC refs.
3848 r.results = null;
3849 r.pendingResults = null;
3850 r.newIntents = null;
3851 r.icicle = null;
3852 }
3853
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003854 /**
3855 * @return Returns true if this activity has been removed from the history
3856 * list, or false if it is still in the list and will be removed later.
3857 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003858 final boolean finishActivityLocked(ActivityRecord r, int resultCode,
3859 Intent resultData, String reason, boolean oomAdj) {
3860 return finishActivityLocked(r, resultCode, resultData, reason, false, oomAdj);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003861 }
3862
3863 /**
3864 * @return Returns true if this activity has been removed from the history
3865 * list, or false if it is still in the list and will be removed later.
3866 */
Craig Mautnerd44711d2013-02-23 11:24:36 -08003867 final boolean finishActivityLocked(ActivityRecord r, int resultCode, Intent resultData,
3868 String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003869 if (r.finishing) {
3870 Slog.w(TAG, "Duplicate finish request for " + r);
3871 return false;
3872 }
3873
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003874 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003875 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003876 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003877 r.task.taskId, r.shortComponentName, reason);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003878 final ArrayList<ActivityRecord> activities = r.task.mActivities;
3879 final int index = activities.indexOf(r);
3880 if (index < (activities.size() - 1)) {
3881 ActivityRecord next = activities.get(index+1);
3882 if (r.frontOfTask) {
3883 // The next activity is now the front of the task.
3884 next.frontOfTask = true;
3885 }
3886 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3887 // If the caller asked that this activity (and all above it)
3888 // be cleared when the task is reset, don't lose that information,
3889 // but propagate it up to the next activity.
3890 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003891 }
3892 }
3893
3894 r.pauseKeyDispatchingLocked();
3895 if (mMainStack) {
3896 if (mService.mFocusedActivity == r) {
3897 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3898 }
3899 }
3900
Dianne Hackborn5c607432012-02-28 14:44:19 -08003901 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003902
3903 if (mService.mPendingThumbnails.size() > 0) {
3904 // There are clients waiting to receive thumbnails so, in case
3905 // this is an activity that someone is waiting for, add it
3906 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08003907 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003908 }
3909
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003910 if (immediate) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08003911 return finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003912 } else if (mResumedActivity == r) {
Craig Mautner0247fc82013-02-28 14:32:06 -08003913 boolean endTask = index <= 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003914 if (DEBUG_TRANSITION) Slog.v(TAG,
3915 "Prepare close transition: finishing " + r);
3916 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08003917 ? AppTransition.TRANSIT_TASK_CLOSE
3918 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Craig Mautner0247fc82013-02-28 14:32:06 -08003919
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003920 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003921 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003922
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003923 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003924 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3925 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3926 startPausingLocked(false, false);
3927 }
3928
3929 } else if (r.state != ActivityState.PAUSING) {
3930 // If the activity is PAUSING, we will complete the finish once
3931 // it is done pausing; else we can just directly finish it here.
3932 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
Craig Mautnerd44711d2013-02-23 11:24:36 -08003933 return finishCurrentActivityLocked(r, FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003934 } else {
3935 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3936 }
3937
3938 return false;
3939 }
3940
3941 private static final int FINISH_IMMEDIATELY = 0;
3942 private static final int FINISH_AFTER_PAUSE = 1;
3943 private static final int FINISH_AFTER_VISIBLE = 2;
3944
Craig Mautnerd44711d2013-02-23 11:24:36 -08003945
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003946 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003947 int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003948 // First things first: if this activity is currently visible,
3949 // and the resumed activity is not yet visible, then hold off on
3950 // finishing until the resumed one becomes visible.
3951 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3952 if (!mStoppingActivities.contains(r)) {
3953 mStoppingActivities.add(r);
3954 if (mStoppingActivities.size() > 3) {
3955 // If we already have a few activities waiting to stop,
3956 // then give up on things going idle and start clearing
3957 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003958 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003959 } else {
3960 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003961 }
3962 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003963 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3964 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003965 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003966 if (oomAdj) {
3967 mService.updateOomAdjLocked();
3968 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003969 return r;
3970 }
3971
3972 // make sure the record is cleaned out of other places.
3973 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003974 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003975 mWaitingVisibleActivities.remove(r);
3976 if (mResumedActivity == r) {
3977 mResumedActivity = null;
3978 }
3979 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003980 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003981 r.state = ActivityState.FINISHING;
3982
3983 if (mode == FINISH_IMMEDIATELY
3984 || prevState == ActivityState.STOPPED
3985 || prevState == ActivityState.INITIALIZING) {
3986 // If this activity is already stopped, we can just finish
3987 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003988 boolean activityRemoved = destroyActivityLocked(r, true,
3989 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003990 if (activityRemoved) {
3991 resumeTopActivityLocked(null);
3992 }
3993 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003994 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003995
3996 // Need to go through the full pause cycle to get this
3997 // activity into the stopped state and then finish it.
3998 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
3999 mFinishingActivities.add(r);
4000 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004001 return r;
4002 }
4003
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004004 final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
4005 Intent resultData) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004006 final TaskRecord task = srec.task;
4007 final ArrayList<ActivityRecord> activities = task.mActivities;
4008 final int start = activities.indexOf(srec);
4009 if (!mTaskHistory.contains(task) || (start < 0)) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004010 return false;
4011 }
4012 int finishTo = start - 1;
Craig Mautner0247fc82013-02-28 14:32:06 -08004013 ActivityRecord parent = finishTo < 0 ? null : activities.get(finishTo);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004014 boolean foundParentInTask = false;
Craig Mautner0247fc82013-02-28 14:32:06 -08004015 final ComponentName dest = destIntent.getComponent();
4016 if (start > 0 && dest != null) {
4017 for (int i = finishTo; i >= 0; i--) {
4018 ActivityRecord r = activities.get(i);
4019 if (r.info.packageName.equals(dest.getPackageName()) &&
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004020 r.info.name.equals(dest.getClassName())) {
4021 finishTo = i;
4022 parent = r;
4023 foundParentInTask = true;
4024 break;
4025 }
4026 }
4027 }
4028
4029 IActivityController controller = mService.mController;
4030 if (controller != null) {
4031 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
4032 if (next != null) {
4033 // ask watcher if this is allowed
4034 boolean resumeOK = true;
4035 try {
4036 resumeOK = controller.activityResuming(next.packageName);
4037 } catch (RemoteException e) {
4038 mService.mController = null;
4039 }
4040
4041 if (!resumeOK) {
4042 return false;
4043 }
4044 }
4045 }
4046 final long origId = Binder.clearCallingIdentity();
4047 for (int i = start; i > finishTo; i--) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004048 ActivityRecord r = activities.get(i);
4049 requestFinishActivityLocked(r.appToken, resultCode, resultData, "navigate-up", true);
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004050 // Only return the supplied result for the first activity finished
4051 resultCode = Activity.RESULT_CANCELED;
4052 resultData = null;
4053 }
4054
4055 if (parent != null && foundParentInTask) {
4056 final int parentLaunchMode = parent.info.launchMode;
4057 final int destIntentFlags = destIntent.getFlags();
4058 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
4059 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
4060 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
4061 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
4062 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
4063 } else {
4064 try {
4065 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
4066 destIntent.getComponent(), 0, srec.userId);
4067 int res = startActivityLocked(srec.app.thread, destIntent,
4068 null, aInfo, parent.appToken, null,
4069 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
4070 0, null, true, null);
4071 foundParentInTask = res == ActivityManager.START_SUCCESS;
4072 } catch (RemoteException e) {
4073 foundParentInTask = false;
4074 }
4075 requestFinishActivityLocked(parent.appToken, resultCode,
4076 resultData, "navigate-up", true);
4077 }
4078 }
4079 Binder.restoreCallingIdentity(origId);
4080 return foundParentInTask;
4081 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004082 /**
4083 * Perform the common clean-up of an activity record. This is called both
4084 * as part of destroyActivityLocked() (when destroying the client-side
4085 * representation) and cleaning things up as a result of its hosting
4086 * processing going away, in which case there is no remaining client-side
4087 * state to destroy so only the cleanup here is needed.
4088 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004089 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
4090 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004091 if (mResumedActivity == r) {
4092 mResumedActivity = null;
4093 }
4094 if (mService.mFocusedActivity == r) {
4095 mService.mFocusedActivity = null;
4096 }
4097
4098 r.configDestroy = false;
4099 r.frozenBeforeDestroy = false;
4100
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004101 if (setState) {
4102 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
4103 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004104 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004105 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004106 }
4107
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004108 // Make sure this record is no longer in the pending finishes list.
4109 // This could happen, for example, if we are trimming activities
4110 // down to the max limit while they are still waiting to finish.
4111 mFinishingActivities.remove(r);
4112 mWaitingVisibleActivities.remove(r);
4113
4114 // Remove any pending results.
4115 if (r.finishing && r.pendingResults != null) {
4116 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
4117 PendingIntentRecord rec = apr.get();
4118 if (rec != null) {
4119 mService.cancelIntentSenderLocked(rec, false);
4120 }
4121 }
4122 r.pendingResults = null;
4123 }
4124
4125 if (cleanServices) {
4126 cleanUpActivityServicesLocked(r);
4127 }
4128
4129 if (mService.mPendingThumbnails.size() > 0) {
4130 // There are clients waiting to receive thumbnails so, in case
4131 // this is an activity that someone is waiting for, add it
4132 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004133 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004134 }
4135
4136 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004137 removeTimeoutsForActivityLocked(r);
4138 }
4139
4140 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004141 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004142 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004143 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004144 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004145 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004146 }
4147
Dianne Hackborn5c607432012-02-28 14:44:19 -08004148 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004149 if (VALIDATE_TASK_REPLACE) {
4150 verifyActivityRecords(true);
4151 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004152 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4153 r.makeFinishing();
4154 if (DEBUG_ADD_REMOVE) {
4155 RuntimeException here = new RuntimeException("here");
4156 here.fillInStackTrace();
4157 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004158 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004159 if (r.task != null) {
4160 removeActivity(r);
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004161 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004162
4163 { // TODO: Remove when mHistory no longer used.
4164 mHistory.remove(r);
4165 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004166 r.takeFromHistory();
Craig Mautner0247fc82013-02-28 14:32:06 -08004167 if (VALIDATE_TASK_REPLACE) {
4168 verifyActivityRecords(true);
4169 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004170 removeTimeoutsForActivityLocked(r);
Craig Mautner0247fc82013-02-28 14:32:06 -08004171 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (removed from history)");
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004172 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004173 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004174 r.app = null;
4175 mService.mWindowManager.removeAppToken(r.appToken);
4176 if (VALIDATE_TOKENS) {
4177 validateAppTokensLocked();
4178 }
4179 cleanUpActivityServicesLocked(r);
4180 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004181 }
4182
4183 /**
4184 * Perform clean-up of service connections in an activity record.
4185 */
4186 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4187 // Throw away any services that have been bound by this activity.
4188 if (r.connections != null) {
4189 Iterator<ConnectionRecord> it = r.connections.iterator();
4190 while (it.hasNext()) {
4191 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004192 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004193 }
4194 r.connections = null;
4195 }
4196 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004197
4198 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4199 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4200 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4201 mHandler.sendMessage(msg);
4202 }
4203
Dianne Hackborn28695e02011-11-02 21:59:51 -07004204 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004205 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004206 boolean activityRemoved = false;
Craig Mautnerd44711d2013-02-23 11:24:36 -08004207 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4208 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4209 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4210 final ActivityRecord r = activities.get(activityNdx);
4211 if (r.finishing) {
4212 continue;
4213 }
4214 if (r.fullscreen) {
4215 lastIsOpaque = true;
4216 }
4217 if (owner != null && r.app != owner) {
4218 continue;
4219 }
4220 if (!lastIsOpaque) {
4221 continue;
4222 }
4223 // We can destroy this one if we have its icicle saved and
4224 // it is not in the process of pausing/stopping/finishing.
4225 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4226 && r.haveState && !r.visible && r.stopped
4227 && r.state != ActivityState.DESTROYING
4228 && r.state != ActivityState.DESTROYED) {
4229 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4230 + " resumed=" + mResumedActivity
4231 + " pausing=" + mPausingActivity);
4232 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4233 activityRemoved = true;
4234 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004235 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004236 }
4237 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004238 if (activityRemoved) {
4239 resumeTopActivityLocked(null);
4240 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004241 }
4242
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004243 /**
4244 * Destroy the current CLIENT SIDE instance of an activity. This may be
4245 * called both when actually finishing an activity, or when performing
4246 * a configuration switch where we destroy the current client-side object
4247 * but then create a new client-side object for this same HistoryRecord.
4248 */
4249 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004250 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004251 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004252 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004253 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4254 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004255 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004256 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004257
4258 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004259
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004260 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004261
4262 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004263
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004264 if (hadApp) {
4265 if (removeFromApp) {
4266 int idx = r.app.activities.indexOf(r);
4267 if (idx >= 0) {
4268 r.app.activities.remove(idx);
4269 }
4270 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4271 mService.mHeavyWeightProcess = null;
4272 mService.mHandler.sendEmptyMessage(
4273 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4274 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004275 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004276 // No longer have activities, so update oom adj.
4277 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004278 }
4279 }
4280
4281 boolean skipDestroy = false;
4282
4283 try {
4284 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004285 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004286 r.configChangeFlags);
4287 } catch (Exception e) {
4288 // We can just ignore exceptions here... if the process
4289 // has crashed, our death notification will clean things
4290 // up.
4291 //Slog.w(TAG, "Exception thrown during finish", e);
4292 if (r.finishing) {
4293 removeActivityFromHistoryLocked(r);
4294 removedFromHistory = true;
4295 skipDestroy = true;
4296 }
4297 }
4298
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004299 r.nowVisible = false;
4300
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004301 // If the activity is finishing, we need to wait on removing it
4302 // from the list to give it a chance to do its cleanup. During
4303 // that time it may make calls back with its token so we need to
4304 // be able to find it on the list and so we don't want to remove
4305 // it from the list yet. Otherwise, we can just immediately put
4306 // it in the destroyed state since we are not removing it from the
4307 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004308 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004309 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4310 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004311 r.state = ActivityState.DESTROYING;
4312 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4313 msg.obj = r;
4314 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4315 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004316 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4317 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004318 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004319 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004320 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004321 }
4322 } else {
4323 // remove this record from the history.
4324 if (r.finishing) {
4325 removeActivityFromHistoryLocked(r);
4326 removedFromHistory = true;
4327 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004328 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4329 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004330 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004331 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004332 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004333 }
4334 }
4335
4336 r.configChangeFlags = 0;
4337
4338 if (!mLRUActivities.remove(r) && hadApp) {
4339 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4340 }
4341
4342 return removedFromHistory;
4343 }
4344
4345 final void activityDestroyed(IBinder token) {
4346 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004347 final long origId = Binder.clearCallingIdentity();
4348 try {
4349 ActivityRecord r = ActivityRecord.forToken(token);
4350 if (r != null) {
4351 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004352 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004353
Craig Mautnerd44711d2013-02-23 11:24:36 -08004354 if (isInStackLocked(token) != null) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004355 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004356 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004357 removeActivityFromHistoryLocked(r);
4358 }
4359 }
4360 resumeTopActivityLocked(null);
4361 } finally {
4362 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004363 }
4364 }
4365 }
4366
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004367 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4368 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004369 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004370 if (DEBUG_CLEANUP) Slog.v(
4371 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004372 + " with " + i + " entries");
4373 while (i > 0) {
4374 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004375 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004376 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004377 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004378 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004379 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004380 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004381 }
4382 }
4383 }
4384
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004385 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4386 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4387 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4388 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4389 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4390 "mWaitingVisibleActivities");
4391 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4392
4393 boolean hasVisibleActivities = false;
4394
4395 // Clean out the history list.
Craig Mautner0247fc82013-02-28 14:32:06 -08004396 int i = numActivities();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004397 if (DEBUG_CLEANUP) Slog.v(
4398 TAG, "Removing app " + app + " from history with " + i + " entries");
Craig Mautner0247fc82013-02-28 14:32:06 -08004399 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4400 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
4401 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4402 final ActivityRecord r = activities.get(activityNdx);
4403 --i;
4404 if (DEBUG_CLEANUP) Slog.v(
4405 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4406 if (r.app == app) {
4407 boolean remove;
4408 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
4409 // Don't currently have state for the activity, or
4410 // it is finishing -- always remove it.
4411 remove = true;
4412 } else if (r.launchCount > 2 &&
4413 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4414 // We have launched this activity too many times since it was
4415 // able to run, so give up and remove it.
4416 remove = true;
4417 } else {
4418 // The process may be gone, but the activity lives on!
4419 remove = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004420 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004421 if (remove) {
4422 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4423 RuntimeException here = new RuntimeException("here");
4424 here.fillInStackTrace();
4425 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4426 + ": haveState=" + r.haveState
4427 + " stateNotNeeded=" + r.stateNotNeeded
4428 + " finishing=" + r.finishing
4429 + " state=" + r.state, here);
4430 }
4431 if (!r.finishing) {
4432 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4433 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4434 r.userId, System.identityHashCode(r),
4435 r.task.taskId, r.shortComponentName,
4436 "proc died without state saved");
4437 }
4438 removeActivityFromHistoryLocked(r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004439
Craig Mautner0247fc82013-02-28 14:32:06 -08004440 } else {
4441 // We have the current state for this activity, so
4442 // it can be restarted later when needed.
4443 if (localLOGV) Slog.v(
4444 TAG, "Keeping entry, setting app to null");
4445 if (r.visible) {
4446 hasVisibleActivities = true;
4447 }
4448 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4449 + r);
4450 r.app = null;
4451 r.nowVisible = false;
4452 if (!r.haveState) {
4453 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4454 "App died, clearing saved state of " + r);
4455 r.icicle = null;
4456 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004457 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004458
Craig Mautner0247fc82013-02-28 14:32:06 -08004459 r.stack.cleanUpActivityLocked(r, true, true);
4460 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004461 }
4462 }
4463
4464 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004465 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004466
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004467 /**
4468 * Move the current home activity's task (if one exists) to the front
4469 * of the stack.
4470 */
4471 final void moveHomeToFrontLocked() {
Craig Mautner0247fc82013-02-28 14:32:06 -08004472 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
4473 final TaskRecord task = mTaskHistory.get(taskNdx);
4474 final ArrayList<ActivityRecord> activities = task.mActivities;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004475 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
4476 final ActivityRecord r = activities.get(activityNdx);
4477 if (r.isHomeActivity) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004478 moveTaskToFrontLocked(task, null, null);
4479 return;
Craig Mautner11bf9a52013-02-19 14:08:51 -08004480 }
4481 }
4482 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004483 }
4484
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004485 final void updateTransitLocked(int transit, Bundle options) {
4486 if (options != null) {
4487 ActivityRecord r = topRunningActivityLocked(null);
4488 if (r != null && r.state != ActivityState.RESUMED) {
4489 r.updateOptionsLocked(options);
4490 } else {
4491 ActivityOptions.abort(options);
4492 }
4493 }
4494 mService.mWindowManager.prepareAppTransition(transit, false);
4495 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004496
Craig Mautnercae015f2013-02-08 14:31:27 -08004497 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
Craig Mautneraab647e2013-02-28 16:31:36 -08004498 final TaskRecord task = mTaskIdToTaskRecord.get(taskId);
4499 if (mTaskHistory.contains(task)) {
4500 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4501 mUserLeaving = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004502 }
Craig Mautneraab647e2013-02-28 16:31:36 -08004503 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4504 // Caller wants the home activity moved with it. To accomplish this,
4505 // we'll just move the home task to the top first.
4506 moveHomeToFrontLocked();
4507 }
4508 moveTaskToFrontLocked(task, null, options);
4509 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08004510 }
4511 return false;
4512 }
4513
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004514 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Craig Mautner0247fc82013-02-28 14:32:06 -08004515 if (VALIDATE_TASK_REPLACE) {
4516 verifyActivityRecords(true);
4517 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004518
4519 final int task = tr.taskId;
4520 int top = mHistory.size()-1;
4521
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004522 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004523 // nothing to do!
4524 return;
4525 }
4526
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004527
4528 // Shift all activities with this task up to the top
4529 // of the stack, keeping them in the same internal order.
Craig Mautner11bf9a52013-02-19 14:08:51 -08004530 int pos = top;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004531 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004532 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004533 if (localLOGV) Slog.v(
4534 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004535 if (r.task.taskId == task) {
4536 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004537 if (DEBUG_ADD_REMOVE) {
4538 RuntimeException here = new RuntimeException("here");
4539 here.fillInStackTrace();
4540 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4541 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004542 mHistory.remove(pos);
4543 mHistory.add(top, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004544 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004545 }
4546 pos--;
4547 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08004548 //
4549 // Start new code here! Delete everything above.
4550 //
4551 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004552
Craig Mautner11bf9a52013-02-19 14:08:51 -08004553 final int numTasks = mTaskHistory.size();
4554 final int index = mTaskHistory.indexOf(tr);
4555 if (numTasks == 0 || index < 0 || index == numTasks - 1) {
4556 // nothing to do!
4557 if (reason != null &&
4558 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4559 ActivityOptions.abort(options);
4560 } else {
4561 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
4562 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004563 if (VALIDATE_TASK_REPLACE) {
4564 verifyActivityRecords(true);
4565 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08004566 return;
4567 }
4568
4569 // Shift all activities with this task up to the top
4570 // of the stack, keeping them in the same internal order.
4571 mTaskHistory.remove(tr);
4572 mTaskHistory.add(tr);
4573
4574 if (DEBUG_TRANSITION) Slog.v(TAG, "Prepare to front transition: task=" + tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004575 if (reason != null &&
4576 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004577 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004578 ActivityRecord r = topRunningActivityLocked(null);
4579 if (r != null) {
4580 mNoAnimActivities.add(r);
4581 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004582 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004583 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004584 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004585 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004586
Craig Mautner30e2d722013-02-12 11:30:16 -08004587 mService.mWindowManager.moveTaskToTop(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004588
4589 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004590 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Craig Mautner11bf9a52013-02-19 14:08:51 -08004591
4592 if (VALIDATE_TOKENS) {
4593 validateAppTokensLocked();
4594 }
4595 if (VALIDATE_TASK_REPLACE) {
4596 verifyActivityRecords(true);
4597 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004598 }
4599
4600 private final void finishTaskMoveLocked(int task) {
4601 resumeTopActivityLocked(null);
4602 }
4603
4604 /**
4605 * Worker method for rearranging history stack. Implements the function of moving all
4606 * activities for a specific task (gathering them if disjoint) into a single group at the
4607 * bottom of the stack.
4608 *
4609 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4610 * to premeptively cancel the move.
4611 *
4612 * @param task The taskId to collect and move to the bottom.
4613 * @return Returns true if the move completed, false if not.
4614 */
4615 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4616 Slog.i(TAG, "moveTaskToBack: " + task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004617
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004618 // If we have a watcher, preflight the move before committing to it. First check
4619 // for *other* available tasks, but if none are available, then try again allowing the
4620 // current task to be selected.
4621 if (mMainStack && mService.mController != null) {
4622 ActivityRecord next = topRunningActivityLocked(null, task);
4623 if (next == null) {
4624 next = topRunningActivityLocked(null, 0);
4625 }
4626 if (next != null) {
4627 // ask watcher if this is allowed
4628 boolean moveOK = true;
4629 try {
4630 moveOK = mService.mController.activityResuming(next.packageName);
4631 } catch (RemoteException e) {
4632 mService.mController = null;
4633 }
4634 if (!moveOK) {
4635 return false;
4636 }
4637 }
4638 }
Craig Mautner0247fc82013-02-28 14:32:06 -08004639 if (VALIDATE_TASK_REPLACE) {
4640 verifyActivityRecords(true);
4641 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004642
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004643 if (DEBUG_TRANSITION) Slog.v(TAG,
4644 "Prepare to back transition: task=" + task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004645
Craig Mautner11bf9a52013-02-19 14:08:51 -08004646 final TaskRecord tr = mTaskIdToTaskRecord.get(task);
4647 mTaskHistory.remove(tr);
4648 mTaskHistory.add(0, tr);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004649
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004650 // BEGIN REGION TO REMOVE.
4651 final int N = mHistory.size();
4652 int bottom = 0;
4653 int pos = 0;
4654
4655 // Shift all activities with this task down to the bottom
4656 // of the stack, keeping them in the same internal order.
4657 while (pos < N) {
4658 ActivityRecord r = mHistory.get(pos);
4659 if (localLOGV) Slog.v(
4660 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4661 if (r.task.taskId == task) {
4662 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
4663 if (DEBUG_ADD_REMOVE) {
4664 RuntimeException here = new RuntimeException("here");
4665 here.fillInStackTrace();
4666 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4667 + bottom, here);
4668 }
4669 mHistory.remove(pos);
4670 mHistory.add(bottom, r);
4671 bottom++;
4672 }
4673 pos++;
4674 }
4675 if (VALIDATE_TASK_REPLACE) {
4676 verifyActivityRecords(true);
4677 }
4678 // END REGION TO REMOVE
4679
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004680 if (reason != null &&
4681 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Craig Mautner11bf9a52013-02-19 14:08:51 -08004682 mService.mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004683 ActivityRecord r = topRunningActivityLocked(null);
4684 if (r != null) {
4685 mNoAnimActivities.add(r);
4686 }
4687 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004688 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004689 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004690 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004691 mService.mWindowManager.moveTaskToBottom(task);
Craig Mautnerb44de0d2013-02-21 20:00:58 -08004692
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004693 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004694 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004695 }
4696
4697 finishTaskMoveLocked(task);
4698 return true;
4699 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004700
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004701 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
Craig Mautner16030772013-02-26 16:05:47 -08004702 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004703 ActivityRecord resumed = mResumedActivity;
4704 if (resumed != null && resumed.thumbHolder == tr) {
4705 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004706 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004707 if (info.mainThumbnail == null) {
4708 info.mainThumbnail = tr.lastThumbnail;
4709 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004710 return info;
4711 }
4712
Dianne Hackborn15491c62012-09-19 10:59:14 -07004713 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4714 ActivityRecord resumed = mResumedActivity;
4715 if (resumed != null && resumed.task == tr) {
4716 // This task is the current resumed task, we just need to take
4717 // a screenshot of it and return that.
4718 return resumed.stack.screenshotActivities(resumed);
4719 }
4720 // Return the information about the task, to figure out the top
4721 // thumbnail to return.
Craig Mautner16030772013-02-26 16:05:47 -08004722 TaskAccessInfo info = getTaskAccessInfoLocked(tr, true);
Dianne Hackborn15491c62012-09-19 10:59:14 -07004723 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004724 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004725 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004726 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004727 }
4728
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004729 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4730 boolean taskRequired) {
Craig Mautner16030772013-02-26 16:05:47 -08004731 final TaskRecord task = mTaskIdToTaskRecord.get(taskId);
4732 TaskAccessInfo info = getTaskAccessInfoLocked(task, false);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004733 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004734 if (taskRequired) {
4735 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4736 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004737 return null;
4738 }
4739
4740 if (subTaskIndex < 0) {
4741 // Just remove the entire task.
Craig Mautner16030772013-02-26 16:05:47 -08004742 performClearTaskAtIndexLocked(task, info.rootIndex);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004743 return info.root;
4744 }
4745
4746 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004747 if (taskRequired) {
4748 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4749 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004750 return null;
4751 }
4752
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004753 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004754 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
Craig Mautner16030772013-02-26 16:05:47 -08004755 performClearTaskAtIndexLocked(task, subtask.index);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004756 return subtask.activity;
4757 }
4758
Craig Mautner16030772013-02-26 16:05:47 -08004759 public TaskAccessInfo getTaskAccessInfoLocked(TaskRecord task, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004760 final TaskAccessInfo thumbs = new TaskAccessInfo();
4761 // How many different sub-thumbnails?
Craig Mautner16030772013-02-26 16:05:47 -08004762 final ArrayList<ActivityRecord> activities = task.mActivities;
4763 final int NA = activities.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004764 int j = 0;
4765 ThumbnailHolder holder = null;
4766 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004767 ActivityRecord ar = activities.get(j);
4768 if (!ar.finishing) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004769 thumbs.root = ar;
4770 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004771 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004772 if (holder != null) {
4773 thumbs.mainThumbnail = holder.lastThumbnail;
4774 }
4775 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004776 break;
4777 }
4778 j++;
4779 }
4780
4781 if (j >= NA) {
4782 return thumbs;
4783 }
4784
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004785 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4786 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004787 while (j < NA) {
Craig Mautner16030772013-02-26 16:05:47 -08004788 ActivityRecord ar = activities.get(j);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004789 j++;
4790 if (ar.finishing) {
4791 continue;
4792 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004793 if (ar.thumbHolder != holder && holder != null) {
4794 thumbs.numSubThumbbails++;
4795 holder = ar.thumbHolder;
4796 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004797 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004798 sub.activity = ar;
4799 sub.index = j-1;
4800 subtasks.add(sub);
4801 }
4802 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004803 if (thumbs.numSubThumbbails > 0) {
4804 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004805 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004806 public Bitmap getThumbnail(int index) {
4807 if (index < 0 || index >= thumbs.subtasks.size()) {
4808 return null;
4809 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004810 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4811 ActivityRecord resumed = mResumedActivity;
4812 if (resumed != null && resumed.thumbHolder == sub.holder) {
4813 return resumed.stack.screenshotActivities(resumed);
4814 }
4815 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004816 }
4817 };
4818 }
4819 return thumbs;
4820 }
4821
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004822 private final void logStartActivity(int tag, ActivityRecord r,
4823 TaskRecord task) {
4824 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004825 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004826 r.shortComponentName, r.intent.getAction(),
4827 r.intent.getType(), r.intent.getDataString(),
4828 r.intent.getFlags());
4829 }
4830
4831 /**
4832 * Make sure the given activity matches the current configuration. Returns
4833 * false if the activity had to be destroyed. Returns true if the
4834 * configuration is the same, or the activity will remain running as-is
4835 * for whatever reason. Ensures the HistoryRecord is updated with the
4836 * correct configuration and all other bookkeeping is handled.
4837 */
4838 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4839 int globalChanges) {
4840 if (mConfigWillChange) {
4841 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4842 "Skipping config check (will change): " + r);
4843 return true;
4844 }
4845
4846 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4847 "Ensuring correct configuration: " + r);
4848
4849 // Short circuit: if the two configurations are the exact same
4850 // object (the common case), then there is nothing to do.
4851 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004852 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004853 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4854 "Configuration unchanged in " + r);
4855 return true;
4856 }
4857
4858 // We don't worry about activities that are finishing.
4859 if (r.finishing) {
4860 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4861 "Configuration doesn't matter in finishing " + r);
4862 r.stopFreezingScreenLocked(false);
4863 return true;
4864 }
4865
4866 // Okay we now are going to make this activity have the new config.
4867 // But then we need to figure out how it needs to deal with that.
4868 Configuration oldConfig = r.configuration;
4869 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004870
4871 // Determine what has changed. May be nothing, if this is a config
4872 // that has come back from the app after going idle. In that case
4873 // we just want to leave the official config object now in the
4874 // activity and do nothing else.
4875 final int changes = oldConfig.diff(newConfig);
4876 if (changes == 0 && !r.forceNewConfig) {
4877 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4878 "Configuration no differences in " + r);
4879 return true;
4880 }
4881
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004882 // If the activity isn't currently running, just leave the new
4883 // configuration and it will pick that up next time it starts.
4884 if (r.app == null || r.app.thread == null) {
4885 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4886 "Configuration doesn't matter not running " + r);
4887 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004888 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004889 return true;
4890 }
4891
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004892 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004893 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4894 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4895 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004896 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004897 + ", newConfig=" + newConfig);
4898 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004899 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004900 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4901 r.configChangeFlags |= changes;
4902 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004903 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004904 if (r.app == null || r.app.thread == null) {
4905 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004906 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004907 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004908 } else if (r.state == ActivityState.PAUSING) {
4909 // A little annoying: we are waiting for this activity to
4910 // finish pausing. Let's not do anything now, but just
4911 // flag that it needs to be restarted when done pausing.
4912 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004913 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004914 r.configDestroy = true;
4915 return true;
4916 } else if (r.state == ActivityState.RESUMED) {
4917 // Try to optimize this case: the configuration is changing
4918 // and we need to restart the top, resumed activity.
4919 // Instead of doing the normal handshaking, just say
4920 // "restart!".
4921 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004922 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004923 relaunchActivityLocked(r, r.configChangeFlags, true);
4924 r.configChangeFlags = 0;
4925 } else {
4926 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004927 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004928 relaunchActivityLocked(r, r.configChangeFlags, false);
4929 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004930 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004931
4932 // All done... tell the caller we weren't able to keep this
4933 // activity around.
4934 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004935 }
4936
4937 // Default case: the activity can handle this new configuration, so
4938 // hand it over. Note that we don't need to give it the new
4939 // configuration, since we always send configuration changes to all
4940 // process when they happen so it can just use whatever configuration
4941 // it last got.
4942 if (r.app != null && r.app.thread != null) {
4943 try {
4944 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004945 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004946 } catch (RemoteException e) {
4947 // If process died, whatever.
4948 }
4949 }
4950 r.stopFreezingScreenLocked(false);
4951
4952 return true;
4953 }
4954
4955 private final boolean relaunchActivityLocked(ActivityRecord r,
4956 int changes, boolean andResume) {
4957 List<ResultInfo> results = null;
4958 List<Intent> newIntents = null;
4959 if (andResume) {
4960 results = r.results;
4961 newIntents = r.newIntents;
4962 }
4963 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4964 + " with results=" + results + " newIntents=" + newIntents
4965 + " andResume=" + andResume);
4966 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004967 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004968 r.task.taskId, r.shortComponentName);
4969
4970 r.startFreezingScreenLocked(r.app, 0);
4971
4972 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004973 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4974 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4975 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004976 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004977 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004978 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004979 // Note: don't need to call pauseIfSleepingLocked() here, because
4980 // the caller will only pass in 'andResume' if this activity is
4981 // currently resumed, which implies we aren't sleeping.
4982 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004983 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004984 }
4985
4986 if (andResume) {
4987 r.results = null;
4988 r.newIntents = null;
4989 if (mMainStack) {
4990 mService.reportResumedActivityLocked(r);
4991 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004992 r.state = ActivityState.RESUMED;
4993 } else {
4994 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4995 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004996 }
4997
4998 return true;
4999 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07005000
5001 public void dismissKeyguardOnNextActivityLocked() {
5002 mDismissKeyguardOnNextActivity = true;
5003 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005004
5005 boolean willActivityBeVisibleLocked(IBinder token) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08005006 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5007 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
5008 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
5009 final ActivityRecord r = activities.get(activityNdx);
5010 if (r.appToken == token) {
5011 return true;
5012 }
5013 if (r.fullscreen && !r.finishing) {
5014 return false;
5015 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005016 }
5017 }
5018 return true;
5019 }
5020
5021 void closeSystemDialogsLocked() {
Craig Mautnerd44711d2013-02-23 11:24:36 -08005022 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5023 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
5024 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
5025 final ActivityRecord r = activities.get(activityNdx);
5026 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
5027 r.stack.finishActivityLocked(r, Activity.RESULT_CANCELED,
5028 null, "close-sys", true);
5029 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005030 }
5031 }
5032 }
5033
5034 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
5035 boolean didSomething = false;
5036 TaskRecord lastTask = null;
Craig Mautner56f52db2013-02-25 10:03:01 -08005037 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5038 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
5039 int numActivities = activities.size();
5040 for (int activityNdx = 0; activityNdx < numActivities; ++activityNdx) {
5041 ActivityRecord r = activities.get(activityNdx);
5042 final boolean samePackage = r.packageName.equals(name)
5043 || (name == null && r.userId == userId);
5044 if ((userId == UserHandle.USER_ALL || r.userId == userId)
5045 && (samePackage || r.task == lastTask)
5046 && (r.app == null || evenPersistent || !r.app.persistent)) {
5047 if (!doit) {
5048 if (r.finishing) {
5049 // If this activity is just finishing, then it is not
5050 // interesting as far as something to stop.
5051 continue;
5052 }
5053 return true;
Craig Mautnercae015f2013-02-08 14:31:27 -08005054 }
Craig Mautner56f52db2013-02-25 10:03:01 -08005055 didSomething = true;
5056 Slog.i(TAG, " Force finishing activity " + r);
5057 if (samePackage) {
5058 if (r.app != null) {
5059 r.app.removed = true;
5060 }
5061 r.app = null;
Craig Mautnercae015f2013-02-08 14:31:27 -08005062 }
Craig Mautner56f52db2013-02-25 10:03:01 -08005063 lastTask = r.task;
5064 r.stack.finishActivityLocked(r, Activity.RESULT_CANCELED, null, "force-stop",
5065 true);
Craig Mautnercae015f2013-02-08 14:31:27 -08005066 }
5067 }
5068 }
5069 return didSomething;
5070 }
5071
5072 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
Craig Mautneraab647e2013-02-28 16:31:36 -08005073 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
Craig Mautnercae015f2013-02-08 14:31:27 -08005074 ActivityRecord topRecord = null;
Craig Mautneraab647e2013-02-28 16:31:36 -08005075 for (int taskNdx = mTaskHistory.size() - 1; maxNum > 0 && taskNdx >= 0;
5076 --maxNum, --taskNdx) {
5077 final TaskRecord task = mTaskHistory.get(taskNdx);
5078 ActivityRecord r = null;
5079 ActivityRecord top = null;
5080 int numActivities = 0;
5081 int numRunning = 0;
5082 final ArrayList<ActivityRecord> activities = task.mActivities;
5083 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
5084 r = activities.get(activityNdx);
Craig Mautnercae015f2013-02-08 14:31:27 -08005085
Craig Mautneraab647e2013-02-28 16:31:36 -08005086 // Initialize state for next task if needed.
5087 if (top == null || (top.state == ActivityState.INITIALIZING)) {
5088 top = r;
5089 numActivities = numRunning = 0;
Craig Mautnercae015f2013-02-08 14:31:27 -08005090 }
Craig Mautneraab647e2013-02-28 16:31:36 -08005091
5092 // Add 'r' into the current task.
5093 numActivities++;
5094 if (r.app != null && r.app.thread != null) {
5095 numRunning++;
5096 }
5097
5098 if (localLOGV) Slog.v(
5099 TAG, r.intent.getComponent().flattenToShortString()
5100 + ": task=" + r.task);
5101 }
5102
5103 RunningTaskInfo ci = new RunningTaskInfo();
5104 ci.id = task.taskId;
5105 ci.baseActivity = r.intent.getComponent();
5106 ci.topActivity = top.intent.getComponent();
5107 if (top.thumbHolder != null) {
5108 ci.description = top.thumbHolder.lastDescription;
5109 }
5110 ci.numActivities = numActivities;
5111 ci.numRunning = numRunning;
5112 //System.out.println(
5113 // "#" + maxNum + ": " + " descr=" + ci.description);
5114 if (receiver != null) {
5115 if (localLOGV) Slog.v(
5116 TAG, "State=" + top.state + "Idle=" + top.idle
5117 + " app=" + top.app
5118 + " thr=" + (top.app != null ? top.app.thread : null));
5119 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
5120 if (top.idle && top.app != null && top.app.thread != null) {
5121 topRecord = top;
5122 } else {
5123 top.thumbnailNeeded = true;
Craig Mautnercae015f2013-02-08 14:31:27 -08005124 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005125 }
Craig Mautneraab647e2013-02-28 16:31:36 -08005126 pending.pendingRecords.add(top);
Craig Mautnercae015f2013-02-08 14:31:27 -08005127 }
Craig Mautneraab647e2013-02-28 16:31:36 -08005128 list.add(ci);
Craig Mautnercae015f2013-02-08 14:31:27 -08005129 }
5130 return topRecord;
5131 }
5132
5133 public void unhandledBackLocked() {
Craig Mautneraab647e2013-02-28 16:31:36 -08005134 final int top = mTaskHistory.size() - 1;
Craig Mautnercae015f2013-02-08 14:31:27 -08005135 if (DEBUG_SWITCH) Slog.d(
5136 TAG, "Performing unhandledBack(): top activity at " + top);
Craig Mautneraab647e2013-02-28 16:31:36 -08005137 if (top >= 0) {
5138 final ArrayList<ActivityRecord> activities = mTaskHistory.get(top).mActivities;
5139 int activityTop = activities.size() - 1;
5140 if (activityTop > 0) {
5141 finishActivityLocked(activities.get(activityTop), Activity.RESULT_CANCELED, null,
5142 "unhandled-back", true);
5143 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005144 }
5145 }
5146
5147 void handleAppCrashLocked(ProcessRecord app) {
Craig Mautnerd44711d2013-02-23 11:24:36 -08005148 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5149 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
5150 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
5151 final ActivityRecord r = activities.get(activityNdx);
5152 if (r.app == app) {
5153 Slog.w(TAG, " Force finishing activity "
5154 + r.intent.getComponent().flattenToShortString());
5155 r.stack.finishActivityLocked(r, Activity.RESULT_CANCELED, null, "crashed",
5156 false);
5157 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005158 }
5159 }
5160 }
5161
5162 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
5163 boolean dumpClient, String dumpPackage) {
Craig Mautneraab647e2013-02-28 16:31:36 -08005164 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5165 final TaskRecord task = mTaskHistory.get(taskNdx);
5166 pw.print(" Task "); pw.print(taskNdx); pw.print(": id #"); pw.println(task.taskId);
5167 ActivityManagerService.dumpHistoryList(fd, pw, mTaskHistory.get(taskNdx).mActivities,
5168 " ", "Hist", true, !dumpAll, dumpClient, dumpPackage);
5169 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005170 }
5171
5172 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
5173 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
5174
5175 if ("all".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08005176 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5177 activities.addAll(mTaskHistory.get(taskNdx).mActivities);
Craig Mautnercae015f2013-02-08 14:31:27 -08005178 }
5179 } else if ("top".equals(name)) {
Craig Mautneraab647e2013-02-28 16:31:36 -08005180 final int top = mTaskHistory.size() - 1;
5181 if (top >= 0) {
5182 final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities;
5183 int listTop = list.size() - 1;
5184 if (listTop >= 0) {
5185 activities.add(list.get(listTop));
5186 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005187 }
5188 } else {
5189 ItemMatcher matcher = new ItemMatcher();
5190 matcher.build(name);
5191
Craig Mautneraab647e2013-02-28 16:31:36 -08005192 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5193 for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) {
5194 if (matcher.match(r1, r1.intent.getComponent())) {
5195 activities.add(r1);
5196 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005197 }
5198 }
5199 }
5200
5201 return activities;
5202 }
5203
5204 ActivityRecord restartPackage(String packageName) {
5205 ActivityRecord starting = topRunningActivityLocked(null);
5206
5207 // All activities that came from the package must be
5208 // restarted as if there was a config change.
Craig Mautneraab647e2013-02-28 16:31:36 -08005209 for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
5210 final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities;
5211 for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
5212 final ActivityRecord a = activities.get(activityNdx);
5213 if (a.info.packageName.equals(packageName)) {
5214 a.forceNewConfig = true;
5215 if (starting != null && a == starting && a.visible) {
5216 a.startFreezingScreenLocked(starting.app,
5217 ActivityInfo.CONFIG_SCREEN_LAYOUT);
5218 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005219 }
5220 }
5221 }
5222
5223 return starting;
5224 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005225
Craig Mautner11bf9a52013-02-19 14:08:51 -08005226 void rebuildTaskHistory() {
5227 mTaskHistory.clear();
5228 final int numActivities = mHistory.size();
5229 TaskRecord task = null;
5230 for (int i = 0; i < numActivities; ++i) {
5231 final ActivityRecord r = mHistory.get(i);
5232 if (r.task != task) {
5233 task = r.task;
5234 task.mActivities.clear();
5235 mTaskHistory.add(task);
5236 }
5237 task.mActivities.add(r);
5238 }
5239 }
5240
5241 boolean verifyActivityRecords(boolean rebuild) {
5242 final int numHistory = mHistory.size();
5243 int historyNdx = 0;
5244
5245 final int numTasks = mTaskHistory.size();
5246 int taskNdx;
5247 for (taskNdx = historyNdx = 0; taskNdx < numTasks; ++taskNdx) {
5248 final TaskRecord task = mTaskHistory.get(taskNdx);
5249 final ArrayList<ActivityRecord> activities = task.mActivities;
5250 final int numActivities = activities.size();
5251 int activityNdx;
5252 for (activityNdx = 0;
5253 activityNdx < numActivities && historyNdx < numHistory;
5254 ++activityNdx, ++historyNdx) {
5255 ActivityRecord r1 = mHistory.get(historyNdx);
5256 ActivityRecord r2 = activities.get(activityNdx);
5257 if (r1 != r2) {
5258 break;
5259 }
5260 }
5261 if (activityNdx != numActivities) {
5262 // either a mismatch or mHistory ran out before mTaskHistory.
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005263 break;
5264 }
5265 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08005266 if (taskNdx != numTasks || historyNdx != numHistory) {
5267 logHistories("verifyActivityRecords", rebuild);
5268 return true;
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005269 }
Craig Mautner11bf9a52013-02-19 14:08:51 -08005270 return false;
5271 }
5272
5273 private void logHistories(String caller, boolean rebuild) {
5274 Slog.w(TAG, "Mismatch! " + caller + " mHistory=" + mHistory);
5275 ArrayList<ArrayList<ActivityRecord>> nestedRecords =
5276 new ArrayList<ArrayList<ActivityRecord>>();
5277 for (TaskRecord task : mTaskHistory) {
5278 nestedRecords.add(task.mActivities);
5279 }
5280 Slog.w(TAG, "Mismatch! " + caller + " mTaskHistory" + nestedRecords);
5281 Slog.w(TAG, "Mismatch! " + caller + " lastHistoryModifier=" + mLastHistoryModifier
5282 + " Caller=" + Debug.getCallers(4));
5283 if (rebuild) {
5284 rebuildTaskHistory();
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005285 }
5286 }
5287
Craig Mautner0247fc82013-02-28 14:32:06 -08005288 private void removeActivity(ActivityRecord r) {
5289 final TaskRecord task = r.task;
5290 if (task.removeActivity(r)) {
5291 if (DEBUG_ADD_REMOVE) Slog.i(TAG, "removeActivity: Removing from history, task="
5292 + task);
5293 mTaskHistory.remove(task);
5294 mTaskIdToTaskRecord.delete(task.taskId);
5295 }
5296 }
5297
5298 private void setTask(ActivityRecord r, TaskRecord newTask, ThumbnailHolder newThumbHolder,
5299 boolean isRoot) {
5300 if (r.task != null) {
5301 removeActivity(r);
5302 }
5303 r.setTask(newTask, newThumbHolder, isRoot);
5304 }
5305
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005306 private TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
5307 boolean toTop) {
5308 TaskRecord oldTask = mTaskIdToTaskRecord.get(taskId);
5309 if (oldTask != null) {
5310 Slog.w(TAG, "createTaskRecord: Reusing taskId=" + taskId + " without removing");
5311 mTaskHistory.remove(oldTask);
5312 }
5313 TaskRecord task = new TaskRecord(taskId, info, intent);
5314 mTaskIdToTaskRecord.put(taskId, task);
5315 if (toTop) {
5316 mTaskHistory.add(task);
5317 } else {
5318 mTaskHistory.add(0, task);
5319 }
5320 return task;
5321 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005322}