blob: a18a0d1c35f890fedec8f56f666356ef05bf14a9 [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 Mautnercae015f2013-02-08 14:31:27 -080024import com.android.server.am.ActivityManagerService.ItemMatcher;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070025import com.android.server.am.ActivityManagerService.PendingActivityLaunch;
Craig Mautner4b71aa12012-12-27 17:20:01 -080026import com.android.server.wm.AppTransition;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080027import com.android.server.wm.TaskGroup;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070028
29import android.app.Activity;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070030import android.app.ActivityManager;
Dianne Hackborn7a2195c2012-03-19 17:38:00 -070031import android.app.ActivityOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070032import android.app.AppGlobals;
Craig Mautner05d6272ba2013-02-11 09:39:27 -080033import android.app.IActivityController;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070034import android.app.IActivityManager;
Craig Mautnercae015f2013-02-08 14:31:27 -080035import android.app.IThumbnailReceiver;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070036import android.app.IThumbnailRetriever;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070037import android.app.IApplicationThread;
38import android.app.PendingIntent;
39import android.app.ResultInfo;
Craig Mautnercae015f2013-02-08 14:31:27 -080040import android.app.ActivityManager.RunningTaskInfo;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070041import android.app.IActivityManager.WaitResult;
42import android.content.ComponentName;
43import android.content.Context;
44import android.content.IIntentSender;
45import android.content.Intent;
46import android.content.IntentSender;
47import android.content.pm.ActivityInfo;
48import android.content.pm.ApplicationInfo;
49import android.content.pm.PackageManager;
50import android.content.pm.ResolveInfo;
51import android.content.res.Configuration;
Dianne Hackborn0aae2d42010-12-07 23:51:29 -080052import android.content.res.Resources;
53import android.graphics.Bitmap;
Craig Mautnerb12428a2012-12-20 16:07:06 -080054import android.graphics.Bitmap.Config;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070055import android.os.Binder;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070056import android.os.Bundle;
Craig Mautner5d9c7be2013-02-15 14:02:56 -080057import android.os.Debug;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070058import android.os.Handler;
59import android.os.IBinder;
Zoran Marcetaf958b322012-08-09 20:27:12 +090060import android.os.Looper;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070061import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070062import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070063import android.os.PowerManager;
64import android.os.RemoteException;
65import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070066import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070067import android.util.EventLog;
68import android.util.Log;
69import android.util.Slog;
Craig Mautner5d9c7be2013-02-15 14:02:56 -080070import android.util.SparseArray;
Craig Mautner59c00972012-07-30 12:10:24 -070071import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070072
Craig Mautnercae015f2013-02-08 14:31:27 -080073import java.io.FileDescriptor;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070074import java.io.IOException;
Craig Mautnercae015f2013-02-08 14:31:27 -080075import java.io.PrintWriter;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070076import java.lang.ref.WeakReference;
77import java.util.ArrayList;
78import java.util.Iterator;
79import java.util.List;
Craig Mautner5d9c7be2013-02-15 14:02:56 -080080import java.util.NoSuchElementException;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070081
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;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070097
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;
132
133 // 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;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700136
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;
140
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
145 static final boolean FORWARD_ITERATOR = false;
146 static final boolean REVERSE_ITERATOR = true;
147
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700148 enum ActivityState {
149 INITIALIZING,
150 RESUMED,
151 PAUSING,
152 PAUSED,
153 STOPPING,
154 STOPPED,
155 FINISHING,
156 DESTROYING,
157 DESTROYED
158 }
159
160 final ActivityManagerService mService;
161 final boolean mMainStack;
162
163 final Context mContext;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800164
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700165 /**
166 * The back history of all previous (and possibly still
Craig Mautnercae015f2013-02-08 14:31:27 -0800167 * running) activities. It contains #ActivityRecord objects.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700168 */
Craig Mautnercae015f2013-02-08 14:31:27 -0800169 private final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800170
171 /**
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800172 * The back history of all previous (and possibly still
173 * running) activities. It contains #TaskRecord objects.
174 */
175 private ArrayList<TaskRecord> mTaskHistory = new ArrayList<TaskRecord>();
176
177 /**
178 * Mapping from taskId to TaskRecord
179 */
180 private SparseArray<TaskRecord> mTaskIdToTaskRecord = new SparseArray<TaskRecord>();
181
182 /**
Dianne Hackbornbe707852011-11-11 14:32:10 -0800183 * Used for validating app tokens with window manager.
184 */
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800185 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800186
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700187 /**
188 * List of running activities, sorted by recent usage.
189 * The first entry in the list is the least recently used.
190 * It contains HistoryRecord objects.
191 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700192 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700193
194 /**
195 * List of activities that are waiting for a new activity
196 * to become visible before completing whatever operation they are
197 * supposed to do.
198 */
199 final ArrayList<ActivityRecord> mWaitingVisibleActivities
200 = new ArrayList<ActivityRecord>();
201
202 /**
203 * List of activities that are ready to be stopped, but waiting
204 * for the next activity to settle down before doing so. It contains
205 * HistoryRecord objects.
206 */
207 final ArrayList<ActivityRecord> mStoppingActivities
208 = new ArrayList<ActivityRecord>();
209
210 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800211 * List of activities that are in the process of going to sleep.
212 */
213 final ArrayList<ActivityRecord> mGoingToSleepActivities
214 = new ArrayList<ActivityRecord>();
215
216 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700217 * Animations that for the current transition have requested not to
218 * be considered for the transition animation.
219 */
220 final ArrayList<ActivityRecord> mNoAnimActivities
221 = new ArrayList<ActivityRecord>();
222
223 /**
224 * List of activities that are ready to be finished, but waiting
225 * for the previous activity to settle down before doing so. It contains
226 * HistoryRecord objects.
227 */
228 final ArrayList<ActivityRecord> mFinishingActivities
229 = new ArrayList<ActivityRecord>();
230
231 /**
232 * List of people waiting to find out about the next launched activity.
233 */
234 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
235 = new ArrayList<IActivityManager.WaitResult>();
236
237 /**
238 * List of people waiting to find out about the next visible activity.
239 */
240 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
241 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700242
243 final ArrayList<UserStartedState> mStartingUsers
244 = new ArrayList<UserStartedState>();
245
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700246 /**
247 * Set when the system is going to sleep, until we have
248 * successfully paused the current activity and released our wake lock.
249 * At that point the system is allowed to actually sleep.
250 */
251 final PowerManager.WakeLock mGoingToSleep;
252
253 /**
254 * We don't want to allow the device to go to sleep while in the process
255 * of launching an activity. This is primarily to allow alarm intent
256 * receivers to launch an activity and get that to run before the device
257 * goes back to sleep.
258 */
259 final PowerManager.WakeLock mLaunchingActivity;
260
261 /**
262 * When we are in the process of pausing an activity, before starting the
263 * next one, this variable holds the activity that is currently being paused.
264 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800265 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700266
267 /**
268 * This is the last activity that we put into the paused state. This is
269 * used to determine if we need to do an activity transition while sleeping,
270 * when we normally hold the top activity paused.
271 */
272 ActivityRecord mLastPausedActivity = null;
273
274 /**
275 * Current activity that is resumed, or null if there is none.
276 */
277 ActivityRecord mResumedActivity = null;
278
279 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700280 * This is the last activity that has been started. It is only used to
281 * identify when multiple activities are started at once so that the user
282 * can be warned they may not be in the activity they think they are.
283 */
284 ActivityRecord mLastStartedActivity = null;
285
286 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700287 * Set when we know we are going to be calling updateConfiguration()
288 * soon, so want to skip intermediate config checks.
289 */
290 boolean mConfigWillChange;
291
292 /**
293 * Set to indicate whether to issue an onUserLeaving callback when a
294 * newly launched activity is being brought in front of us.
295 */
296 boolean mUserLeaving = false;
297
298 long mInitialStartTime = 0;
299
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800300 /**
301 * Set when we have taken too long waiting to go to sleep.
302 */
303 boolean mSleepTimeout = false;
304
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700305 /**
306 * Dismiss the keyguard after the next activity is displayed?
307 */
308 boolean mDismissKeyguardOnNextActivity = false;
309
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800310 /** So we don't have to keep constructing a new object for utility non-nested use. */
311 final ActivityIterator mTmpActivityIterator = new ActivityIterator(FORWARD_ITERATOR, true);
312
313 /** So we don't have to keep constructing a new object for utility non-nested use. */
314 final TaskIterator mTmpTaskIterator = new TaskIterator();
315
Craig Mautnerb12428a2012-12-20 16:07:06 -0800316 /**
317 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
318 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
319 */
320 private ActivityRecord mLastScreenshotActivity = null;
321 private Bitmap mLastScreenshotBitmap = null;
322
Craig Mautnercae015f2013-02-08 14:31:27 -0800323 /**
324 * List of ActivityRecord objects that have been finished and must
325 * still report back to a pending thumbnail receiver.
326 */
327 private final ArrayList<ActivityRecord> mCancelledThumbnails = new ArrayList<ActivityRecord>();
328
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800329 int mThumbnailWidth = -1;
330 int mThumbnailHeight = -1;
331
Amith Yamasani742a6712011-05-04 14:49:28 -0700332 private int mCurrentUser;
333
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800334 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
335 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
336 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
337 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
338 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
339 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
340 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700341 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700342 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700343 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
344
345 static class ScheduleDestroyArgs {
346 final ProcessRecord mOwner;
347 final boolean mOomAdj;
348 final String mReason;
349 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
350 mOwner = owner;
351 mOomAdj = oomAdj;
352 mReason = reason;
353 }
354 }
355
Zoran Marcetaf958b322012-08-09 20:27:12 +0900356 final Handler mHandler;
357
358 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700359 //public Handler() {
360 // if (localLOGV) Slog.v(TAG, "Handler started!");
361 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900362 public ActivityStackHandler(Looper looper) {
363 super(looper);
364 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700365
Zoran Marcetaf958b322012-08-09 20:27:12 +0900366 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 public void handleMessage(Message msg) {
368 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800369 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700370 synchronized (mService) {
371 if (mService.isSleeping()) {
372 Slog.w(TAG, "Sleep timeout! Sleeping now.");
373 mSleepTimeout = true;
374 checkReadyForSleepLocked();
375 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800376 }
377 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700378 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800379 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700380 // We don't at this point know if the activity is fullscreen,
381 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800382 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700383 synchronized (mService) {
384 if (r.app != null) {
385 mService.logAppTooSlow(r.app, r.pauseTime,
386 "pausing " + r);
387 }
388 }
389
Dianne Hackbornbe707852011-11-11 14:32:10 -0800390 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700391 } break;
392 case IDLE_TIMEOUT_MSG: {
393 if (mService.mDidDexOpt) {
394 mService.mDidDexOpt = false;
395 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
396 nmsg.obj = msg.obj;
397 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
398 return;
399 }
400 // We don't at this point know if the activity is fullscreen,
401 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800402 ActivityRecord r = (ActivityRecord)msg.obj;
403 Slog.w(TAG, "Activity idle timeout for " + r);
404 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700405 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700406 case LAUNCH_TICK_MSG: {
407 ActivityRecord r = (ActivityRecord)msg.obj;
408 synchronized (mService) {
409 if (r.continueLaunchTickingLocked()) {
410 mService.logAppTooSlow(r.app, r.launchTickTime,
411 "launching " + r);
412 }
413 }
414 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700415 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800416 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700417 // We don't at this point know if the activity is fullscreen,
418 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800419 Slog.w(TAG, "Activity destroy timeout for " + r);
420 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700421 } break;
422 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800423 ActivityRecord r = (ActivityRecord)msg.obj;
424 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700425 } break;
426 case LAUNCH_TIMEOUT_MSG: {
427 if (mService.mDidDexOpt) {
428 mService.mDidDexOpt = false;
429 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
430 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
431 return;
432 }
433 synchronized (mService) {
434 if (mLaunchingActivity.isHeld()) {
435 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
436 mLaunchingActivity.release();
437 }
438 }
439 } break;
440 case RESUME_TOP_ACTIVITY_MSG: {
441 synchronized (mService) {
442 resumeTopActivityLocked(null);
443 }
444 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700445 case STOP_TIMEOUT_MSG: {
446 ActivityRecord r = (ActivityRecord)msg.obj;
447 // We don't at this point know if the activity is fullscreen,
448 // so we need to be conservative and assume it isn't.
449 Slog.w(TAG, "Activity stop timeout for " + r);
450 synchronized (mService) {
451 if (r.isInHistory()) {
452 activityStoppedLocked(r, null, null, null);
453 }
454 }
455 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700456 case DESTROY_ACTIVITIES_MSG: {
457 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
458 synchronized (mService) {
459 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
460 }
461 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700462 }
463 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800464 }
465
Zoran Marcetaf958b322012-08-09 20:27:12 +0900466 ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper) {
467 mHandler = new ActivityStackHandler(looper);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700468 mService = service;
469 mContext = context;
470 mMainStack = mainStack;
471 PowerManager pm =
472 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
473 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
474 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
475 mLaunchingActivity.setReferenceCounted(false);
476 }
Craig Mautner5962b122012-10-05 14:45:52 -0700477
478 private boolean okToShow(ActivityRecord r) {
479 return r.userId == mCurrentUser
480 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
481 }
482
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700483 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
484 int i = mHistory.size()-1;
485 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700486 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700487 if (!r.finishing && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700488 return r;
489 }
490 i--;
491 }
492 return null;
493 }
494
495 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
496 int i = mHistory.size()-1;
497 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700498 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700499 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700500 return r;
501 }
502 i--;
503 }
504 return null;
505 }
506
507 /**
508 * This is a simplified version of topRunningActivityLocked that provides a number of
509 * optional skip-over modes. It is intended for use with the ActivityController hook only.
510 *
511 * @param token If non-null, any history records matching this token will be skipped.
512 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
513 *
514 * @return Returns the HistoryRecord of the next activity on the stack.
515 */
516 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
517 int i = mHistory.size()-1;
518 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700519 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700520 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700521 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
Craig Mautner5962b122012-10-05 14:45:52 -0700522 && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700523 return r;
524 }
525 i--;
526 }
527 return null;
528 }
529
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800530 private final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800531 return mHistory.indexOf(ActivityRecord.forToken(token));
532 }
533
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700534 final ActivityRecord isInStackLocked(IBinder token) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800535 ActivityRecord newAr = newIsInStackLocked(token);
536
Dianne Hackbornbe707852011-11-11 14:32:10 -0800537 ActivityRecord r = ActivityRecord.forToken(token);
538 if (mHistory.contains(r)) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800539 if (VALIDATE_TASK_REPLACE && newAr != r) Slog.w(TAG,
540 "isInStackLocked: mismatch: newAr=" + newAr + " r=" + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800541 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700542 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800543 if (VALIDATE_TASK_REPLACE && newAr != null) Slog.w(TAG,
544 "isInStackLocked: mismatch: newAr!=null");
545 return null;
546 }
547
548 final ActivityRecord newIsInStackLocked(IBinder token) {
549 final ActivityRecord r = ActivityRecord.forToken(token);
550 if (r != null) {
551 final TaskRecord task = r.task;
552 if (mTaskHistory.contains(task) && task.mActivities.contains(r)) {
553 return r;
554 }
555 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700556 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700557 }
558
Craig Mautnercae015f2013-02-08 14:31:27 -0800559 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800560 int newTaskId = newGetTaskForActivityLocked(token, onlyRoot);
561
Craig Mautnercae015f2013-02-08 14:31:27 -0800562 TaskRecord lastTask = null;
563 final int N = mHistory.size();
564 for (int i = 0; i < N; i++) {
565 ActivityRecord r = mHistory.get(i);
566 if (r.appToken == token) {
567 if (!onlyRoot || lastTask != r.task) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800568 if (VALIDATE_TASK_REPLACE && newTaskId != r.task.taskId) Slog.w(TAG,
569 "getTaskForActivityLocked: mismatch: new=" + newTaskId
570 + " taskId=" + r.task.taskId);
Craig Mautnercae015f2013-02-08 14:31:27 -0800571 return r.task.taskId;
572 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800573 if (VALIDATE_TASK_REPLACE && newTaskId != -1) Slog.w(TAG,
574 "getTaskForActivityLocked: mismatch: newTaskId=" + newTaskId + " not -1.");
Craig Mautnercae015f2013-02-08 14:31:27 -0800575 return -1;
576 }
577 lastTask = r.task;
578 }
579
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800580 if (VALIDATE_TASK_REPLACE && newTaskId != -1) Slog.w(TAG,
581 "getTaskForActivityLocked: mismatch at end: newTaskId=" + newTaskId + " not -1.");
Craig Mautnercae015f2013-02-08 14:31:27 -0800582 return -1;
583 }
584
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800585 int newGetTaskForActivityLocked(IBinder token, boolean onlyRoot) {
586 final ActivityRecord r = ActivityRecord.forToken(token);
587 if (r == null) {
588 return -1;
589 }
590 final TaskRecord task = r.task;
591 switch (task.mActivities.indexOf(r)) {
592 case -1: return -1;
593 case 0: return task.taskId;
594 default: return onlyRoot ? -1 : task.taskId;
595 }
596 }
597
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700598 private final boolean updateLRUListLocked(ActivityRecord r) {
599 final boolean hadit = mLRUActivities.remove(r);
600 mLRUActivities.add(r);
601 return hadit;
602 }
603
604 /**
605 * Returns the top activity in any existing task matching the given
606 * Intent. Returns null if no such task is found.
607 */
608 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
609 ComponentName cls = intent.getComponent();
610 if (info.targetActivity != null) {
611 cls = new ComponentName(info.packageName, info.targetActivity);
612 }
613
614 TaskRecord cp = null;
615
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700616 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700617 final int N = mHistory.size();
618 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700619 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700620 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700621 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
622 cp = r.task;
623 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
624 // + "/aff=" + r.task.affinity + " to new cls="
625 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
626 if (r.task.affinity != null) {
627 if (r.task.affinity.equals(info.taskAffinity)) {
628 //Slog.i(TAG, "Found matching affinity!");
629 return r;
630 }
631 } else if (r.task.intent != null
632 && r.task.intent.getComponent().equals(cls)) {
633 //Slog.i(TAG, "Found matching class!");
634 //dump();
635 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
636 return r;
637 } else if (r.task.affinityIntent != null
638 && r.task.affinityIntent.getComponent().equals(cls)) {
639 //Slog.i(TAG, "Found matching class!");
640 //dump();
641 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
642 return r;
643 }
644 }
645 }
646
647 return null;
648 }
649
650 /**
651 * Returns the first activity (starting from the top of the stack) that
652 * is the same as the given activity. Returns null if no such activity
653 * is found.
654 */
655 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
656 ComponentName cls = intent.getComponent();
657 if (info.targetActivity != null) {
658 cls = new ComponentName(info.packageName, info.targetActivity);
659 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700660 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700661
662 final int N = mHistory.size();
663 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700664 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700665 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700666 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700667 //Slog.i(TAG, "Found matching class!");
668 //dump();
669 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
670 return r;
671 }
672 }
673 }
674
675 return null;
676 }
677
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700678 final void showAskCompatModeDialogLocked(ActivityRecord r) {
679 Message msg = Message.obtain();
680 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
681 msg.obj = r.task.askedCompatMode ? null : r;
682 mService.mHandler.sendMessage(msg);
683 }
684
Amith Yamasani742a6712011-05-04 14:49:28 -0700685 /*
686 * Move the activities around in the stack to bring a user to the foreground.
687 * @return whether there are any activities for the specified user.
688 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700689 final boolean switchUserLocked(int userId, UserStartedState uss) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800690 if (VALIDATE_TOKENS) {
691 validateAppTokensLocked();
692 }
693 final boolean newResult = newSwitchUserLocked(userId, uss);
694
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700695 mCurrentUser = userId;
696 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700697
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700698 // Only one activity? Nothing to do...
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800699 if (mHistory.size() < 2) {
700 if (VALIDATE_TASK_REPLACE && newResult) Slog.w(TAG,
701 "switchUserLocked: mismatch: " + newResult + " " + false);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700702 return false;
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800703 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700704
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700705 boolean haveActivities = false;
706 // Check if the top activity is from the new user.
707 ActivityRecord top = mHistory.get(mHistory.size() - 1);
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800708 if (top.userId == userId) {
709 if (VALIDATE_TASK_REPLACE && !newResult) Slog.w(TAG,
710 "switchUserLocked: mismatch: " + newResult + " " + true);
711 return true;
712 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700713 // Otherwise, move the user's activities to the top.
714 int N = mHistory.size();
715 int i = 0;
716 while (i < N) {
717 ActivityRecord r = mHistory.get(i);
718 if (r.userId == userId) {
719 ActivityRecord moveToTop = mHistory.remove(i);
720 mHistory.add(moveToTop);
721 // No need to check the top one now
722 N--;
723 haveActivities = true;
724 } else {
725 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700726 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700727 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700728 // Transition from the old top to the new top
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800729 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
730 "switchUserLocked: calling resumeTopActivity " + top);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700731 resumeTopActivityLocked(top);
Craig Mautner5d9c7be2013-02-15 14:02:56 -0800732 if (VALIDATE_TASK_REPLACE && (newResult != haveActivities)) Slog.w(TAG,
733 "switchUserLocked: mismatch: " + newResult + " " + haveActivities);
734 return haveActivities;
735 }
736
737 /*
738 * Move the activities around in the stack to bring a user to the foreground.
739 * @return whether there are any activities for the specified user.
740 */
741 final boolean newSwitchUserLocked(int userId, UserStartedState uss) {
742// mStartingUsers.add(uss);
743 if (mCurrentUser == userId) {
744 return true;
745 }
746 mCurrentUser = userId;
747
748 // Move userId's tasks to the top.
749 boolean haveActivities = false;
750 TaskRecord task = null;
751 int index = mTaskHistory.size();
752 for (int i = 0; i < index; ++i) {
753 task = mTaskHistory.get(i);
754 if (task.userId == userId) {
755 haveActivities = true;
756 mTaskHistory.remove(i);
757 mTaskHistory.add(task);
758 --index;
759 }
760 }
761
762 // task is now the original topmost TaskRecord. Transition from the old top to the new top.
763 ActivityRecord top = task != null ? task.getTopActivity() : null;
764 if (VALIDATE_TASK_REPLACE) Slog.w(TAG,
765 "newSwitchUserLocked: would call resumeTopActivity " + top);
766// resumeTopActivityLocked(top);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700767 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700768 }
769
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700770 final boolean realStartActivityLocked(ActivityRecord r,
771 ProcessRecord app, boolean andResume, boolean checkConfig)
772 throws RemoteException {
773
774 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800775 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700776
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700777 // schedule launch ticks to collect information about slow apps.
778 r.startLaunchTickingLocked();
779
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700780 // Have the window manager re-evaluate the orientation of
781 // the screen based on the new activity order. Note that
782 // as a result of this, it can call back into the activity
783 // manager with a new orientation. We don't care about that,
784 // because the activity is not currently running so we are
785 // just restarting it anyway.
786 if (checkConfig) {
787 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
788 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800789 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800790 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700791 }
792
793 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700794 app.waitingToKill = null;
Dianne Hackborn07981492013-01-28 11:36:23 -0800795 r.launchCount++;
796 r.lastLaunchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700797
798 if (localLOGV) Slog.v(TAG, "Launching: " + r);
799
800 int idx = app.activities.indexOf(r);
801 if (idx < 0) {
802 app.activities.add(r);
803 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700804 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700805
806 try {
807 if (app.thread == null) {
808 throw new RemoteException();
809 }
810 List<ResultInfo> results = null;
811 List<Intent> newIntents = null;
812 if (andResume) {
813 results = r.results;
814 newIntents = r.newIntents;
815 }
816 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
817 + " icicle=" + r.icicle
818 + " with results=" + results + " newIntents=" + newIntents
819 + " andResume=" + andResume);
820 if (andResume) {
821 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700822 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700823 r.task.taskId, r.shortComponentName);
824 }
825 if (r.isHomeActivity) {
826 mService.mHomeProcess = app;
827 }
828 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800829 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400830 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700831 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700832 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700833 String profileFile = null;
834 ParcelFileDescriptor profileFd = null;
835 boolean profileAutoStop = false;
836 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
837 if (mService.mProfileProc == null || mService.mProfileProc == app) {
838 mService.mProfileProc = app;
839 profileFile = mService.mProfileFile;
840 profileFd = mService.mProfileFd;
841 profileAutoStop = mService.mAutoStopProfiler;
842 }
843 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700844 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700845 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700846 if (profileFd != null) {
847 try {
848 profileFd = profileFd.dup();
849 } catch (IOException e) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800850 if (profileFd != null) {
851 try {
852 profileFd.close();
853 } catch (IOException o) {
854 }
855 profileFd = null;
856 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700857 }
858 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800859 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800860 System.identityHashCode(r), r.info,
861 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700862 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700863 mService.isNextTransitionForward(), profileFile, profileFd,
864 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700865
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700866 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700867 // This may be a heavy-weight process! Note that the package
868 // manager will ensure that only activity can run in the main
869 // process of the .apk, which is the only thing that will be
870 // considered heavy-weight.
871 if (app.processName.equals(app.info.packageName)) {
872 if (mService.mHeavyWeightProcess != null
873 && mService.mHeavyWeightProcess != app) {
874 Log.w(TAG, "Starting new heavy weight process " + app
875 + " when already running "
876 + mService.mHeavyWeightProcess);
877 }
878 mService.mHeavyWeightProcess = app;
879 Message msg = mService.mHandler.obtainMessage(
880 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
881 msg.obj = r;
882 mService.mHandler.sendMessage(msg);
883 }
884 }
885
886 } catch (RemoteException e) {
887 if (r.launchFailed) {
888 // This is the second time we failed -- finish activity
889 // and give up.
890 Slog.e(TAG, "Second failure launching "
891 + r.intent.getComponent().flattenToShortString()
892 + ", giving up", e);
893 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800894 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700895 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700896 return false;
897 }
898
899 // This is the first time we failed -- restart process and
900 // retry.
901 app.activities.remove(r);
902 throw e;
903 }
904
905 r.launchFailed = false;
906 if (updateLRUListLocked(r)) {
907 Slog.w(TAG, "Activity " + r
908 + " being launched, but already in LRU list");
909 }
910
911 if (andResume) {
912 // As part of the process of launching, ActivityThread also performs
913 // a resume.
914 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700915 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
916 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700917 r.stopped = false;
918 mResumedActivity = r;
919 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800920 if (mMainStack) {
921 mService.addRecentTaskLocked(r.task);
922 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700923 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800924 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700925 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700926 } else {
927 // This activity is not starting in the resumed state... which
928 // should look like we asked it to pause+stop (but remain visible),
929 // and it has done so and reported back the current icicle and
930 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700931 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
932 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700933 r.state = ActivityState.STOPPED;
934 r.stopped = true;
935 }
936
937 // Launch the new version setup screen if needed. We do this -after-
938 // launching the initial activity (that is, home), so that it can have
939 // a chance to initialize itself while in the background, making the
940 // switch back to it faster and look better.
941 if (mMainStack) {
942 mService.startSetupActivityLocked();
943 }
944
945 return true;
946 }
947
948 private final void startSpecificActivityLocked(ActivityRecord r,
949 boolean andResume, boolean checkConfig) {
950 // Is this activity's application already running?
951 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
952 r.info.applicationInfo.uid);
Dianne Hackborn07981492013-01-28 11:36:23 -0800953
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700954 if (r.launchTime == 0) {
955 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700956 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700957 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700958 }
959 } else if (mInitialStartTime == 0) {
960 mInitialStartTime = SystemClock.uptimeMillis();
961 }
962
963 if (app != null && app.thread != null) {
964 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700965 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700966 realStartActivityLocked(r, app, andResume, checkConfig);
967 return;
968 } catch (RemoteException e) {
969 Slog.w(TAG, "Exception when starting activity "
970 + r.intent.getComponent().flattenToShortString(), e);
971 }
972
973 // If a dead object exception was thrown -- fall through to
974 // restart the application.
975 }
976
977 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800978 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700979 }
980
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800981 void stopIfSleepingLocked() {
982 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700983 if (!mGoingToSleep.isHeld()) {
984 mGoingToSleep.acquire();
985 if (mLaunchingActivity.isHeld()) {
986 mLaunchingActivity.release();
987 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
988 }
989 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800990 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
991 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
992 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
993 checkReadyForSleepLocked();
994 }
995 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700996
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800997 void awakeFromSleepingLocked() {
998 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
999 mSleepTimeout = false;
1000 if (mGoingToSleep.isHeld()) {
1001 mGoingToSleep.release();
1002 }
1003 // Ensure activities are no longer sleeping.
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001004 if (VALIDATE_TASK_REPLACE) {
1005 verifyActivityRecords();
1006 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001007 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001008 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001009 r.setSleeping(false);
1010 }
1011 mGoingToSleepActivities.clear();
1012 }
1013
1014 void activitySleptLocked(ActivityRecord r) {
1015 mGoingToSleepActivities.remove(r);
1016 checkReadyForSleepLocked();
1017 }
1018
1019 void checkReadyForSleepLocked() {
1020 if (!mService.isSleeping()) {
1021 // Do not care.
1022 return;
1023 }
1024
1025 if (!mSleepTimeout) {
1026 if (mResumedActivity != null) {
1027 // Still have something resumed; can't sleep until it is paused.
1028 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001029 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
1030 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001031 return;
1032 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001033 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001034 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001035 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001036 return;
1037 }
1038
1039 if (mStoppingActivities.size() > 0) {
1040 // Still need to tell some activities to stop; can't sleep yet.
1041 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
1042 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07001043 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001044 return;
1045 }
1046
1047 ensureActivitiesVisibleLocked(null, 0);
1048
1049 // Make sure any stopped but visible activities are now sleeping.
1050 // This ensures that the activity's onStop() is called.
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001051 if (VALIDATE_TASK_REPLACE) {
1052 verifyActivityRecords();
1053 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001054 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001055 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001056 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
1057 r.setSleeping(true);
1058 }
1059 }
1060
1061 if (mGoingToSleepActivities.size() > 0) {
1062 // Still need to tell some activities to sleep; can't sleep yet.
1063 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
1064 + mGoingToSleepActivities.size() + " activities");
1065 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001066 }
1067 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001068
1069 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
1070
1071 if (mGoingToSleep.isHeld()) {
1072 mGoingToSleep.release();
1073 }
1074 if (mService.mShuttingDown) {
1075 mService.notifyAll();
1076 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001077 }
Craig Mautner59c00972012-07-30 12:10:24 -07001078
Dianne Hackbornd2835932010-12-13 16:28:46 -08001079 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -08001080 if (who.noDisplay) {
1081 return null;
1082 }
1083
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001084 Resources res = mService.mContext.getResources();
1085 int w = mThumbnailWidth;
1086 int h = mThumbnailHeight;
1087 if (w < 0) {
1088 mThumbnailWidth = w =
1089 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
1090 mThumbnailHeight = h =
1091 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
1092 }
1093
1094 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -08001095 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
1096 || mLastScreenshotBitmap.getWidth() != w
1097 || mLastScreenshotBitmap.getHeight() != h) {
1098 mLastScreenshotActivity = who;
1099 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
1100 who.appToken, Display.DEFAULT_DISPLAY, w, h);
1101 }
1102 if (mLastScreenshotBitmap != null) {
1103 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
1104 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001105 }
1106 return null;
1107 }
1108
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001109 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001110 if (mPausingActivity != null) {
1111 RuntimeException e = new RuntimeException();
1112 Slog.e(TAG, "Trying to pause when pause is already pending for "
1113 + mPausingActivity, e);
1114 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001115 ActivityRecord prev = mResumedActivity;
1116 if (prev == null) {
1117 RuntimeException e = new RuntimeException();
1118 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
1119 resumeTopActivityLocked(null);
1120 return;
1121 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001122 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
1123 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001124 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001125 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001126 mLastPausedActivity = prev;
1127 prev.state = ActivityState.PAUSING;
1128 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001129 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001130
1131 mService.updateCpuStats();
1132
1133 if (prev.app != null && prev.app.thread != null) {
1134 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
1135 try {
1136 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001137 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001138 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001139 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1140 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001141 if (mMainStack) {
1142 mService.updateUsageStats(prev, false);
1143 }
1144 } catch (Exception e) {
1145 // Ignore exception, if process died other code will cleanup.
1146 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001147 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001148 mLastPausedActivity = null;
1149 }
1150 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001151 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001152 mLastPausedActivity = null;
1153 }
1154
1155 // If we are not going to sleep, we want to ensure the device is
1156 // awake until the next activity is started.
1157 if (!mService.mSleeping && !mService.mShuttingDown) {
1158 mLaunchingActivity.acquire();
1159 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1160 // To be safe, don't allow the wake lock to be held for too long.
1161 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1162 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1163 }
1164 }
1165
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001166
1167 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001168 // Have the window manager pause its key dispatching until the new
1169 // activity has started. If we're pausing the activity just because
1170 // the screen is being turned off and the UI is sleeping, don't interrupt
1171 // key dispatch; the same activity will pick it up again on wakeup.
1172 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001173 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001174 } else {
1175 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1176 }
1177
1178 // Schedule a pause timeout in case the app doesn't respond.
1179 // We don't give it much time because this directly impacts the
1180 // responsiveness seen by the user.
1181 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1182 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001183 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001184 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1185 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1186 } else {
1187 // This activity failed to schedule the
1188 // pause, so just treat it as being paused now.
1189 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001190 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001191 }
1192 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001193
1194 final void activityResumed(IBinder token) {
1195 ActivityRecord r = null;
1196
1197 synchronized (mService) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001198 if (VALIDATE_TASK_REPLACE) {
1199 verifyActivityRecords();
1200 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001201 int index = indexOfTokenLocked(token);
1202 if (index >= 0) {
1203 r = mHistory.get(index);
1204 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1205 r.icicle = null;
1206 r.haveState = false;
1207 }
1208 }
1209 }
1210
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001211 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001212 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001213 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001214
1215 ActivityRecord r = null;
1216
1217 synchronized (mService) {
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001218 if (VALIDATE_TASK_REPLACE) {
1219 verifyActivityRecords();
1220 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001221 int index = indexOfTokenLocked(token);
1222 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001223 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001224 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001225 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001226 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1227 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001228 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001229 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001230 } else {
1231 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001232 r.userId, System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001233 mPausingActivity != null
1234 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001235 }
1236 }
1237 }
1238 }
1239
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001240 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1241 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001242 if (r.state != ActivityState.STOPPING) {
1243 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1244 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1245 return;
1246 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001247 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001248 if (icicle != null) {
1249 // If icicle is null, this is happening due to a timeout, so we
1250 // haven't really saved the state.
1251 r.icicle = icicle;
1252 r.haveState = true;
Dianne Hackborn07981492013-01-28 11:36:23 -08001253 r.launchCount = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001254 r.updateThumbnail(thumbnail, description);
1255 }
1256 if (!r.stopped) {
1257 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1258 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1259 r.stopped = true;
1260 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001261 if (r.finishing) {
1262 r.clearOptionsLocked();
1263 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001264 if (r.configDestroy) {
1265 destroyActivityLocked(r, true, false, "stop-config");
1266 resumeTopActivityLocked(null);
1267 } else {
1268 // Now that this process has stopped, we may want to consider
1269 // it to be the previous app to try to keep around in case
1270 // the user wants to return to it.
1271 ProcessRecord fgApp = null;
1272 if (mResumedActivity != null) {
1273 fgApp = mResumedActivity.app;
1274 } else if (mPausingActivity != null) {
1275 fgApp = mPausingActivity.app;
1276 }
1277 if (r.app != null && fgApp != null && r.app != fgApp
1278 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1279 && r.app != mService.mHomeProcess) {
1280 mService.mPreviousProcess = r.app;
1281 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1282 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001283 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001284 }
1285 }
1286 }
1287
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001288 private final void completePauseLocked() {
1289 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001290 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1291
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001292 if (prev != null) {
1293 if (prev.finishing) {
1294 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001295 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001296 } else if (prev.app != null) {
1297 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1298 if (prev.waitingVisible) {
1299 prev.waitingVisible = false;
1300 mWaitingVisibleActivities.remove(prev);
1301 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1302 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001303 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001304 if (prev.configDestroy) {
1305 // The previous is being paused because the configuration
1306 // is changing, which means it is actually stopping...
1307 // To juggle the fact that we are also starting a new
1308 // instance right now, we need to first completely stop
1309 // the current instance before starting the new one.
1310 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1311 destroyActivityLocked(prev, true, false, "pause-config");
1312 } else {
1313 mStoppingActivities.add(prev);
1314 if (mStoppingActivities.size() > 3) {
1315 // If we already have a few activities waiting to stop,
1316 // then give up on things going idle and start clearing
1317 // them out.
1318 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1319 scheduleIdleLocked();
1320 } else {
1321 checkReadyForSleepLocked();
1322 }
1323 }
1324 } else {
1325 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1326 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001327 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001328 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001329 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001330
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001331 if (!mService.isSleeping()) {
1332 resumeTopActivityLocked(prev);
1333 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001334 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001335 ActivityRecord top = topRunningActivityLocked(null);
1336 if (top == null || (prev != null && top != prev)) {
1337 // If there are no more activities available to run,
1338 // do resume anyway to start something. Also if the top
1339 // activity on the stack is not the just paused activity,
1340 // we need to go ahead and resume it to ensure we complete
1341 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001342 resumeTopActivityLocked(null);
1343 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001344 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001345
1346 if (prev != null) {
1347 prev.resumeKeyDispatchingLocked();
1348 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001349
1350 if (prev.app != null && prev.cpuTimeAtResume > 0
1351 && mService.mBatteryStatsService.isOnBattery()) {
1352 long diff = 0;
1353 synchronized (mService.mProcessStatsThread) {
1354 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1355 - prev.cpuTimeAtResume;
1356 }
1357 if (diff > 0) {
1358 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1359 synchronized (bsi) {
1360 BatteryStatsImpl.Uid.Proc ps =
1361 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1362 prev.info.packageName);
1363 if (ps != null) {
1364 ps.addForegroundTimeLocked(diff);
1365 }
1366 }
1367 }
1368 }
1369 prev.cpuTimeAtResume = 0; // reset it
1370 }
1371
1372 /**
1373 * Once we know that we have asked an application to put an activity in
1374 * the resumed state (either by launching it or explicitly telling it),
1375 * this function updates the rest of our state to match that fact.
1376 */
1377 private final void completeResumeLocked(ActivityRecord next) {
1378 next.idle = false;
1379 next.results = null;
1380 next.newIntents = null;
1381
1382 // schedule an idle timeout in case the app doesn't do it for us.
1383 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1384 msg.obj = next;
1385 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1386
1387 if (false) {
1388 // The activity was never told to pause, so just keep
1389 // things going as-is. To maintain our own state,
1390 // we need to emulate it coming back and saying it is
1391 // idle.
1392 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1393 msg.obj = next;
1394 mHandler.sendMessage(msg);
1395 }
1396
1397 if (mMainStack) {
1398 mService.reportResumedActivityLocked(next);
1399 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001400
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001401 if (mMainStack) {
1402 mService.setFocusedActivityLocked(next);
1403 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001404 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001405 ensureActivitiesVisibleLocked(null, 0);
1406 mService.mWindowManager.executeAppTransition();
1407 mNoAnimActivities.clear();
1408
1409 // Mark the point when the activity is resuming
1410 // TODO: To be more accurate, the mark should be before the onCreate,
1411 // not after the onResume. But for subsequent starts, onResume is fine.
1412 if (next.app != null) {
1413 synchronized (mService.mProcessStatsThread) {
1414 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1415 }
1416 } else {
1417 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1418 }
1419 }
1420
1421 /**
1422 * Make sure that all activities that need to be visible (that is, they
1423 * currently can be seen by the user) actually are.
1424 */
1425 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1426 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1427 if (DEBUG_VISBILITY) Slog.v(
1428 TAG, "ensureActivitiesVisible behind " + top
1429 + " configChanges=0x" + Integer.toHexString(configChanges));
1430
1431 // If the top activity is not fullscreen, then we need to
1432 // make sure any activities under it are now visible.
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001433 if (VALIDATE_TASK_REPLACE) {
1434 verifyActivityRecords();
1435 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001436 final int count = mHistory.size();
1437 int i = count-1;
1438 while (mHistory.get(i) != top) {
1439 i--;
1440 }
1441 ActivityRecord r;
1442 boolean behindFullscreen = false;
1443 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001444 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001445 if (DEBUG_VISBILITY) Slog.v(
1446 TAG, "Make visible? " + r + " finishing=" + r.finishing
1447 + " state=" + r.state);
1448 if (r.finishing) {
1449 continue;
1450 }
1451
1452 final boolean doThisProcess = onlyThisProcess == null
1453 || onlyThisProcess.equals(r.processName);
1454
1455 // First: if this is not the current activity being started, make
1456 // sure it matches the current configuration.
1457 if (r != starting && doThisProcess) {
1458 ensureActivityConfigurationLocked(r, 0);
1459 }
1460
1461 if (r.app == null || r.app.thread == null) {
1462 if (onlyThisProcess == null
1463 || onlyThisProcess.equals(r.processName)) {
1464 // This activity needs to be visible, but isn't even
1465 // running... get it started, but don't resume it
1466 // at this point.
1467 if (DEBUG_VISBILITY) Slog.v(
1468 TAG, "Start and freeze screen for " + r);
1469 if (r != starting) {
1470 r.startFreezingScreenLocked(r.app, configChanges);
1471 }
1472 if (!r.visible) {
1473 if (DEBUG_VISBILITY) Slog.v(
1474 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001475 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001476 }
1477 if (r != starting) {
1478 startSpecificActivityLocked(r, false, false);
1479 }
1480 }
1481
1482 } else if (r.visible) {
1483 // If this activity is already visible, then there is nothing
1484 // else to do here.
1485 if (DEBUG_VISBILITY) Slog.v(
1486 TAG, "Skipping: already visible at " + r);
1487 r.stopFreezingScreenLocked(false);
1488
1489 } else if (onlyThisProcess == null) {
1490 // This activity is not currently visible, but is running.
1491 // Tell it to become visible.
1492 r.visible = true;
1493 if (r.state != ActivityState.RESUMED && r != starting) {
1494 // If this activity is paused, tell it
1495 // to now show its window.
1496 if (DEBUG_VISBILITY) Slog.v(
1497 TAG, "Making visible and scheduling visibility: " + r);
1498 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001499 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001500 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001501 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001502 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001503 r.stopFreezingScreenLocked(false);
1504 } catch (Exception e) {
1505 // Just skip on any failure; we'll make it
1506 // visible when it next restarts.
1507 Slog.w(TAG, "Exception thrown making visibile: "
1508 + r.intent.getComponent(), e);
1509 }
1510 }
1511 }
1512
1513 // Aggregate current change flags.
1514 configChanges |= r.configChangeFlags;
1515
1516 if (r.fullscreen) {
1517 // At this point, nothing else needs to be shown
1518 if (DEBUG_VISBILITY) Slog.v(
1519 TAG, "Stopping: fullscreen at " + r);
1520 behindFullscreen = true;
1521 i--;
1522 break;
1523 }
1524 }
1525
1526 // Now for any activities that aren't visible to the user, make
1527 // sure they no longer are keeping the screen frozen.
1528 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001529 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001530 if (DEBUG_VISBILITY) Slog.v(
1531 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1532 + " state=" + r.state
1533 + " behindFullscreen=" + behindFullscreen);
1534 if (!r.finishing) {
1535 if (behindFullscreen) {
1536 if (r.visible) {
1537 if (DEBUG_VISBILITY) Slog.v(
1538 TAG, "Making invisible: " + r);
1539 r.visible = false;
1540 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001541 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001542 if ((r.state == ActivityState.STOPPING
1543 || r.state == ActivityState.STOPPED)
1544 && r.app != null && r.app.thread != null) {
1545 if (DEBUG_VISBILITY) Slog.v(
1546 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001547 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001548 }
1549 } catch (Exception e) {
1550 // Just skip on any failure; we'll make it
1551 // visible when it next restarts.
1552 Slog.w(TAG, "Exception thrown making hidden: "
1553 + r.intent.getComponent(), e);
1554 }
1555 } else {
1556 if (DEBUG_VISBILITY) Slog.v(
1557 TAG, "Already invisible: " + r);
1558 }
1559 } else if (r.fullscreen) {
1560 if (DEBUG_VISBILITY) Slog.v(
1561 TAG, "Now behindFullscreen: " + r);
1562 behindFullscreen = true;
1563 }
1564 }
1565 i--;
1566 }
1567 }
1568
1569 /**
1570 * Version of ensureActivitiesVisible that can easily be called anywhere.
1571 */
1572 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1573 int configChanges) {
1574 ActivityRecord r = topRunningActivityLocked(null);
1575 if (r != null) {
1576 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1577 }
1578 }
1579
1580 /**
1581 * Ensure that the top activity in the stack is resumed.
1582 *
1583 * @param prev The previously resumed activity, for when in the process
1584 * of pausing; can be null to call from elsewhere.
1585 *
1586 * @return Returns true if something is being resumed, or false if
1587 * nothing happened.
1588 */
1589 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001590 return resumeTopActivityLocked(prev, null);
1591 }
1592
1593 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001594 // Find the first activity that is not finishing.
1595 ActivityRecord next = topRunningActivityLocked(null);
1596
1597 // Remember how we'll process this pause/resume situation, and ensure
1598 // that the state is reset however we wind up proceeding.
1599 final boolean userLeaving = mUserLeaving;
1600 mUserLeaving = false;
1601
1602 if (next == null) {
1603 // There are no more activities! Let's just start up the
1604 // Launcher...
1605 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001606 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001607 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001608 }
1609 }
1610
1611 next.delayedResume = false;
1612
1613 // If the top activity is the resumed one, nothing to do.
1614 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1615 // Make sure we have executed any pending transitions, since there
1616 // should be nothing left to do at this point.
1617 mService.mWindowManager.executeAppTransition();
1618 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001619 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001620 return false;
1621 }
1622
1623 // If we are sleeping, and there is no resumed activity, and the top
1624 // activity is paused, well that is the state we want.
1625 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001626 && mLastPausedActivity == next
1627 && (next.state == ActivityState.PAUSED
1628 || next.state == ActivityState.STOPPED
1629 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001630 // Make sure we have executed any pending transitions, since there
1631 // should be nothing left to do at this point.
1632 mService.mWindowManager.executeAppTransition();
1633 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001634 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001635 return false;
1636 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001637
1638 // Make sure that the user who owns this activity is started. If not,
1639 // we will just leave it as is because someone should be bringing
1640 // another user's activities to the top of the stack.
1641 if (mService.mStartedUsers.get(next.userId) == null) {
1642 Slog.w(TAG, "Skipping resume of top activity " + next
1643 + ": user " + next.userId + " is stopped");
1644 return false;
1645 }
1646
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001647 // The activity may be waiting for stop, but that is no longer
1648 // appropriate for it.
1649 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001650 mGoingToSleepActivities.remove(next);
1651 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001652 mWaitingVisibleActivities.remove(next);
1653
Dianne Hackborn84375872012-06-01 19:03:50 -07001654 next.updateOptionsLocked(options);
1655
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001656 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1657
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001658 // If we are currently pausing an activity, then don't do anything
1659 // until that is done.
1660 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001661 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1662 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001663 return false;
1664 }
1665
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001666 // Okay we are now going to start a switch, to 'next'. We may first
1667 // have to pause the current activity, but this is an important point
1668 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001669 // XXX "App Redirected" dialog is getting too many false positives
1670 // at this point, so turn off for now.
1671 if (false) {
1672 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1673 long now = SystemClock.uptimeMillis();
1674 final boolean inTime = mLastStartedActivity.startTime != 0
1675 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1676 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1677 final int nextUid = next.info.applicationInfo.uid;
1678 if (inTime && lastUid != nextUid
1679 && lastUid != next.launchedFromUid
1680 && mService.checkPermission(
1681 android.Manifest.permission.STOP_APP_SWITCHES,
1682 -1, next.launchedFromUid)
1683 != PackageManager.PERMISSION_GRANTED) {
1684 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1685 } else {
1686 next.startTime = now;
1687 mLastStartedActivity = next;
1688 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001689 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001690 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001691 mLastStartedActivity = next;
1692 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001693 }
1694
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001695 // We need to start pausing the current activity so the top one
1696 // can be resumed...
1697 if (mResumedActivity != null) {
1698 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001699 // At this point we want to put the upcoming activity's process
1700 // at the top of the LRU list, since we know we will be needing it
1701 // very soon and it would be a waste to let it get killed if it
1702 // happens to be sitting towards the end.
1703 if (next.app != null && next.app.thread != null) {
1704 // No reason to do full oom adj update here; we'll let that
1705 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001706 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001707 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001708 startPausingLocked(userLeaving, false);
1709 return true;
1710 }
1711
Christopher Tated3f175c2012-06-14 14:16:54 -07001712 // If the most recent activity was noHistory but was only stopped rather
1713 // than stopped+finished because the device went to sleep, we need to make
1714 // sure to finish it as we're making a new activity topmost.
1715 final ActivityRecord last = mLastPausedActivity;
1716 if (mService.mSleeping && last != null && !last.finishing) {
1717 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1718 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1719 if (DEBUG_STATES) {
1720 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1721 }
1722 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001723 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001724 }
1725 }
1726
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001727 if (prev != null && prev != next) {
1728 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1729 prev.waitingVisible = true;
1730 mWaitingVisibleActivities.add(prev);
1731 if (DEBUG_SWITCH) Slog.v(
1732 TAG, "Resuming top, waiting visible to hide: " + prev);
1733 } else {
1734 // The next activity is already visible, so hide the previous
1735 // activity's windows right now so we can show the new one ASAP.
1736 // We only do this if the previous is finishing, which should mean
1737 // it is on top of the one being resumed so hiding it quickly
1738 // is good. Otherwise, we want to do the normal route of allowing
1739 // the resumed activity to be shown so we can decide if the
1740 // previous should actually be hidden depending on whether the
1741 // new one is found to be full-screen or not.
1742 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001743 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001744 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1745 + prev + ", waitingVisible="
1746 + (prev != null ? prev.waitingVisible : null)
1747 + ", nowVisible=" + next.nowVisible);
1748 } else {
1749 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1750 + prev + ", waitingVisible="
1751 + (prev != null ? prev.waitingVisible : null)
1752 + ", nowVisible=" + next.nowVisible);
1753 }
1754 }
1755 }
1756
Dianne Hackborne7f97212011-02-24 14:40:20 -08001757 // Launching this app's activity, make sure the app is no longer
1758 // considered stopped.
1759 try {
1760 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001761 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001762 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001763 } catch (IllegalArgumentException e) {
1764 Slog.w(TAG, "Failed trying to unstop package "
1765 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001766 }
1767
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001768 // We are starting up the next activity, so tell the window manager
1769 // that the previous one will be hidden soon. This way it can know
1770 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001771 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001772 if (prev != null) {
1773 if (prev.finishing) {
1774 if (DEBUG_TRANSITION) Slog.v(TAG,
1775 "Prepare close transition: prev=" + prev);
1776 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001777 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001778 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001779 } else {
1780 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001781 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1782 : AppTransition.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001784 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1785 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001786 } else {
1787 if (DEBUG_TRANSITION) Slog.v(TAG,
1788 "Prepare open transition: prev=" + prev);
1789 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001790 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001791 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001792 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001793 } else {
1794 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001795 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1796 : AppTransition.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001797 }
1798 }
1799 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001800 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1801 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 }
1803 } else if (mHistory.size() > 1) {
1804 if (DEBUG_TRANSITION) Slog.v(TAG,
1805 "Prepare open transition: no previous");
1806 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001807 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001808 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001809 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001810 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001811 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001812 AppTransition.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001813 }
1814 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001815 if (!noAnim) {
1816 next.applyOptionsLocked();
1817 } else {
1818 next.clearOptionsLocked();
1819 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001820
1821 if (next.app != null && next.app.thread != null) {
1822 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1823
1824 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001825 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001826
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001827 // schedule launch ticks to collect information about slow apps.
1828 next.startLaunchTickingLocked();
1829
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001830 ActivityRecord lastResumedActivity = mResumedActivity;
1831 ActivityState lastState = next.state;
1832
1833 mService.updateCpuStats();
1834
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001835 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001836 next.state = ActivityState.RESUMED;
1837 mResumedActivity = next;
1838 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001839 if (mMainStack) {
1840 mService.addRecentTaskLocked(next.task);
1841 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001842 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001843 updateLRUListLocked(next);
1844
1845 // Have the window manager re-evaluate the orientation of
1846 // the screen based on the new activity order.
1847 boolean updated = false;
1848 if (mMainStack) {
1849 synchronized (mService) {
1850 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1851 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001852 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001853 if (config != null) {
1854 next.frozenBeforeDestroy = true;
1855 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001856 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001857 }
1858 }
1859 if (!updated) {
1860 // The configuration update wasn't able to keep the existing
1861 // instance of the activity, and instead started a new one.
1862 // We should be all done, but let's just make sure our activity
1863 // is still at the top and schedule another run if something
1864 // weird happened.
1865 ActivityRecord nextNext = topRunningActivityLocked(null);
1866 if (DEBUG_SWITCH) Slog.i(TAG,
1867 "Activity config changed during resume: " + next
1868 + ", new next: " + nextNext);
1869 if (nextNext != next) {
1870 // Do over!
1871 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1872 }
1873 if (mMainStack) {
1874 mService.setFocusedActivityLocked(next);
1875 }
1876 ensureActivitiesVisibleLocked(null, 0);
1877 mService.mWindowManager.executeAppTransition();
1878 mNoAnimActivities.clear();
1879 return true;
1880 }
1881
1882 try {
1883 // Deliver all pending results.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08001884 ArrayList<ResultInfo> a = next.results;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001885 if (a != null) {
1886 final int N = a.size();
1887 if (!next.finishing && N > 0) {
1888 if (DEBUG_RESULTS) Slog.v(
1889 TAG, "Delivering results to " + next
1890 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001891 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001892 }
1893 }
1894
1895 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001896 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001897 }
1898
1899 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001900 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001901 next.task.taskId, next.shortComponentName);
1902
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001903 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001904 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001905 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001906 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001907 mService.isNextTransitionForward());
1908
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001909 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001910
1911 } catch (Exception e) {
1912 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001913 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1914 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001915 next.state = lastState;
1916 mResumedActivity = lastResumedActivity;
1917 Slog.i(TAG, "Restarting because process died: " + next);
1918 if (!next.hasBeenLaunched) {
1919 next.hasBeenLaunched = true;
1920 } else {
1921 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1922 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001923 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001924 mService.compatibilityInfoForPackageLocked(
1925 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001926 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001927 next.labelRes, next.icon, next.windowFlags,
1928 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001929 }
1930 }
1931 startSpecificActivityLocked(next, true, false);
1932 return true;
1933 }
1934
1935 // From this point on, if something goes wrong there is no way
1936 // to recover the activity.
1937 try {
1938 next.visible = true;
1939 completeResumeLocked(next);
1940 } catch (Exception e) {
1941 // If any exception gets thrown, toss away this
1942 // activity and try the next one.
1943 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001944 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001945 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001946 return true;
1947 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001948 next.stopped = false;
1949
1950 } else {
1951 // Whoops, need to restart this activity!
1952 if (!next.hasBeenLaunched) {
1953 next.hasBeenLaunched = true;
1954 } else {
1955 if (SHOW_APP_STARTING_PREVIEW) {
1956 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001957 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001958 mService.compatibilityInfoForPackageLocked(
1959 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001960 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001961 next.labelRes, next.icon, next.windowFlags,
1962 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001963 }
1964 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1965 }
1966 startSpecificActivityLocked(next, true, true);
1967 }
1968
1969 return true;
1970 }
1971
1972 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001973 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001974 final int NH = mHistory.size();
1975
1976 int addPos = -1;
1977
1978 if (!newTask) {
1979 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001980 boolean startIt = true;
1981 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001982 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001983 if (p.finishing) {
1984 continue;
1985 }
1986 if (p.task == r.task) {
1987 // Here it is! Now, if this is not yet visible to the
1988 // user, then just add it without starting; it will
1989 // get started when the user navigates back to it.
1990 addPos = i+1;
1991 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001992 if (DEBUG_ADD_REMOVE) {
1993 RuntimeException here = new RuntimeException("here");
1994 here.fillInStackTrace();
1995 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1996 here);
1997 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08001998 r.task.addActivityToTop(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001999 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002000 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08002001 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07002002 r.info.screenOrientation, r.fullscreen,
2003 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002004 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002005 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002006 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002007 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002008 return;
2009 }
2010 break;
2011 }
2012 if (p.fullscreen) {
2013 startIt = false;
2014 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002015 }
2016 }
2017
2018 // Place a new activity at top of stack, so it is next to interact
2019 // with the user.
2020 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07002021 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002022 }
2023
2024 // If we are not placing the new activity frontmost, we do not want
2025 // to deliver the onUserLeaving callback to the actual frontmost
2026 // activity
2027 if (addPos < NH) {
2028 mUserLeaving = false;
2029 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
2030 }
2031
2032 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002033 if (DEBUG_ADD_REMOVE) {
2034 RuntimeException here = new RuntimeException("here");
2035 here.fillInStackTrace();
2036 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
2037 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002038 r.task.addActivityToTop(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002040 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002041 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002042 if (NH > 0) {
2043 // We want to show the starting preview window if we are
2044 // switching to a new task, or the next activity's process is
2045 // not currently running.
2046 boolean showStartingIcon = newTask;
2047 ProcessRecord proc = r.app;
2048 if (proc == null) {
2049 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
2050 }
2051 if (proc == null || proc.thread == null) {
2052 showStartingIcon = true;
2053 }
2054 if (DEBUG_TRANSITION) Slog.v(TAG,
2055 "Prepare open transition: starting " + r);
2056 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002057 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08002058 AppTransition.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002059 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002060 } else {
2061 mService.mWindowManager.prepareAppTransition(newTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08002062 ? AppTransition.TRANSIT_TASK_OPEN
2063 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002064 mNoAnimActivities.remove(r);
2065 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002066 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002067 mService.mWindowManager.addAppToken(
Craig Mautner5962b122012-10-05 14:45:52 -07002068 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
2069 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002070 boolean doShow = true;
2071 if (newTask) {
2072 // Even though this activity is starting fresh, we still need
2073 // to reset it to make sure we apply affinities to move any
2074 // existing activities from other tasks in to it.
2075 // If the caller has requested that the target task be
2076 // reset, then do so.
2077 if ((r.intent.getFlags()
2078 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2079 resetTaskIfNeededLocked(r, r);
2080 doShow = topRunningNonDelayedActivityLocked(null) == r;
2081 }
2082 }
2083 if (SHOW_APP_STARTING_PREVIEW && doShow) {
2084 // Figure out if we are transitioning from another activity that is
2085 // "has the same starting icon" as the next one. This allows the
2086 // window manager to keep the previous window it had previously
2087 // created, if it still had one.
2088 ActivityRecord prev = mResumedActivity;
2089 if (prev != null) {
2090 // We don't want to reuse the previous starting preview if:
2091 // (1) The current activity is in a different task.
2092 if (prev.task != r.task) prev = null;
2093 // (2) The current activity is already displayed.
2094 else if (prev.nowVisible) prev = null;
2095 }
2096 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08002097 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07002098 mService.compatibilityInfoForPackageLocked(
2099 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08002100 r.labelRes, r.icon, r.windowFlags,
2101 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002102 }
2103 } else {
2104 // If this is the first activity, don't do any fancy animations,
2105 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08002106 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07002107 r.info.screenOrientation, r.fullscreen,
2108 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002109 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002110 }
2111 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08002112 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002113 }
2114
2115 if (doResume) {
2116 resumeTopActivityLocked(null);
2117 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002118 if (VALIDATE_TASK_REPLACE) {
2119 verifyActivityRecords();
2120 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002121 }
2122
Dianne Hackbornbe707852011-11-11 14:32:10 -08002123 final void validateAppTokensLocked() {
2124 mValidateAppTokens.clear();
2125 mValidateAppTokens.ensureCapacity(mHistory.size());
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08002126 int taskId = Integer.MIN_VALUE;
2127 TaskGroup task = null;
Dianne Hackbornbe707852011-11-11 14:32:10 -08002128 for (int i=0; i<mHistory.size(); i++) {
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08002129 final ActivityRecord r = mHistory.get(i);
2130 if (taskId != r.task.taskId) {
2131 taskId = r.task.taskId;
2132 task = new TaskGroup();
2133 task.taskId = taskId;
2134 mValidateAppTokens.add(task);
2135 }
2136 task.tokens.add(r.appToken);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002137 }
2138 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
2139 }
2140
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002141 /**
2142 * Perform a reset of the given task, if needed as part of launching it.
2143 * Returns the new HistoryRecord at the top of the task.
2144 */
2145 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2146 ActivityRecord newActivity) {
2147 boolean forceReset = (newActivity.info.flags
2148 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002149 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2150 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002151 if ((newActivity.info.flags
2152 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2153 forceReset = true;
2154 }
2155 }
2156
2157 final TaskRecord task = taskTop.task;
2158
2159 // We are going to move through the history list so that we can look
2160 // at each activity 'target' with 'below' either the interesting
2161 // activity immediately below it in the stack or null.
2162 ActivityRecord target = null;
2163 int targetI = 0;
2164 int taskTopI = -1;
2165 int replyChainEnd = -1;
2166 int lastReparentPos = -1;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002167 ActivityOptions topOptions = null;
2168 boolean canMoveOptions = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002169 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002170 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002171
2172 if (below != null && below.finishing) {
2173 continue;
2174 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002175 // Don't check any lower in the stack if we're crossing a user boundary.
2176 if (below != null && below.userId != taskTop.userId) {
2177 break;
2178 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002179 if (target == null) {
2180 target = below;
2181 targetI = i;
2182 // If we were in the middle of a reply chain before this
2183 // task, it doesn't appear like the root of the chain wants
2184 // anything interesting, so drop it.
2185 replyChainEnd = -1;
2186 continue;
2187 }
2188
2189 final int flags = target.info.flags;
2190
2191 final boolean finishOnTaskLaunch =
2192 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2193 final boolean allowTaskReparenting =
2194 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2195
2196 if (target.task == task) {
2197 // We are inside of the task being reset... we'll either
2198 // finish this activity, push it out for another task,
2199 // or leave it as-is. We only do this
2200 // for activities that are not the root of the task (since
2201 // if we finish the root, we may no longer have the task!).
2202 if (taskTopI < 0) {
2203 taskTopI = targetI;
2204 }
2205 if (below != null && below.task == task) {
2206 final boolean clearWhenTaskReset =
2207 (target.intent.getFlags()
2208 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2209 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
2210 // If this activity is sending a reply to a previous
2211 // activity, we can't do anything with it now until
2212 // we reach the start of the reply chain.
2213 // XXX note that we are assuming the result is always
2214 // to the previous activity, which is almost always
2215 // the case but we really shouldn't count on.
2216 if (replyChainEnd < 0) {
2217 replyChainEnd = targetI;
2218 }
2219 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2220 && target.taskAffinity != null
2221 && !target.taskAffinity.equals(task.affinity)) {
2222 // If this activity has an affinity for another
2223 // task, then we need to move it out of here. We will
2224 // move it as far out of the way as possible, to the
2225 // bottom of the activity stack. This also keeps it
2226 // correctly ordered with any activities we previously
2227 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002228 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002229 if (target.taskAffinity != null
2230 && target.taskAffinity.equals(p.task.affinity)) {
2231 // If the activity currently at the bottom has the
2232 // same task affinity as the one we are moving,
2233 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002234 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002235 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2236 + " out to bottom task " + p.task);
2237 } else {
2238 mService.mCurTask++;
2239 if (mService.mCurTask <= 0) {
2240 mService.mCurTask = 1;
2241 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002242 target.setTask(createTaskRecord(mService.mCurTask, target.info, null,
2243 false), null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002244 target.task.affinityIntent = target.intent;
2245 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2246 + " out to new task " + target.task);
2247 }
Craig Mautner926f3832013-02-13 11:56:07 -08002248 mService.mWindowManager.setAppGroupId(target.appToken, target.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002249 if (replyChainEnd < 0) {
2250 replyChainEnd = targetI;
2251 }
2252 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002253 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002254 boolean gotOptions = !canMoveOptions;
Craig Mautner30e2d722013-02-12 11:30:16 -08002255 final int taskId = target.task.taskId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002256 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002257 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002258 if (p.finishing) {
2259 continue;
2260 }
2261 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2262 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002263 p.setTask(target.task, curThumbHolder, false);
2264 curThumbHolder = p.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002265 canMoveOptions = false;
2266 if (!gotOptions && topOptions == null) {
2267 topOptions = p.takeOptionsLocked();
2268 if (topOptions != null) {
2269 gotOptions = true;
2270 }
2271 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002272 if (DEBUG_ADD_REMOVE) {
2273 RuntimeException here = new RuntimeException("here");
2274 here.fillInStackTrace();
2275 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2276 + dstPos, here);
2277 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002278 mHistory.remove(srcPos);
2279 mHistory.add(dstPos, p);
Craig Mautner30e2d722013-02-12 11:30:16 -08002280 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002281 dstPos++;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002282 i++;
2283 }
Craig Mautner30e2d722013-02-12 11:30:16 -08002284 mService.mWindowManager.moveTaskToBottom(taskId);
2285 if (VALIDATE_TOKENS) {
2286 validateAppTokensLocked();
2287 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002288 if (taskTop == p) {
2289 taskTop = below;
2290 }
2291 if (taskTopI == replyChainEnd) {
2292 taskTopI = -1;
2293 }
2294 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002295 } else if (forceReset || finishOnTaskLaunch
2296 || clearWhenTaskReset) {
2297 // If the activity should just be removed -- either
2298 // because it asks for it, or the task should be
2299 // cleared -- then finish it and anything that is
2300 // part of its reply chain.
2301 if (clearWhenTaskReset) {
2302 // In this case, we want to finish this activity
2303 // and everything above it, so be sneaky and pretend
2304 // like these are all in the reply chain.
2305 replyChainEnd = targetI+1;
2306 while (replyChainEnd < mHistory.size() &&
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002307 (mHistory.get(replyChainEnd)).task == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002308 replyChainEnd++;
2309 }
2310 replyChainEnd--;
2311 } else if (replyChainEnd < 0) {
2312 replyChainEnd = targetI;
2313 }
2314 ActivityRecord p = null;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002315 boolean gotOptions = !canMoveOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002316 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002317 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002318 if (p.finishing) {
2319 continue;
2320 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002321 canMoveOptions = false;
2322 if (!gotOptions && topOptions == null) {
2323 topOptions = p.takeOptionsLocked();
2324 if (topOptions != null) {
2325 gotOptions = true;
2326 }
2327 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002328 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002329 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002330 replyChainEnd--;
2331 srcPos--;
2332 }
2333 }
2334 if (taskTop == p) {
2335 taskTop = below;
2336 }
2337 if (taskTopI == replyChainEnd) {
2338 taskTopI = -1;
2339 }
2340 replyChainEnd = -1;
2341 } else {
2342 // If we were in the middle of a chain, well the
2343 // activity that started it all doesn't want anything
2344 // special, so leave it all as-is.
2345 replyChainEnd = -1;
2346 }
2347 } else {
2348 // Reached the bottom of the task -- any reply chain
2349 // should be left as-is.
2350 replyChainEnd = -1;
2351 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002352
2353 } else if (target.resultTo != null && (below == null
2354 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002355 // If this activity is sending a reply to a previous
2356 // activity, we can't do anything with it now until
2357 // we reach the start of the reply chain.
2358 // XXX note that we are assuming the result is always
2359 // to the previous activity, which is almost always
2360 // the case but we really shouldn't count on.
2361 if (replyChainEnd < 0) {
2362 replyChainEnd = targetI;
2363 }
2364
2365 } else if (taskTopI >= 0 && allowTaskReparenting
2366 && task.affinity != null
2367 && task.affinity.equals(target.taskAffinity)) {
2368 // We are inside of another task... if this activity has
2369 // an affinity for our task, then either remove it if we are
2370 // clearing or move it over to our task. Note that
2371 // we currently punt on the case where we are resetting a
2372 // task that is not at the top but who has activities above
2373 // with an affinity to it... this is really not a normal
2374 // case, and we will need to later pull that task to the front
2375 // and usually at that point we will do the reset and pick
2376 // up those remaining activities. (This only happens if
2377 // someone starts an activity in a new task from an activity
2378 // in a task that is not currently on top.)
2379 if (forceReset || finishOnTaskLaunch) {
2380 if (replyChainEnd < 0) {
2381 replyChainEnd = targetI;
2382 }
2383 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002384 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2385 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002386 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002387 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002388 if (p.finishing) {
2389 continue;
2390 }
2391 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002392 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002393 taskTopI--;
2394 lastReparentPos--;
2395 replyChainEnd--;
2396 srcPos--;
2397 }
2398 }
2399 replyChainEnd = -1;
2400 } else {
2401 if (replyChainEnd < 0) {
2402 replyChainEnd = targetI;
2403 }
Craig Mautner30e2d722013-02-12 11:30:16 -08002404 final int taskId = task.taskId;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002405 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2406 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002407 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002408 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002409 if (p.finishing) {
2410 continue;
2411 }
2412 if (lastReparentPos < 0) {
2413 lastReparentPos = taskTopI;
2414 taskTop = p;
2415 } else {
2416 lastReparentPos--;
2417 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002418 if (DEBUG_ADD_REMOVE) {
2419 RuntimeException here = new RuntimeException("here");
2420 here.fillInStackTrace();
2421 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2422 + lastReparentPos, here);
2423 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002424 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002425 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002426 mHistory.add(lastReparentPos, p);
2427 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002428 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002429 + " in to resetting task " + task);
Craig Mautner30e2d722013-02-12 11:30:16 -08002430 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002431 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002432 // TODO: This is wrong because it doesn't take lastReparentPos into account.
Craig Mautner30e2d722013-02-12 11:30:16 -08002433 mService.mWindowManager.moveTaskToTop(taskId);
2434 if (VALIDATE_TOKENS) {
2435 validateAppTokensLocked();
2436 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002437 replyChainEnd = -1;
2438
2439 // Now we've moved it in to place... but what if this is
2440 // a singleTop activity and we have put it on top of another
2441 // instance of the same activity? Then we drop the instance
2442 // below so it remains singleTop.
2443 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2444 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002445 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002446 if (p.finishing) {
2447 continue;
2448 }
2449 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2450 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002451 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002452 taskTopI--;
2453 lastReparentPos--;
2454 }
2455 }
2456 }
2457 }
2458 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002459
2460 } else if (below != null && below.task != target.task) {
2461 // We hit the botton of a task; the reply chain can't
2462 // pass through it.
2463 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002464 }
2465
2466 target = below;
2467 targetI = i;
2468 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002469
2470 if (topOptions != null) {
2471 // If we got some ActivityOptions from an activity on top that
2472 // was removed from the task, propagate them to the new real top.
2473 if (taskTop != null) {
2474 taskTop.updateOptionsLocked(topOptions);
2475 } else {
2476 topOptions.abort();
2477 }
2478 }
2479
Craig Mautner5d9c7be2013-02-15 14:02:56 -08002480 if (VALIDATE_TASK_REPLACE) {
2481 verifyActivityRecords();
2482 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002483 return taskTop;
2484 }
2485
2486 /**
2487 * Perform clear operation as requested by
2488 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2489 * stack to the given task, then look for
2490 * an instance of that activity in the stack and, if found, finish all
2491 * activities on top of it and return the instance.
2492 *
2493 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002494 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002495 * or null if none was found.
2496 */
2497 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002498 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002499 int i = mHistory.size();
2500
2501 // First find the requested task.
2502 while (i > 0) {
2503 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002504 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002505 if (r.task.taskId == taskId) {
2506 i++;
2507 break;
2508 }
2509 }
2510
2511 // Now clear it.
2512 while (i > 0) {
2513 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002514 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515 if (r.finishing) {
2516 continue;
2517 }
2518 if (r.task.taskId != taskId) {
2519 return null;
2520 }
2521 if (r.realActivity.equals(newR.realActivity)) {
2522 // Here it is! Now finish everything in front...
2523 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002524 while (i < (mHistory.size()-1)) {
2525 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002526 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002527 if (r.task.taskId != taskId) {
2528 break;
2529 }
2530 if (r.finishing) {
2531 continue;
2532 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002533 ActivityOptions opts = r.takeOptionsLocked();
2534 if (opts != null) {
2535 ret.updateOptionsLocked(opts);
2536 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002537 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002538 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002539 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002540 }
2541 }
2542
2543 // Finally, if this is a normal launch mode (that is, not
2544 // expecting onNewIntent()), then we will finish the current
2545 // instance of the activity so a new fresh one can be started.
2546 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2547 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2548 if (!ret.finishing) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002549 int index = mHistory.indexOf(ret);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002550 if (index >= 0) {
2551 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002552 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002553 }
2554 return null;
2555 }
2556 }
2557
2558 return ret;
2559 }
2560 }
2561
2562 return null;
2563 }
2564
2565 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002566 * Completely remove all activities associated with an existing
2567 * task starting at a specified index.
2568 */
2569 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002570 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002571 ActivityRecord r = mHistory.get(i);
2572 if (r.task.taskId != taskId) {
2573 // Whoops hit the end.
2574 return;
2575 }
2576 if (r.finishing) {
2577 i++;
2578 continue;
2579 }
2580 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002581 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002582 i++;
2583 }
2584 }
2585 }
2586
2587 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002588 * Completely remove all activities associated with an existing task.
2589 */
2590 private final void performClearTaskLocked(int taskId) {
2591 int i = mHistory.size();
2592
2593 // First find the requested task.
2594 while (i > 0) {
2595 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002596 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002597 if (r.task.taskId == taskId) {
2598 i++;
2599 break;
2600 }
2601 }
2602
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002603 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002604 while (i > 0) {
2605 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002606 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002607 if (r.finishing) {
2608 continue;
2609 }
2610 if (r.task.taskId != taskId) {
2611 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002612 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002613 return;
2614 }
2615 }
2616 }
2617
2618 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002619 * Find the activity in the history stack within the given task. Returns
2620 * the index within the history at which it's found, or < 0 if not found.
2621 */
2622 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2623 int i = mHistory.size();
2624 while (i > 0) {
2625 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002626 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002627 if (candidate.finishing) {
2628 continue;
2629 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002630 if (candidate.task.taskId != task) {
2631 break;
2632 }
2633 if (candidate.realActivity.equals(r.realActivity)) {
2634 return i;
2635 }
2636 }
2637
2638 return -1;
2639 }
2640
2641 /**
2642 * Reorder the history stack so that the activity at the given index is
2643 * brought to the front.
2644 */
2645 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002646 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002647 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002648 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002649 if (DEBUG_ADD_REMOVE) {
2650 RuntimeException here = new RuntimeException("here");
2651 here.fillInStackTrace();
2652 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2653 + top, here);
2654 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002655 mHistory.add(top, newTop);
2656 oldTop.frontOfTask = false;
2657 newTop.frontOfTask = true;
2658 return newTop;
2659 }
2660
2661 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002662 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002663 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002664 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002665 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002666
Dianne Hackborna4972e92012-03-14 10:38:05 -07002667 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002668
2669 ProcessRecord callerApp = null;
2670 if (caller != null) {
2671 callerApp = mService.getRecordForAppLocked(caller);
2672 if (callerApp != null) {
2673 callingPid = callerApp.pid;
2674 callingUid = callerApp.info.uid;
2675 } else {
2676 Slog.w(TAG, "Unable to find app for caller " + caller
2677 + " (pid=" + callingPid + ") when starting: "
2678 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002679 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002680 }
2681 }
2682
Dianne Hackborna4972e92012-03-14 10:38:05 -07002683 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002684 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002685 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2686 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002687 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688
2689 ActivityRecord sourceRecord = null;
2690 ActivityRecord resultRecord = null;
2691 if (resultTo != null) {
2692 int index = indexOfTokenLocked(resultTo);
2693 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002694 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002695 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002696 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002697 if (requestCode >= 0 && !sourceRecord.finishing) {
2698 resultRecord = sourceRecord;
2699 }
2700 }
2701 }
2702
2703 int launchFlags = intent.getFlags();
2704
2705 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2706 && sourceRecord != null) {
2707 // Transfer the result target from the source activity to the new
2708 // one being started, including any failures.
2709 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002710 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002711 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002712 }
2713 resultRecord = sourceRecord.resultTo;
2714 resultWho = sourceRecord.resultWho;
2715 requestCode = sourceRecord.requestCode;
2716 sourceRecord.resultTo = null;
2717 if (resultRecord != null) {
2718 resultRecord.removeResultsLocked(
2719 sourceRecord, resultWho, requestCode);
2720 }
2721 }
2722
Dianne Hackborna4972e92012-03-14 10:38:05 -07002723 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002724 // We couldn't find a class that can handle the given Intent.
2725 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002726 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002727 }
2728
Dianne Hackborna4972e92012-03-14 10:38:05 -07002729 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002730 // We couldn't find the specific class specified in the Intent.
2731 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002732 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002733 }
2734
Dianne Hackborna4972e92012-03-14 10:38:05 -07002735 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002736 if (resultRecord != null) {
2737 sendActivityResultLocked(-1,
2738 resultRecord, resultWho, requestCode,
2739 Activity.RESULT_CANCELED, null);
2740 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002741 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002742 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002743 return err;
2744 }
2745
Jeff Sharkey35be7562012-04-18 19:16:15 -07002746 final int startAnyPerm = mService.checkPermission(
2747 START_ANY_ACTIVITY, callingPid, callingUid);
2748 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002749 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002750 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002751 if (resultRecord != null) {
2752 sendActivityResultLocked(-1,
2753 resultRecord, resultWho, requestCode,
2754 Activity.RESULT_CANCELED, null);
2755 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002756 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002757 String msg;
2758 if (!aInfo.exported) {
2759 msg = "Permission Denial: starting " + intent.toString()
2760 + " from " + callerApp + " (pid=" + callingPid
2761 + ", uid=" + callingUid + ")"
2762 + " not exported from uid " + aInfo.applicationInfo.uid;
2763 } else {
2764 msg = "Permission Denial: starting " + intent.toString()
2765 + " from " + callerApp + " (pid=" + callingPid
2766 + ", uid=" + callingUid + ")"
2767 + " requires " + aInfo.permission;
2768 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002769 Slog.w(TAG, msg);
2770 throw new SecurityException(msg);
2771 }
2772
2773 if (mMainStack) {
2774 if (mService.mController != null) {
2775 boolean abort = false;
2776 try {
2777 // The Intent we give to the watcher has the extra data
2778 // stripped off, since it can contain private information.
2779 Intent watchIntent = intent.cloneFilter();
2780 abort = !mService.mController.activityStarting(watchIntent,
2781 aInfo.applicationInfo.packageName);
2782 } catch (RemoteException e) {
2783 mService.mController = null;
2784 }
2785
2786 if (abort) {
2787 if (resultRecord != null) {
2788 sendActivityResultLocked(-1,
2789 resultRecord, resultWho, requestCode,
2790 Activity.RESULT_CANCELED, null);
2791 }
2792 // We pretend to the caller that it was really started, but
2793 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002794 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002795 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002796 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002797 }
2798 }
2799 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002800
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002801 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002802 intent, resolvedType, aInfo, mService.mConfiguration,
2803 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002804 if (outActivity != null) {
2805 outActivity[0] = r;
2806 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002807
2808 if (mMainStack) {
2809 if (mResumedActivity == null
2810 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2811 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2812 PendingActivityLaunch pal = new PendingActivityLaunch();
2813 pal.r = r;
2814 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002815 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002816 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002817 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002818 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002819 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002820 }
2821 }
2822
2823 if (mService.mDidAppSwitch) {
2824 // This is the second allowed switch since we stopped switches,
2825 // so now just generally allow switches. Use case: user presses
2826 // home (switches disabled, switch to home, mDidAppSwitch now true);
2827 // user taps a home icon (coming from home so allowed, we hit here
2828 // and now allow anyone to switch again).
2829 mService.mAppSwitchesAllowedTime = 0;
2830 } else {
2831 mService.mDidAppSwitch = true;
2832 }
2833
2834 mService.doPendingActivityLaunchesLocked(false);
2835 }
2836
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002837 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002838 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002839 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002840 // Someone asked to have the keyguard dismissed on the next
2841 // activity start, but we are not actually doing an activity
2842 // switch... just dismiss the keyguard now, because we
2843 // probably want to see whatever is behind it.
2844 mDismissKeyguardOnNextActivity = false;
2845 mService.mWindowManager.dismissKeyguard();
2846 }
2847 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002848 }
2849
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002850 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2851 if ((launchFlags &
2852 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2853 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2854 // Caller wants to appear on home activity, so before starting
2855 // their own activity we will bring home to the front.
2856 moveHomeToFrontLocked();
2857 }
2858 }
2859
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002861 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2862 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002863 final Intent intent = r.intent;
2864 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002865
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002866 int launchFlags = intent.getFlags();
2867
2868 // We'll invoke onUserLeaving before onPause only if the launching
2869 // activity did not explicitly state that this is an automated launch.
2870 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2871 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2872 "startActivity() => mUserLeaving=" + mUserLeaving);
2873
2874 // If the caller has asked not to resume at this point, we make note
2875 // of this in the record so that we can skip it when trying to find
2876 // the top running activity.
2877 if (!doResume) {
2878 r.delayedResume = true;
2879 }
2880
2881 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2882 != 0 ? r : null;
2883
2884 // If the onlyIfNeeded flag is set, then we can do this if the activity
2885 // being launched is the same as the one making the call... or, as
2886 // a special case, if we do not know the caller then we count the
2887 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002888 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002889 ActivityRecord checkedCaller = sourceRecord;
2890 if (checkedCaller == null) {
2891 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2892 }
2893 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2894 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002895 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002896 }
2897 }
2898
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002899 if (sourceRecord == null) {
2900 // This activity is not being started from another... in this
2901 // case we -always- start a new task.
2902 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2903 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2904 + intent);
2905 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2906 }
2907 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2908 // The original activity who is starting us is running as a single
2909 // instance... this new activity it is starting must go on its
2910 // own task.
2911 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2912 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2913 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2914 // The activity being started is a single instance... it always
2915 // gets launched into its own task.
2916 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2917 }
2918
2919 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2920 // For whatever reason this activity is being launched into a new
2921 // task... yet the caller has requested a result back. Well, that
2922 // is pretty messed up, so instead immediately send back a cancel
2923 // and let the new task continue launched as normal without a
2924 // dependency on its originator.
2925 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2926 sendActivityResultLocked(-1,
2927 r.resultTo, r.resultWho, r.requestCode,
2928 Activity.RESULT_CANCELED, null);
2929 r.resultTo = null;
2930 }
2931
2932 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002933 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002934 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002935 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2936 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2937 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2938 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2939 // If bring to front is requested, and no result is requested, and
2940 // we can find a task that was started with this same
2941 // component, then instead of launching bring that one to the front.
2942 if (r.resultTo == null) {
2943 // See if there is a task to bring to the front. If this is
2944 // a SINGLE_INSTANCE activity, there can be one and only one
2945 // instance of it in the history, and it is always in its own
2946 // unique task, so we do a special search.
2947 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2948 ? findTaskLocked(intent, r.info)
2949 : findActivityLocked(intent, r.info);
2950 if (taskTop != null) {
2951 if (taskTop.task.intent == null) {
2952 // This task was started because of movement of
2953 // the activity based on affinity... now that we
2954 // are actually launching it, we can assign the
2955 // base intent.
2956 taskTop.task.setIntent(intent, r.info);
2957 }
2958 // If the target task is not in the front, then we need
2959 // to bring it to the front... except... well, with
2960 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2961 // to have the same behavior as if a new instance was
2962 // being started, which means not bringing it to the front
2963 // if the caller is not itself in the front.
2964 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002965 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002966 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2967 boolean callerAtFront = sourceRecord == null
2968 || curTop.task == sourceRecord.task;
2969 if (callerAtFront) {
2970 // We really do want to push this one into the
2971 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002972 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002973 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002974 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002975 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002976 }
2977 }
2978 // If the caller has requested that the target task be
2979 // reset, then do so.
2980 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2981 taskTop = resetTaskIfNeededLocked(taskTop, r);
2982 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002983 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002984 // We don't need to start a new activity, and
2985 // the client said not to do anything if that
2986 // is the case, so this is it! And for paranoia, make
2987 // sure we have correctly resumed the top activity.
2988 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002989 resumeTopActivityLocked(null, options);
2990 } else {
2991 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002992 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002993 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002994 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002995 if ((launchFlags &
2996 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2997 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2998 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002999 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003000 // not be too hard...
3001 reuseTask = taskTop.task;
3002 performClearTaskLocked(taskTop.task.taskId);
3003 reuseTask.setIntent(r.intent, r.info);
3004 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003005 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
3006 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
3007 // In this situation we want to remove all activities
3008 // from the task up to the one being started. In most
3009 // cases this means we are resetting the task to its
3010 // initial state.
3011 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003012 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003013 if (top != null) {
3014 if (top.frontOfTask) {
3015 // Activity aliases may mean we use different
3016 // intents for the top activity, so make sure
3017 // the task now has the identity of the new
3018 // intent.
3019 top.task.setIntent(r.intent, r.info);
3020 }
3021 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003022 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003023 } else {
3024 // A special case: we need to
3025 // start the activity because it is not currently
3026 // running, and the caller has asked to clear the
3027 // current task to have this activity at the top.
3028 addingToTask = true;
3029 // Now pretend like this activity is being started
3030 // by the top of its task, so it is put in the
3031 // right place.
3032 sourceRecord = taskTop;
3033 }
3034 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
3035 // In this case the top activity on the task is the
3036 // same as the one being launched, so we take that
3037 // as a request to bring the task to the foreground.
3038 // If the top activity in the task is the root
3039 // activity, deliver this new intent to it if it
3040 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01003041 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
3042 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003043 && taskTop.realActivity.equals(r.realActivity)) {
3044 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
3045 if (taskTop.frontOfTask) {
3046 taskTop.task.setIntent(r.intent, r.info);
3047 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003048 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003049 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
3050 // In this case we are launching the root activity
3051 // of the task, but with a different intent. We
3052 // should start a new instance on top.
3053 addingToTask = true;
3054 sourceRecord = taskTop;
3055 }
3056 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
3057 // In this case an activity is being launched in to an
3058 // existing task, without resetting that task. This
3059 // is typically the situation of launching an activity
3060 // from a notification or shortcut. We want to place
3061 // the new activity on top of the current task.
3062 addingToTask = true;
3063 sourceRecord = taskTop;
3064 } else if (!taskTop.task.rootWasReset) {
3065 // In this case we are launching in to an existing task
3066 // that has not yet been started from its front door.
3067 // The current task has been brought to the front.
3068 // Ideally, we'd probably like to place this new task
3069 // at the bottom of its stack, but that's a little hard
3070 // to do with the current organization of the code so
3071 // for now we'll just drop it.
3072 taskTop.task.setIntent(r.intent, r.info);
3073 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003074 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003075 // We didn't do anything... but it was needed (a.k.a., client
3076 // don't use that intent!) And for paranoia, make
3077 // sure we have correctly resumed the top activity.
3078 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07003079 resumeTopActivityLocked(null, options);
3080 } else {
3081 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003082 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003083 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003084 }
3085 }
3086 }
3087 }
3088
3089 //String uri = r.intent.toURI();
3090 //Intent intent2 = new Intent(uri);
3091 //Slog.i(TAG, "Given intent: " + r.intent);
3092 //Slog.i(TAG, "URI is: " + uri);
3093 //Slog.i(TAG, "To intent: " + intent2);
3094
3095 if (r.packageName != null) {
3096 // If the activity being launched is the same as the one currently
3097 // at the top, then we need to check if it should only be launched
3098 // once.
3099 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
3100 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07003101 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003102 if (top.app != null && top.app.thread != null) {
3103 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
3104 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
3105 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
3106 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
3107 // For paranoia, make sure we have correctly
3108 // resumed the top activity.
3109 if (doResume) {
3110 resumeTopActivityLocked(null);
3111 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003112 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003113 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003114 // We don't need to start a new activity, and
3115 // the client said not to do anything if that
3116 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07003117 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003118 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003119 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003120 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003121 }
3122 }
3123 }
3124 }
3125
3126 } else {
3127 if (r.resultTo != null) {
3128 sendActivityResultLocked(-1,
3129 r.resultTo, r.resultWho, r.requestCode,
3130 Activity.RESULT_CANCELED, null);
3131 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003132 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003133 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003134 }
3135
3136 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003137 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003138
3139 // Should this be considered a new task?
3140 if (r.resultTo == null && !addingToTask
3141 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003142 if (reuseTask == null) {
3143 // todo: should do better management of integers.
3144 mService.mCurTask++;
3145 if (mService.mCurTask <= 0) {
3146 mService.mCurTask = 1;
3147 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08003148 r.setTask(createTaskRecord(mService.mCurTask, r.info, intent, true), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003149 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3150 + " in new task " + r.task);
3151 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003152 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003153 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003154 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07003155 if (!movedHome) {
3156 moveHomeToFrontFromLaunchLocked(launchFlags);
3157 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003158
3159 } else if (sourceRecord != null) {
3160 if (!addingToTask &&
3161 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3162 // In this case, we are adding the activity to an existing
3163 // task, but the caller has asked to clear that task if the
3164 // activity is already running.
3165 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003166 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003167 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003168 if (top != null) {
3169 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003170 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003171 // For paranoia, make sure we have correctly
3172 // resumed the top activity.
3173 if (doResume) {
3174 resumeTopActivityLocked(null);
3175 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003176 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003177 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003178 }
3179 } else if (!addingToTask &&
3180 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
3181 // In this case, we are launching an activity in our own task
3182 // that may already be running somewhere in the history, and
3183 // we want to shuffle it to the front of the stack if so.
3184 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
3185 if (where >= 0) {
3186 ActivityRecord top = moveActivityToFrontLocked(where);
3187 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003188 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003189 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003190 if (doResume) {
3191 resumeTopActivityLocked(null);
3192 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003193 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003194 }
3195 }
3196 // An existing activity is starting this new activity, so we want
3197 // to keep the new one in the same task as the one that is starting
3198 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003199 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003200 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3201 + " in existing task " + r.task);
3202
3203 } else {
3204 // This not being started from an existing activity, and not part
3205 // of a new task... just put it in the top task, though these days
3206 // this case should never happen.
3207 final int N = mHistory.size();
3208 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003209 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003210 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003211 ? prev.task
Craig Mautner5d9c7be2013-02-15 14:02:56 -08003212 : createTaskRecord(mService.mCurTask, r.info, intent, true), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003213 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3214 + " in new guessed " + r.task);
3215 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003216
Dianne Hackborn39792d22010-08-19 18:01:52 -07003217 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003218 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07003219
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003220 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003221 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003222 }
3223 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003224 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003225 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003226 }
3227
Dianne Hackborna4972e92012-03-14 10:38:05 -07003228 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003229 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003230 // Collect information about the target of the Intent.
3231 ActivityInfo aInfo;
3232 try {
3233 ResolveInfo rInfo =
3234 AppGlobals.getPackageManager().resolveIntent(
3235 intent, resolvedType,
3236 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003237 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003238 aInfo = rInfo != null ? rInfo.activityInfo : null;
3239 } catch (RemoteException e) {
3240 aInfo = null;
3241 }
3242
3243 if (aInfo != null) {
3244 // Store the found target back into the intent, because now that
3245 // we have it we never want to do this again. For example, if the
3246 // user navigates back to this point in the history, we should
3247 // always restart the exact same activity.
3248 intent.setComponent(new ComponentName(
3249 aInfo.applicationInfo.packageName, aInfo.name));
3250
3251 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003252 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003253 if (!aInfo.processName.equals("system")) {
3254 mService.setDebugApp(aInfo.processName, true, false);
3255 }
3256 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003257
Dianne Hackborna4972e92012-03-14 10:38:05 -07003258 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003259 if (!aInfo.processName.equals("system")) {
3260 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3261 }
3262 }
3263
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003264 if (profileFile != null) {
3265 if (!aInfo.processName.equals("system")) {
3266 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003267 profileFile, profileFd,
3268 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003269 }
3270 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003271 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003272 return aInfo;
3273 }
3274
3275 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003276 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003277 String resultWho, int requestCode, int startFlags, String profileFile,
3278 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3279 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003280 // Refuse possible leaked file descriptors
3281 if (intent != null && intent.hasFileDescriptors()) {
3282 throw new IllegalArgumentException("File descriptors passed in Intent");
3283 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003284 boolean componentSpecified = intent.getComponent() != null;
3285
3286 // Don't modify the client's object!
3287 intent = new Intent(intent);
3288
3289 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003290 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003291 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003292
3293 synchronized (mService) {
3294 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003295 if (callingUid >= 0) {
3296 callingPid = -1;
3297 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003298 callingPid = Binder.getCallingPid();
3299 callingUid = Binder.getCallingUid();
3300 } else {
3301 callingPid = callingUid = -1;
3302 }
3303
3304 mConfigWillChange = config != null
3305 && mService.mConfiguration.diff(config) != 0;
3306 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3307 "Starting activity when config will change = " + mConfigWillChange);
3308
3309 final long origId = Binder.clearCallingIdentity();
3310
3311 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003312 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003313 // This may be a heavy-weight process! Check to see if we already
3314 // have another, different heavy-weight process running.
3315 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3316 if (mService.mHeavyWeightProcess != null &&
3317 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3318 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3319 int realCallingPid = callingPid;
3320 int realCallingUid = callingUid;
3321 if (caller != null) {
3322 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3323 if (callerApp != null) {
3324 realCallingPid = callerApp.pid;
3325 realCallingUid = callerApp.info.uid;
3326 } else {
3327 Slog.w(TAG, "Unable to find app for caller " + caller
3328 + " (pid=" + realCallingPid + ") when starting: "
3329 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003330 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003331 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003332 }
3333 }
3334
3335 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003336 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003337 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003338 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003339 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003340
3341 Intent newIntent = new Intent();
3342 if (requestCode >= 0) {
3343 // Caller is requesting a result.
3344 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3345 }
3346 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3347 new IntentSender(target));
3348 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3349 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3350 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3351 hist.packageName);
3352 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3353 hist.task.taskId);
3354 }
3355 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3356 aInfo.packageName);
3357 newIntent.setFlags(intent.getFlags());
3358 newIntent.setClassName("android",
3359 HeavyWeightSwitcherActivity.class.getName());
3360 intent = newIntent;
3361 resolvedType = null;
3362 caller = null;
3363 callingUid = Binder.getCallingUid();
3364 callingPid = Binder.getCallingPid();
3365 componentSpecified = true;
3366 try {
3367 ResolveInfo rInfo =
3368 AppGlobals.getPackageManager().resolveIntent(
3369 intent, null,
3370 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003371 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003372 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003373 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003374 } catch (RemoteException e) {
3375 aInfo = null;
3376 }
3377 }
3378 }
3379 }
3380
3381 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003382 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003383 callingPackage, startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003384
3385 if (mConfigWillChange && mMainStack) {
3386 // If the caller also wants to switch to a new configuration,
3387 // do so now. This allows a clean switch, as we are waiting
3388 // for the current activity to pause (so we will not destroy
3389 // it), and have not yet started the next activity.
3390 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3391 "updateConfiguration()");
3392 mConfigWillChange = false;
3393 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3394 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003395 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003396 }
3397
3398 Binder.restoreCallingIdentity(origId);
3399
3400 if (outResult != null) {
3401 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003402 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003403 mWaitingActivityLaunched.add(outResult);
3404 do {
3405 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003406 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003407 } catch (InterruptedException e) {
3408 }
3409 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003410 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003411 ActivityRecord r = this.topRunningActivityLocked(null);
3412 if (r.nowVisible) {
3413 outResult.timeout = false;
3414 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3415 outResult.totalTime = 0;
3416 outResult.thisTime = 0;
3417 } else {
3418 outResult.thisTime = SystemClock.uptimeMillis();
3419 mWaitingActivityVisible.add(outResult);
3420 do {
3421 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003422 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003423 } catch (InterruptedException e) {
3424 }
3425 } while (!outResult.timeout && outResult.who == null);
3426 }
3427 }
3428 }
3429
3430 return res;
3431 }
3432 }
3433
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003434 final int startActivities(IApplicationThread caller, int callingUid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003435 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3436 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003437 if (intents == null) {
3438 throw new NullPointerException("intents is null");
3439 }
3440 if (resolvedTypes == null) {
3441 throw new NullPointerException("resolvedTypes is null");
3442 }
3443 if (intents.length != resolvedTypes.length) {
3444 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3445 }
3446
3447 ActivityRecord[] outActivity = new ActivityRecord[1];
3448
3449 int callingPid;
3450 if (callingUid >= 0) {
3451 callingPid = -1;
3452 } else if (caller == null) {
3453 callingPid = Binder.getCallingPid();
3454 callingUid = Binder.getCallingUid();
3455 } else {
3456 callingPid = callingUid = -1;
3457 }
3458 final long origId = Binder.clearCallingIdentity();
3459 try {
3460 synchronized (mService) {
3461
3462 for (int i=0; i<intents.length; i++) {
3463 Intent intent = intents[i];
3464 if (intent == null) {
3465 continue;
3466 }
3467
3468 // Refuse possible leaked file descriptors
3469 if (intent != null && intent.hasFileDescriptors()) {
3470 throw new IllegalArgumentException("File descriptors passed in Intent");
3471 }
3472
3473 boolean componentSpecified = intent.getComponent() != null;
3474
3475 // Don't modify the client's object!
3476 intent = new Intent(intent);
3477
3478 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003479 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003480 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003481 // TODO: New, check if this is correct
3482 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003483
3484 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3485 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3486 throw new IllegalArgumentException(
3487 "FLAG_CANT_SAVE_STATE not supported here");
3488 }
3489
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003490 Bundle theseOptions;
3491 if (options != null && i == intents.length-1) {
3492 theseOptions = options;
3493 } else {
3494 theseOptions = null;
3495 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003496 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003497 aInfo, resultTo, null, -1, callingPid, callingUid, callingPackage,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003498 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003499 if (res < 0) {
3500 return res;
3501 }
3502
Dianne Hackbornbe707852011-11-11 14:32:10 -08003503 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003504 }
3505 }
3506 } finally {
3507 Binder.restoreCallingIdentity(origId);
3508 }
3509
Dianne Hackborna4972e92012-03-14 10:38:05 -07003510 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003511 }
3512
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003513 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3514 long thisTime, long totalTime) {
3515 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3516 WaitResult w = mWaitingActivityLaunched.get(i);
3517 w.timeout = timeout;
3518 if (r != null) {
3519 w.who = new ComponentName(r.info.packageName, r.info.name);
3520 }
3521 w.thisTime = thisTime;
3522 w.totalTime = totalTime;
3523 }
3524 mService.notifyAll();
3525 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003526
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003527 void reportActivityVisibleLocked(ActivityRecord r) {
3528 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3529 WaitResult w = mWaitingActivityVisible.get(i);
3530 w.timeout = false;
3531 if (r != null) {
3532 w.who = new ComponentName(r.info.packageName, r.info.name);
3533 }
3534 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3535 w.thisTime = w.totalTime;
3536 }
3537 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003538
3539 if (mDismissKeyguardOnNextActivity) {
3540 mDismissKeyguardOnNextActivity = false;
3541 mService.mWindowManager.dismissKeyguard();
3542 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003543 }
3544
3545 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3546 String resultWho, int requestCode, int resultCode, Intent data) {
3547
3548 if (callingUid > 0) {
3549 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003550 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003551 }
3552
3553 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3554 + " : who=" + resultWho + " req=" + requestCode
3555 + " res=" + resultCode + " data=" + data);
3556 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3557 try {
3558 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3559 list.add(new ResultInfo(resultWho, requestCode,
3560 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003561 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003562 return;
3563 } catch (Exception e) {
3564 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3565 }
3566 }
3567
3568 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3569 }
3570
3571 private final void stopActivityLocked(ActivityRecord r) {
3572 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3573 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3574 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3575 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003576 if (!mService.mSleeping) {
3577 if (DEBUG_STATES) {
3578 Slog.d(TAG, "no-history finish of " + r);
3579 }
3580 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003581 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003582 } else {
3583 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3584 + " on stop because we're just sleeping");
3585 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003586 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003587 }
3588
3589 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003590 if (mMainStack) {
3591 if (mService.mFocusedActivity == r) {
3592 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3593 }
3594 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003595 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003596 try {
3597 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003598 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3599 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003600 r.state = ActivityState.STOPPING;
3601 if (DEBUG_VISBILITY) Slog.v(
3602 TAG, "Stopping visible=" + r.visible + " for " + r);
3603 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003604 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003605 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003606 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003607 if (mService.isSleeping()) {
3608 r.setSleeping(true);
3609 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003610 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3611 msg.obj = r;
3612 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003613 } catch (Exception e) {
3614 // Maybe just ignore exceptions here... if the process
3615 // has crashed, our death notification will clean things
3616 // up.
3617 Slog.w(TAG, "Exception thrown during pause", e);
3618 // Just in case, assume it to be stopped.
3619 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003620 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003621 r.state = ActivityState.STOPPED;
3622 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003623 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003624 }
3625 }
3626 }
3627 }
3628
3629 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3630 boolean remove) {
3631 int N = mStoppingActivities.size();
3632 if (N <= 0) return null;
3633
3634 ArrayList<ActivityRecord> stops = null;
3635
3636 final boolean nowVisible = mResumedActivity != null
3637 && mResumedActivity.nowVisible
3638 && !mResumedActivity.waitingVisible;
3639 for (int i=0; i<N; i++) {
3640 ActivityRecord s = mStoppingActivities.get(i);
3641 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3642 + nowVisible + " waitingVisible=" + s.waitingVisible
3643 + " finishing=" + s.finishing);
3644 if (s.waitingVisible && nowVisible) {
3645 mWaitingVisibleActivities.remove(s);
3646 s.waitingVisible = false;
3647 if (s.finishing) {
3648 // If this activity is finishing, it is sitting on top of
3649 // everyone else but we now know it is no longer needed...
3650 // so get rid of it. Otherwise, we need to go through the
3651 // normal flow and hide it once we determine that it is
3652 // hidden by the activities in front of it.
3653 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003654 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003655 }
3656 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003657 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003658 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3659 if (stops == null) {
3660 stops = new ArrayList<ActivityRecord>();
3661 }
3662 stops.add(s);
3663 mStoppingActivities.remove(i);
3664 N--;
3665 i--;
3666 }
3667 }
3668
3669 return stops;
3670 }
3671
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003672 final void scheduleIdleLocked() {
3673 Message msg = Message.obtain();
3674 msg.what = IDLE_NOW_MSG;
3675 mHandler.sendMessage(msg);
3676 }
3677
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003678 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003679 Configuration config) {
3680 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3681
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003682 ActivityRecord res = null;
3683
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003684 ArrayList<ActivityRecord> stops = null;
3685 ArrayList<ActivityRecord> finishes = null;
3686 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003687 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003688 int NS = 0;
3689 int NF = 0;
3690 int NT = 0;
3691 IApplicationThread sendThumbnail = null;
3692 boolean booting = false;
3693 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003694 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003695
3696 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003697 ActivityRecord r = ActivityRecord.forToken(token);
3698 if (r != null) {
3699 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003700 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003701 }
3702
3703 // Get the activity record.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003704 int index = mHistory.indexOf(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003705 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003706 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003707
3708 if (fromTimeout) {
3709 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3710 }
3711
3712 // This is a hack to semi-deal with a race condition
3713 // in the client where it can be constructed with a
3714 // newer configuration from when we asked it to launch.
3715 // We'll update with whatever configuration it now says
3716 // it used to launch.
3717 if (config != null) {
3718 r.configuration = config;
3719 }
3720
3721 // No longer need to keep the device awake.
3722 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3723 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3724 mLaunchingActivity.release();
3725 }
3726
3727 // We are now idle. If someone is waiting for a thumbnail from
3728 // us, we can now deliver.
3729 r.idle = true;
3730 mService.scheduleAppGcsLocked();
3731 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3732 sendThumbnail = r.app.thread;
3733 r.thumbnailNeeded = false;
3734 }
3735
3736 // If this activity is fullscreen, set up to hide those under it.
3737
3738 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3739 ensureActivitiesVisibleLocked(null, 0);
3740
3741 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3742 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003743 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003744 mService.mBooted = true;
3745 enableScreen = true;
3746 }
3747 }
3748
3749 } else if (fromTimeout) {
3750 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3751 }
3752
3753 // Atomically retrieve all of the other things to do.
3754 stops = processStoppingActivitiesLocked(true);
3755 NS = stops != null ? stops.size() : 0;
3756 if ((NF=mFinishingActivities.size()) > 0) {
3757 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3758 mFinishingActivities.clear();
3759 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003760 if ((NT=mCancelledThumbnails.size()) > 0) {
3761 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3762 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003763 }
3764
3765 if (mMainStack) {
3766 booting = mService.mBooting;
3767 mService.mBooting = false;
3768 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003769 if (mStartingUsers.size() > 0) {
3770 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3771 mStartingUsers.clear();
3772 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003773 }
3774
3775 int i;
3776
3777 // Send thumbnail if requested.
3778 if (sendThumbnail != null) {
3779 try {
3780 sendThumbnail.requestThumbnail(token);
3781 } catch (Exception e) {
3782 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3783 mService.sendPendingThumbnail(null, token, null, null, true);
3784 }
3785 }
3786
3787 // Stop any activities that are scheduled to do so but have been
3788 // waiting for the next one to start.
3789 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003790 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003791 synchronized (mService) {
3792 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003793 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003794 } else {
3795 stopActivityLocked(r);
3796 }
3797 }
3798 }
3799
3800 // Finish any activities that are scheduled to do so but have been
3801 // waiting for the next one to start.
3802 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003803 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003804 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003805 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003806 }
3807 }
3808
3809 // Report back to any thumbnail receivers.
3810 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003811 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003812 mService.sendPendingThumbnail(r, null, null, null, true);
3813 }
3814
3815 if (booting) {
3816 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003817 } else if (startingUsers != null) {
3818 for (i=0; i<startingUsers.size(); i++) {
3819 mService.finishUserSwitch(startingUsers.get(i));
3820 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003821 }
3822
3823 mService.trimApplications();
3824 //dump();
3825 //mWindowManager.dump();
3826
3827 if (enableScreen) {
3828 mService.enableScreenAfterBoot();
3829 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003830
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003831 if (activityRemoved) {
3832 resumeTopActivityLocked(null);
3833 }
3834
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003835 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003836 }
3837
3838 /**
3839 * @return Returns true if the activity is being finished, false if for
3840 * some reason it is being left as-is.
3841 */
3842 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003843 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003844 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003845 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003846 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003847 + ", result=" + resultCode + ", data=" + resultData
3848 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003849 if (index < 0) {
3850 return false;
3851 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003852 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003853
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003854 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003855 return true;
3856 }
3857
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003858 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3859 ActivityRecord self = isInStackLocked(token);
3860 if (self == null) {
3861 return;
3862 }
3863
3864 int i;
3865 for (i=mHistory.size()-1; i>=0; i--) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003866 ActivityRecord r = mHistory.get(i);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003867 if (r.resultTo == self && r.requestCode == requestCode) {
3868 if ((r.resultWho == null && resultWho == null) ||
3869 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3870 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003871 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003872 }
3873 }
3874 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003875 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003876 }
3877
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003878 final void finishTopRunningActivityLocked(ProcessRecord app) {
3879 ActivityRecord r = topRunningActivityLocked(null);
3880 if (r != null && r.app == app) {
3881 // If the top running activity is from this crashing
3882 // process, then terminate it to avoid getting in a loop.
3883 Slog.w(TAG, " Force finishing activity "
3884 + r.intent.getComponent().flattenToShortString());
3885 int index = mHistory.indexOf(r);
3886 r.stack.finishActivityLocked(r, index,
3887 Activity.RESULT_CANCELED, null, "crashed", false);
3888 // Also terminate any activities below it that aren't yet
3889 // stopped, to avoid a situation where one will get
3890 // re-start our crashing activity once it gets resumed again.
3891 index--;
3892 if (index >= 0) {
3893 r = mHistory.get(index);
3894 if (r.state == ActivityState.RESUMED
3895 || r.state == ActivityState.PAUSING
3896 || r.state == ActivityState.PAUSED) {
3897 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3898 Slog.w(TAG, " Force finishing activity "
3899 + r.intent.getComponent().flattenToShortString());
3900 r.stack.finishActivityLocked(r, index,
3901 Activity.RESULT_CANCELED, null, "crashed", false);
3902 }
3903 }
3904 }
3905 }
3906 }
3907
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003908 final boolean finishActivityAffinityLocked(IBinder token) {
3909 int index = indexOfTokenLocked(token);
3910 if (DEBUG_RESULTS) Slog.v(
3911 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3912 if (index < 0) {
3913 return false;
3914 }
3915 ActivityRecord r = mHistory.get(index);
3916
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003917 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003918 ActivityRecord cur = mHistory.get(index);
3919 if (cur.task != r.task) {
3920 break;
3921 }
3922 if (cur.taskAffinity == null && r.taskAffinity != null) {
3923 break;
3924 }
3925 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3926 break;
3927 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003928 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3929 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003930 index--;
3931 }
3932 return true;
3933 }
3934
Dianne Hackborn5c607432012-02-28 14:44:19 -08003935 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3936 // send the result
3937 ActivityRecord resultTo = r.resultTo;
3938 if (resultTo != null) {
3939 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3940 + " who=" + r.resultWho + " req=" + r.requestCode
3941 + " res=" + resultCode + " data=" + resultData);
3942 if (r.info.applicationInfo.uid > 0) {
3943 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3944 resultTo.packageName, resultData,
3945 resultTo.getUriPermissionsLocked());
3946 }
3947 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3948 resultData);
3949 r.resultTo = null;
3950 }
3951 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3952
3953 // Make sure this HistoryRecord is not holding on to other resources,
3954 // because clients have remote IPC references to this object so we
3955 // can't assume that will go away and want to avoid circular IPC refs.
3956 r.results = null;
3957 r.pendingResults = null;
3958 r.newIntents = null;
3959 r.icicle = null;
3960 }
3961
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003962 /**
3963 * @return Returns true if this activity has been removed from the history
3964 * list, or false if it is still in the list and will be removed later.
3965 */
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003966 final boolean finishActivityLocked(ActivityRecord r,
3967 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3968 int index = mHistory.indexOf(r);
3969 if (index >= 0) {
3970 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
3971 }
3972 return false;
3973 }
3974
3975 /**
3976 * @return Returns true if this activity has been removed from the history
3977 * list, or false if it is still in the list and will be removed later.
3978 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003979 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003980 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3981 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003982 }
3983
3984 /**
3985 * @return Returns true if this activity has been removed from the history
3986 * list, or false if it is still in the list and will be removed later.
3987 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003988 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3989 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003990 if (r.finishing) {
3991 Slog.w(TAG, "Duplicate finish request for " + r);
3992 return false;
3993 }
3994
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003995 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003996 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003997 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003998 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003999 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004000 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004001 if (next.task == r.task) {
4002 if (r.frontOfTask) {
4003 // The next activity is now the front of the task.
4004 next.frontOfTask = true;
4005 }
4006 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
4007 // If the caller asked that this activity (and all above it)
4008 // be cleared when the task is reset, don't lose that information,
4009 // but propagate it up to the next activity.
4010 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
4011 }
4012 }
4013 }
4014
4015 r.pauseKeyDispatchingLocked();
4016 if (mMainStack) {
4017 if (mService.mFocusedActivity == r) {
4018 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
4019 }
4020 }
4021
Dianne Hackborn5c607432012-02-28 14:44:19 -08004022 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004023
4024 if (mService.mPendingThumbnails.size() > 0) {
4025 // There are clients waiting to receive thumbnails so, in case
4026 // this is an activity that someone is waiting for, add it
4027 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004028 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004029 }
4030
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004031 if (immediate) {
4032 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004033 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004034 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004035 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004036 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004037 if (DEBUG_TRANSITION) Slog.v(TAG,
4038 "Prepare close transition: finishing " + r);
4039 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08004040 ? AppTransition.TRANSIT_TASK_CLOSE
4041 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004042
4043 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08004044 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004045
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08004046 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004047 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
4048 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
4049 startPausingLocked(false, false);
4050 }
4051
4052 } else if (r.state != ActivityState.PAUSING) {
4053 // If the activity is PAUSING, we will complete the finish once
4054 // it is done pausing; else we can just directly finish it here.
4055 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
4056 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004057 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004058 } else {
4059 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
4060 }
4061
4062 return false;
4063 }
4064
4065 private static final int FINISH_IMMEDIATELY = 0;
4066 private static final int FINISH_AFTER_PAUSE = 1;
4067 private static final int FINISH_AFTER_VISIBLE = 2;
4068
4069 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004070 int mode, boolean oomAdj) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004071 final int index = mHistory.indexOf(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004072 if (index < 0) {
4073 return null;
4074 }
4075
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004076 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004077 }
4078
4079 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004080 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004081 // First things first: if this activity is currently visible,
4082 // and the resumed activity is not yet visible, then hold off on
4083 // finishing until the resumed one becomes visible.
4084 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
4085 if (!mStoppingActivities.contains(r)) {
4086 mStoppingActivities.add(r);
4087 if (mStoppingActivities.size() > 3) {
4088 // If we already have a few activities waiting to stop,
4089 // then give up on things going idle and start clearing
4090 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07004091 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004092 } else {
4093 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004094 }
4095 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004096 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
4097 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004098 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004099 if (oomAdj) {
4100 mService.updateOomAdjLocked();
4101 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004102 return r;
4103 }
4104
4105 // make sure the record is cleaned out of other places.
4106 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08004107 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004108 mWaitingVisibleActivities.remove(r);
4109 if (mResumedActivity == r) {
4110 mResumedActivity = null;
4111 }
4112 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004113 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004114 r.state = ActivityState.FINISHING;
4115
4116 if (mode == FINISH_IMMEDIATELY
4117 || prevState == ActivityState.STOPPED
4118 || prevState == ActivityState.INITIALIZING) {
4119 // If this activity is already stopped, we can just finish
4120 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004121 boolean activityRemoved = destroyActivityLocked(r, true,
4122 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004123 if (activityRemoved) {
4124 resumeTopActivityLocked(null);
4125 }
4126 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004127 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004128
4129 // Need to go through the full pause cycle to get this
4130 // activity into the stopped state and then finish it.
4131 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
4132 mFinishingActivities.add(r);
4133 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004134 return r;
4135 }
4136
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004137 final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
4138 Intent resultData) {
4139 final int start = mHistory.indexOf(srec);
4140 if (start < 0) {
4141 // Current activity is not in history stack; do nothing.
4142 return false;
4143 }
4144 int finishTo = start - 1;
4145 ActivityRecord parent = null;
4146 boolean foundParentInTask = false;
4147 ComponentName dest = destIntent.getComponent();
4148 if (dest != null) {
4149 TaskRecord tr = srec.task;
4150 for (int i = start - 1; i >= 0; i--) {
4151 ActivityRecord r = mHistory.get(i);
4152 if (tr != r.task) {
4153 // Couldn't find parent in the same task; stop at the one above this.
4154 // (Root of current task; in-app "home" behavior)
4155 // Always at least finish the current activity.
4156 finishTo = Math.min(start - 1, i + 1);
4157 parent = mHistory.get(finishTo);
4158 break;
4159 } else if (r.info.packageName.equals(dest.getPackageName()) &&
4160 r.info.name.equals(dest.getClassName())) {
4161 finishTo = i;
4162 parent = r;
4163 foundParentInTask = true;
4164 break;
4165 }
4166 }
4167 }
4168
4169 IActivityController controller = mService.mController;
4170 if (controller != null) {
4171 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
4172 if (next != null) {
4173 // ask watcher if this is allowed
4174 boolean resumeOK = true;
4175 try {
4176 resumeOK = controller.activityResuming(next.packageName);
4177 } catch (RemoteException e) {
4178 mService.mController = null;
4179 }
4180
4181 if (!resumeOK) {
4182 return false;
4183 }
4184 }
4185 }
4186 final long origId = Binder.clearCallingIdentity();
4187 for (int i = start; i > finishTo; i--) {
4188 ActivityRecord r = mHistory.get(i);
4189 requestFinishActivityLocked(r.appToken, resultCode, resultData,
4190 "navigate-up", true);
4191 // Only return the supplied result for the first activity finished
4192 resultCode = Activity.RESULT_CANCELED;
4193 resultData = null;
4194 }
4195
4196 if (parent != null && foundParentInTask) {
4197 final int parentLaunchMode = parent.info.launchMode;
4198 final int destIntentFlags = destIntent.getFlags();
4199 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
4200 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
4201 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
4202 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
4203 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
4204 } else {
4205 try {
4206 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
4207 destIntent.getComponent(), 0, srec.userId);
4208 int res = startActivityLocked(srec.app.thread, destIntent,
4209 null, aInfo, parent.appToken, null,
4210 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
4211 0, null, true, null);
4212 foundParentInTask = res == ActivityManager.START_SUCCESS;
4213 } catch (RemoteException e) {
4214 foundParentInTask = false;
4215 }
4216 requestFinishActivityLocked(parent.appToken, resultCode,
4217 resultData, "navigate-up", true);
4218 }
4219 }
4220 Binder.restoreCallingIdentity(origId);
4221 return foundParentInTask;
4222 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004223 /**
4224 * Perform the common clean-up of an activity record. This is called both
4225 * as part of destroyActivityLocked() (when destroying the client-side
4226 * representation) and cleaning things up as a result of its hosting
4227 * processing going away, in which case there is no remaining client-side
4228 * state to destroy so only the cleanup here is needed.
4229 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004230 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
4231 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004232 if (mResumedActivity == r) {
4233 mResumedActivity = null;
4234 }
4235 if (mService.mFocusedActivity == r) {
4236 mService.mFocusedActivity = null;
4237 }
4238
4239 r.configDestroy = false;
4240 r.frozenBeforeDestroy = false;
4241
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004242 if (setState) {
4243 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
4244 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004245 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004246 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004247 }
4248
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004249 // Make sure this record is no longer in the pending finishes list.
4250 // This could happen, for example, if we are trimming activities
4251 // down to the max limit while they are still waiting to finish.
4252 mFinishingActivities.remove(r);
4253 mWaitingVisibleActivities.remove(r);
4254
4255 // Remove any pending results.
4256 if (r.finishing && r.pendingResults != null) {
4257 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
4258 PendingIntentRecord rec = apr.get();
4259 if (rec != null) {
4260 mService.cancelIntentSenderLocked(rec, false);
4261 }
4262 }
4263 r.pendingResults = null;
4264 }
4265
4266 if (cleanServices) {
4267 cleanUpActivityServicesLocked(r);
4268 }
4269
4270 if (mService.mPendingThumbnails.size() > 0) {
4271 // There are clients waiting to receive thumbnails so, in case
4272 // this is an activity that someone is waiting for, add it
4273 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004274 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004275 }
4276
4277 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004278 removeTimeoutsForActivityLocked(r);
4279 }
4280
4281 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004282 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004283 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004284 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004285 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004286 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004287 }
4288
Dianne Hackborn5c607432012-02-28 14:44:19 -08004289 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004290 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4291 r.makeFinishing();
4292 if (DEBUG_ADD_REMOVE) {
4293 RuntimeException here = new RuntimeException("here");
4294 here.fillInStackTrace();
4295 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004296 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08004297 if (r.task != null) {
4298 r.task.removeActivity(r);
4299 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004300 mHistory.remove(r);
4301 r.takeFromHistory();
4302 removeTimeoutsForActivityLocked(r);
4303 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4304 + " (removed from history)");
4305 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004306 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004307 r.app = null;
4308 mService.mWindowManager.removeAppToken(r.appToken);
4309 if (VALIDATE_TOKENS) {
4310 validateAppTokensLocked();
4311 }
4312 cleanUpActivityServicesLocked(r);
4313 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004314 }
4315
4316 /**
4317 * Perform clean-up of service connections in an activity record.
4318 */
4319 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4320 // Throw away any services that have been bound by this activity.
4321 if (r.connections != null) {
4322 Iterator<ConnectionRecord> it = r.connections.iterator();
4323 while (it.hasNext()) {
4324 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004325 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004326 }
4327 r.connections = null;
4328 }
4329 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004330
4331 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4332 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4333 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4334 mHandler.sendMessage(msg);
4335 }
4336
Dianne Hackborn28695e02011-11-02 21:59:51 -07004337 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004338 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004339 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004340 for (int i=mHistory.size()-1; i>=0; i--) {
4341 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004342 if (r.finishing) {
4343 continue;
4344 }
4345 if (r.fullscreen) {
4346 lastIsOpaque = true;
4347 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004348 if (owner != null && r.app != owner) {
4349 continue;
4350 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004351 if (!lastIsOpaque) {
4352 continue;
4353 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004354 // We can destroy this one if we have its icicle saved and
4355 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004356 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4357 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004358 && r.state != ActivityState.DESTROYING
4359 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004360 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4361 + " resumed=" + mResumedActivity
4362 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004363 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4364 activityRemoved = true;
4365 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004366 }
4367 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004368 if (activityRemoved) {
4369 resumeTopActivityLocked(null);
4370 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004371 }
4372
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004373 /**
4374 * Destroy the current CLIENT SIDE instance of an activity. This may be
4375 * called both when actually finishing an activity, or when performing
4376 * a configuration switch where we destroy the current client-side object
4377 * but then create a new client-side object for this same HistoryRecord.
4378 */
4379 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004380 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004381 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004382 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004383 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4384 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004385 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004386 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004387
4388 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004389
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004390 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004391
4392 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004393
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004394 if (hadApp) {
4395 if (removeFromApp) {
4396 int idx = r.app.activities.indexOf(r);
4397 if (idx >= 0) {
4398 r.app.activities.remove(idx);
4399 }
4400 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4401 mService.mHeavyWeightProcess = null;
4402 mService.mHandler.sendEmptyMessage(
4403 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4404 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004405 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004406 // No longer have activities, so update oom adj.
4407 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004408 }
4409 }
4410
4411 boolean skipDestroy = false;
4412
4413 try {
4414 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004415 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004416 r.configChangeFlags);
4417 } catch (Exception e) {
4418 // We can just ignore exceptions here... if the process
4419 // has crashed, our death notification will clean things
4420 // up.
4421 //Slog.w(TAG, "Exception thrown during finish", e);
4422 if (r.finishing) {
4423 removeActivityFromHistoryLocked(r);
4424 removedFromHistory = true;
4425 skipDestroy = true;
4426 }
4427 }
4428
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004429 r.nowVisible = false;
4430
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004431 // If the activity is finishing, we need to wait on removing it
4432 // from the list to give it a chance to do its cleanup. During
4433 // that time it may make calls back with its token so we need to
4434 // be able to find it on the list and so we don't want to remove
4435 // it from the list yet. Otherwise, we can just immediately put
4436 // it in the destroyed state since we are not removing it from the
4437 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004438 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004439 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4440 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004441 r.state = ActivityState.DESTROYING;
4442 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4443 msg.obj = r;
4444 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4445 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004446 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4447 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004448 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004449 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004450 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004451 }
4452 } else {
4453 // remove this record from the history.
4454 if (r.finishing) {
4455 removeActivityFromHistoryLocked(r);
4456 removedFromHistory = true;
4457 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004458 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4459 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004460 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004461 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004462 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004463 }
4464 }
4465
4466 r.configChangeFlags = 0;
4467
4468 if (!mLRUActivities.remove(r) && hadApp) {
4469 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4470 }
4471
4472 return removedFromHistory;
4473 }
4474
4475 final void activityDestroyed(IBinder token) {
4476 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004477 final long origId = Binder.clearCallingIdentity();
4478 try {
4479 ActivityRecord r = ActivityRecord.forToken(token);
4480 if (r != null) {
4481 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004482 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004483
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004484 int index = mHistory.indexOf(r);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004485 if (index >= 0) {
4486 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004487 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004488 removeActivityFromHistoryLocked(r);
4489 }
4490 }
4491 resumeTopActivityLocked(null);
4492 } finally {
4493 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004494 }
4495 }
4496 }
4497
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004498 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4499 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004500 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004501 if (DEBUG_CLEANUP) Slog.v(
4502 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004503 + " with " + i + " entries");
4504 while (i > 0) {
4505 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004506 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004507 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004508 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004509 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004510 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004511 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004512 }
4513 }
4514 }
4515
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004516 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4517 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4518 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4519 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4520 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4521 "mWaitingVisibleActivities");
4522 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4523
4524 boolean hasVisibleActivities = false;
4525
4526 // Clean out the history list.
4527 int i = mHistory.size();
4528 if (DEBUG_CLEANUP) Slog.v(
4529 TAG, "Removing app " + app + " from history with " + i + " entries");
4530 while (i > 0) {
4531 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004532 ActivityRecord r = mHistory.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004533 if (DEBUG_CLEANUP) Slog.v(
4534 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4535 if (r.app == app) {
Dianne Hackborn07981492013-01-28 11:36:23 -08004536 boolean remove;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004537 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn07981492013-01-28 11:36:23 -08004538 // Don't currently have state for the activity, or
4539 // it is finishing -- always remove it.
4540 remove = true;
4541 } else if (r.launchCount > 2 &&
4542 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4543 // We have launched this activity too many times since it was
4544 // able to run, so give up and remove it.
4545 remove = true;
4546 } else {
4547 // The process may be gone, but the activity lives on!
4548 remove = false;
4549 }
4550 if (remove) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004551 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4552 RuntimeException here = new RuntimeException("here");
4553 here.fillInStackTrace();
4554 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4555 + ": haveState=" + r.haveState
4556 + " stateNotNeeded=" + r.stateNotNeeded
4557 + " finishing=" + r.finishing
4558 + " state=" + r.state, here);
4559 }
4560 if (!r.finishing) {
4561 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4562 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4563 r.userId, System.identityHashCode(r),
4564 r.task.taskId, r.shortComponentName,
4565 "proc died without state saved");
4566 }
4567 removeActivityFromHistoryLocked(r);
4568
4569 } else {
4570 // We have the current state for this activity, so
4571 // it can be restarted later when needed.
4572 if (localLOGV) Slog.v(
4573 TAG, "Keeping entry, setting app to null");
4574 if (r.visible) {
4575 hasVisibleActivities = true;
4576 }
Dianne Hackborn07981492013-01-28 11:36:23 -08004577 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4578 + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004579 r.app = null;
4580 r.nowVisible = false;
4581 if (!r.haveState) {
4582 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4583 "App died, clearing saved state of " + r);
4584 r.icicle = null;
4585 }
4586 }
4587
4588 r.stack.cleanUpActivityLocked(r, true, true);
4589 }
4590 }
4591
4592 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004593 }
4594
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004595 /**
4596 * Move the current home activity's task (if one exists) to the front
4597 * of the stack.
4598 */
4599 final void moveHomeToFrontLocked() {
4600 TaskRecord homeTask = null;
4601 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004602 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004603 if (hr.isHomeActivity) {
4604 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004605 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004606 }
4607 }
4608 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004609 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004610 }
4611 }
4612
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004613 final void updateTransitLocked(int transit, Bundle options) {
4614 if (options != null) {
4615 ActivityRecord r = topRunningActivityLocked(null);
4616 if (r != null && r.state != ActivityState.RESUMED) {
4617 r.updateOptionsLocked(options);
4618 } else {
4619 ActivityOptions.abort(options);
4620 }
4621 }
4622 mService.mWindowManager.prepareAppTransition(transit, false);
4623 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004624
Craig Mautnercae015f2013-02-08 14:31:27 -08004625 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
4626 for (int i = mHistory.size() - 1; i >= 0; i--) {
4627 ActivityRecord hr = mHistory.get(i);
4628 if (hr.task.taskId == taskId) {
4629 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4630 mUserLeaving = true;
4631 }
4632 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4633 // Caller wants the home activity moved with it. To accomplish this,
4634 // we'll just move the home task to the top first.
4635 moveHomeToFrontLocked();
4636 }
4637 moveTaskToFrontLocked(hr.task, null, options);
4638 return true;
4639 }
4640 }
4641 return false;
4642 }
4643
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004644 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004645 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4646
4647 final int task = tr.taskId;
4648 int top = mHistory.size()-1;
4649
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004650 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004651 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004652 if (reason != null &&
4653 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4654 ActivityOptions.abort(options);
4655 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004656 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004657 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004658 return;
4659 }
4660
Dianne Hackbornbe707852011-11-11 14:32:10 -08004661 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004662
4663 // Applying the affinities may have removed entries from the history,
4664 // so get the size again.
4665 top = mHistory.size()-1;
4666 int pos = top;
4667
4668 // Shift all activities with this task up to the top
4669 // of the stack, keeping them in the same internal order.
4670 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004671 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004672 if (localLOGV) Slog.v(
4673 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004674 if (r.task.taskId == task) {
4675 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004676 if (DEBUG_ADD_REMOVE) {
4677 RuntimeException here = new RuntimeException("here");
4678 here.fillInStackTrace();
4679 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4680 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004681 mHistory.remove(pos);
4682 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004683 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004684 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004685 }
4686 pos--;
4687 }
4688
4689 if (DEBUG_TRANSITION) Slog.v(TAG,
4690 "Prepare to front transition: task=" + tr);
4691 if (reason != null &&
4692 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004693 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004694 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004695 ActivityRecord r = topRunningActivityLocked(null);
4696 if (r != null) {
4697 mNoAnimActivities.add(r);
4698 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004699 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004700 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004701 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004702 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004703
Craig Mautner30e2d722013-02-12 11:30:16 -08004704 mService.mWindowManager.moveTaskToTop(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004705 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004706 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004707 }
4708
4709 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004710 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004711 }
4712
4713 private final void finishTaskMoveLocked(int task) {
4714 resumeTopActivityLocked(null);
4715 }
4716
4717 /**
4718 * Worker method for rearranging history stack. Implements the function of moving all
4719 * activities for a specific task (gathering them if disjoint) into a single group at the
4720 * bottom of the stack.
4721 *
4722 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4723 * to premeptively cancel the move.
4724 *
4725 * @param task The taskId to collect and move to the bottom.
4726 * @return Returns true if the move completed, false if not.
4727 */
4728 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4729 Slog.i(TAG, "moveTaskToBack: " + task);
4730
4731 // If we have a watcher, preflight the move before committing to it. First check
4732 // for *other* available tasks, but if none are available, then try again allowing the
4733 // current task to be selected.
4734 if (mMainStack && mService.mController != null) {
4735 ActivityRecord next = topRunningActivityLocked(null, task);
4736 if (next == null) {
4737 next = topRunningActivityLocked(null, 0);
4738 }
4739 if (next != null) {
4740 // ask watcher if this is allowed
4741 boolean moveOK = true;
4742 try {
4743 moveOK = mService.mController.activityResuming(next.packageName);
4744 } catch (RemoteException e) {
4745 mService.mController = null;
4746 }
4747 if (!moveOK) {
4748 return false;
4749 }
4750 }
4751 }
4752
Dianne Hackbornbe707852011-11-11 14:32:10 -08004753 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004754
4755 if (DEBUG_TRANSITION) Slog.v(TAG,
4756 "Prepare to back transition: task=" + task);
4757
4758 final int N = mHistory.size();
4759 int bottom = 0;
4760 int pos = 0;
4761
4762 // Shift all activities with this task down to the bottom
4763 // of the stack, keeping them in the same internal order.
4764 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004765 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004766 if (localLOGV) Slog.v(
4767 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4768 if (r.task.taskId == task) {
4769 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004770 if (DEBUG_ADD_REMOVE) {
4771 RuntimeException here = new RuntimeException("here");
4772 here.fillInStackTrace();
4773 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4774 + bottom, here);
4775 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004776 mHistory.remove(pos);
4777 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004778 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004779 bottom++;
4780 }
4781 pos++;
4782 }
4783
4784 if (reason != null &&
4785 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004786 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004787 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004788 ActivityRecord r = topRunningActivityLocked(null);
4789 if (r != null) {
4790 mNoAnimActivities.add(r);
4791 }
4792 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004793 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004794 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004795 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004796 mService.mWindowManager.moveTaskToBottom(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004797 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004798 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004799 }
4800
4801 finishTaskMoveLocked(task);
4802 return true;
4803 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004804
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004805 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4806 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4807 ActivityRecord resumed = mResumedActivity;
4808 if (resumed != null && resumed.thumbHolder == tr) {
4809 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004810 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004811 if (info.mainThumbnail == null) {
4812 info.mainThumbnail = tr.lastThumbnail;
4813 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004814 return info;
4815 }
4816
Dianne Hackborn15491c62012-09-19 10:59:14 -07004817 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4818 ActivityRecord resumed = mResumedActivity;
4819 if (resumed != null && resumed.task == tr) {
4820 // This task is the current resumed task, we just need to take
4821 // a screenshot of it and return that.
4822 return resumed.stack.screenshotActivities(resumed);
4823 }
4824 // Return the information about the task, to figure out the top
4825 // thumbnail to return.
4826 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4827 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004828 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004829 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004830 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004831 }
4832
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004833 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4834 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004835 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4836 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004837 if (taskRequired) {
4838 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4839 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004840 return null;
4841 }
4842
4843 if (subTaskIndex < 0) {
4844 // Just remove the entire task.
4845 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4846 return info.root;
4847 }
4848
4849 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004850 if (taskRequired) {
4851 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4852 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004853 return null;
4854 }
4855
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004856 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004857 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4858 performClearTaskAtIndexLocked(taskId, subtask.index);
4859 return subtask.activity;
4860 }
4861
4862 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004863 final TaskAccessInfo thumbs = new TaskAccessInfo();
4864 // How many different sub-thumbnails?
4865 final int NA = mHistory.size();
4866 int j = 0;
4867 ThumbnailHolder holder = null;
4868 while (j < NA) {
4869 ActivityRecord ar = mHistory.get(j);
4870 if (!ar.finishing && ar.task.taskId == taskId) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004871 thumbs.root = ar;
4872 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004873 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004874 if (holder != null) {
4875 thumbs.mainThumbnail = holder.lastThumbnail;
4876 }
4877 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004878 break;
4879 }
4880 j++;
4881 }
4882
4883 if (j >= NA) {
4884 return thumbs;
4885 }
4886
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004887 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4888 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004889 while (j < NA) {
4890 ActivityRecord ar = mHistory.get(j);
4891 j++;
4892 if (ar.finishing) {
4893 continue;
4894 }
4895 if (ar.task.taskId != taskId) {
4896 break;
4897 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004898 if (ar.thumbHolder != holder && holder != null) {
4899 thumbs.numSubThumbbails++;
4900 holder = ar.thumbHolder;
4901 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004902 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004903 sub.activity = ar;
4904 sub.index = j-1;
4905 subtasks.add(sub);
4906 }
4907 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004908 if (thumbs.numSubThumbbails > 0) {
4909 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004910 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004911 public Bitmap getThumbnail(int index) {
4912 if (index < 0 || index >= thumbs.subtasks.size()) {
4913 return null;
4914 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004915 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4916 ActivityRecord resumed = mResumedActivity;
4917 if (resumed != null && resumed.thumbHolder == sub.holder) {
4918 return resumed.stack.screenshotActivities(resumed);
4919 }
4920 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004921 }
4922 };
4923 }
4924 return thumbs;
4925 }
4926
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004927 private final void logStartActivity(int tag, ActivityRecord r,
4928 TaskRecord task) {
4929 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004930 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004931 r.shortComponentName, r.intent.getAction(),
4932 r.intent.getType(), r.intent.getDataString(),
4933 r.intent.getFlags());
4934 }
4935
4936 /**
4937 * Make sure the given activity matches the current configuration. Returns
4938 * false if the activity had to be destroyed. Returns true if the
4939 * configuration is the same, or the activity will remain running as-is
4940 * for whatever reason. Ensures the HistoryRecord is updated with the
4941 * correct configuration and all other bookkeeping is handled.
4942 */
4943 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4944 int globalChanges) {
4945 if (mConfigWillChange) {
4946 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4947 "Skipping config check (will change): " + r);
4948 return true;
4949 }
4950
4951 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4952 "Ensuring correct configuration: " + r);
4953
4954 // Short circuit: if the two configurations are the exact same
4955 // object (the common case), then there is nothing to do.
4956 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004957 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004958 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4959 "Configuration unchanged in " + r);
4960 return true;
4961 }
4962
4963 // We don't worry about activities that are finishing.
4964 if (r.finishing) {
4965 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4966 "Configuration doesn't matter in finishing " + r);
4967 r.stopFreezingScreenLocked(false);
4968 return true;
4969 }
4970
4971 // Okay we now are going to make this activity have the new config.
4972 // But then we need to figure out how it needs to deal with that.
4973 Configuration oldConfig = r.configuration;
4974 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004975
4976 // Determine what has changed. May be nothing, if this is a config
4977 // that has come back from the app after going idle. In that case
4978 // we just want to leave the official config object now in the
4979 // activity and do nothing else.
4980 final int changes = oldConfig.diff(newConfig);
4981 if (changes == 0 && !r.forceNewConfig) {
4982 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4983 "Configuration no differences in " + r);
4984 return true;
4985 }
4986
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004987 // If the activity isn't currently running, just leave the new
4988 // configuration and it will pick that up next time it starts.
4989 if (r.app == null || r.app.thread == null) {
4990 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4991 "Configuration doesn't matter not running " + r);
4992 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004993 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004994 return true;
4995 }
4996
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004997 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004998 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4999 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
5000 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07005001 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005002 + ", newConfig=" + newConfig);
5003 }
Dianne Hackborne6676352011-06-01 16:51:20 -07005004 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005005 // Aha, the activity isn't handling the change, so DIE DIE DIE.
5006 r.configChangeFlags |= changes;
5007 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005008 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005009 if (r.app == null || r.app.thread == null) {
5010 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005011 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07005012 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005013 } else if (r.state == ActivityState.PAUSING) {
5014 // A little annoying: we are waiting for this activity to
5015 // finish pausing. Let's not do anything now, but just
5016 // flag that it needs to be restarted when done pausing.
5017 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005018 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005019 r.configDestroy = true;
5020 return true;
5021 } else if (r.state == ActivityState.RESUMED) {
5022 // Try to optimize this case: the configuration is changing
5023 // and we need to restart the top, resumed activity.
5024 // Instead of doing the normal handshaking, just say
5025 // "restart!".
5026 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005027 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005028 relaunchActivityLocked(r, r.configChangeFlags, true);
5029 r.configChangeFlags = 0;
5030 } else {
5031 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005032 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005033 relaunchActivityLocked(r, r.configChangeFlags, false);
5034 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005035 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07005036
5037 // All done... tell the caller we weren't able to keep this
5038 // activity around.
5039 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005040 }
5041
5042 // Default case: the activity can handle this new configuration, so
5043 // hand it over. Note that we don't need to give it the new
5044 // configuration, since we always send configuration changes to all
5045 // process when they happen so it can just use whatever configuration
5046 // it last got.
5047 if (r.app != null && r.app.thread != null) {
5048 try {
5049 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08005050 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005051 } catch (RemoteException e) {
5052 // If process died, whatever.
5053 }
5054 }
5055 r.stopFreezingScreenLocked(false);
5056
5057 return true;
5058 }
5059
5060 private final boolean relaunchActivityLocked(ActivityRecord r,
5061 int changes, boolean andResume) {
5062 List<ResultInfo> results = null;
5063 List<Intent> newIntents = null;
5064 if (andResume) {
5065 results = r.results;
5066 newIntents = r.newIntents;
5067 }
5068 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
5069 + " with results=" + results + " newIntents=" + newIntents
5070 + " andResume=" + andResume);
5071 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07005072 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005073 r.task.taskId, r.shortComponentName);
5074
5075 r.startFreezingScreenLocked(r.app, 0);
5076
5077 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005078 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
5079 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
5080 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04005081 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08005082 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08005083 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005084 // Note: don't need to call pauseIfSleepingLocked() here, because
5085 // the caller will only pass in 'andResume' if this activity is
5086 // currently resumed, which implies we aren't sleeping.
5087 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005088 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005089 }
5090
5091 if (andResume) {
5092 r.results = null;
5093 r.newIntents = null;
5094 if (mMainStack) {
5095 mService.reportResumedActivityLocked(r);
5096 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07005097 r.state = ActivityState.RESUMED;
5098 } else {
5099 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
5100 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005101 }
5102
5103 return true;
5104 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07005105
5106 public void dismissKeyguardOnNextActivityLocked() {
5107 mDismissKeyguardOnNextActivity = true;
5108 }
Craig Mautnercae015f2013-02-08 14:31:27 -08005109
5110 boolean willActivityBeVisibleLocked(IBinder token) {
5111 int i;
5112 for (i = mHistory.size() - 1; i >= 0; i--) {
5113 ActivityRecord r = mHistory.get(i);
5114 if (r.appToken == token) {
5115 return true;
5116 }
5117 if (r.fullscreen && !r.finishing) {
5118 return false;
5119 }
5120 }
5121 return true;
5122 }
5123
5124 void closeSystemDialogsLocked() {
5125 for (int i = mHistory.size() - 1; i >= 0; i--) {
5126 ActivityRecord r = mHistory.get(i);
5127 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
5128 r.stack.finishActivityLocked(r, i,
5129 Activity.RESULT_CANCELED, null, "close-sys", true);
5130 }
5131 }
5132 }
5133
5134 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
5135 boolean didSomething = false;
5136 TaskRecord lastTask = null;
5137 final int N = mHistory.size();
5138 for (int i = 0; i < N; i++) {
5139 ActivityRecord r = mHistory.get(i);
5140 final boolean samePackage = r.packageName.equals(name)
5141 || (name == null && r.userId == userId);
5142 if ((userId == UserHandle.USER_ALL || r.userId == userId)
5143 && (samePackage || r.task == lastTask)
5144 && (r.app == null || evenPersistent || !r.app.persistent)) {
5145 if (!doit) {
5146 if (r.finishing) {
5147 // If this activity is just finishing, then it is not
5148 // interesting as far as something to stop.
5149 continue;
5150 }
5151 return true;
5152 }
5153 didSomething = true;
5154 Slog.i(TAG, " Force finishing activity " + r);
5155 if (samePackage) {
5156 if (r.app != null) {
5157 r.app.removed = true;
5158 }
5159 r.app = null;
5160 }
5161 lastTask = r.task;
5162 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
5163 null, "force-stop", true)) {
5164 i--;
5165 }
5166 }
5167 }
5168 return didSomething;
5169 }
5170
5171 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
5172 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
5173 ActivityRecord topRecord = null;
5174 int pos = mHistory.size() - 1;
5175 ActivityRecord next = pos >= 0 ? mHistory.get(pos) : null;
5176 ActivityRecord top = null;
5177 TaskRecord curTask = null;
5178 int numActivities = 0;
5179 int numRunning = 0;
5180 while (pos >= 0 && maxNum > 0) {
5181 final ActivityRecord r = next;
5182 pos--;
5183 next = pos >= 0 ? mHistory.get(pos) : null;
5184
5185 // Initialize state for next task if needed.
5186 if (top == null || (top.state == ActivityState.INITIALIZING && top.task == r.task)) {
5187 top = r;
5188 curTask = r.task;
5189 numActivities = numRunning = 0;
5190 }
5191
5192 // Add 'r' into the current task.
5193 numActivities++;
5194 if (r.app != null && r.app.thread != null) {
5195 numRunning++;
5196 }
5197
5198 if (localLOGV) Slog.v(
5199 TAG, r.intent.getComponent().flattenToShortString()
5200 + ": task=" + r.task);
5201
5202 // If the next one is a different task, generate a new
5203 // TaskInfo entry for what we have.
5204 if (next == null || next.task != curTask) {
5205 RunningTaskInfo ci = new RunningTaskInfo();
5206 ci.id = curTask.taskId;
5207 ci.baseActivity = r.intent.getComponent();
5208 ci.topActivity = top.intent.getComponent();
5209 if (top.thumbHolder != null) {
5210 ci.description = top.thumbHolder.lastDescription;
5211 }
5212 ci.numActivities = numActivities;
5213 ci.numRunning = numRunning;
5214 //System.out.println(
5215 // "#" + maxNum + ": " + " descr=" + ci.description);
5216 if (receiver != null) {
5217 if (localLOGV) Slog.v(
5218 TAG, "State=" + top.state + "Idle=" + top.idle
5219 + " app=" + top.app
5220 + " thr=" + (top.app != null ? top.app.thread : null));
5221 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
5222 if (top.idle && top.app != null && top.app.thread != null) {
5223 topRecord = top;
5224 } else {
5225 top.thumbnailNeeded = true;
5226 }
5227 }
5228 pending.pendingRecords.add(top);
5229 }
5230 list.add(ci);
5231 maxNum--;
5232 top = null;
5233 }
5234 }
5235 return topRecord;
5236 }
5237
5238 public void unhandledBackLocked() {
5239 int top = mHistory.size() - 1;
5240 if (DEBUG_SWITCH) Slog.d(
5241 TAG, "Performing unhandledBack(): top activity at " + top);
5242 if (top > 0) {
5243 finishActivityLocked(mHistory.get(top),
5244 top, Activity.RESULT_CANCELED, null, "unhandled-back", true);
5245 }
5246 }
5247
5248 void handleAppCrashLocked(ProcessRecord app) {
5249 for (int i = mHistory.size() - 1; i >= 0; i--) {
5250 ActivityRecord r = mHistory.get(i);
5251 if (r.app == app) {
5252 Slog.w(TAG, " Force finishing activity "
5253 + r.intent.getComponent().flattenToShortString());
5254 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
5255 null, "crashed", false);
5256 }
5257 }
5258 }
5259
5260 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
5261 boolean dumpClient, String dumpPackage) {
5262 ActivityManagerService.dumpHistoryList(fd, pw, mHistory, " ", "Hist", true, !dumpAll,
5263 dumpClient, dumpPackage);
5264 }
5265
5266 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
5267 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
5268
5269 if ("all".equals(name)) {
5270 for (ActivityRecord r1 : mHistory) {
5271 activities.add(r1);
5272 }
5273 } else if ("top".equals(name)) {
5274 final int N = mHistory.size();
5275 if (N > 0) {
5276 activities.add(mHistory.get(N-1));
5277 }
5278 } else {
5279 ItemMatcher matcher = new ItemMatcher();
5280 matcher.build(name);
5281
5282 for (ActivityRecord r1 : mHistory) {
5283 if (matcher.match(r1, r1.intent.getComponent())) {
5284 activities.add(r1);
5285 }
5286 }
5287 }
5288
5289 return activities;
5290 }
5291
5292 ActivityRecord restartPackage(String packageName) {
5293 ActivityRecord starting = topRunningActivityLocked(null);
5294
5295 // All activities that came from the package must be
5296 // restarted as if there was a config change.
5297 for (int i = mHistory.size() - 1; i >= 0; i--) {
5298 ActivityRecord a = mHistory.get(i);
5299 if (a.info.packageName.equals(packageName)) {
5300 a.forceNewConfig = true;
5301 if (starting != null && a == starting && a.visible) {
5302 a.startFreezingScreenLocked(starting.app, ActivityInfo.CONFIG_SCREEN_LAYOUT);
5303 }
5304 }
5305 }
5306
5307 return starting;
5308 }
Craig Mautner5d9c7be2013-02-15 14:02:56 -08005309
5310 void verifyActivityRecords() {
5311 /* Until we have activity movement implemented for tasks just do the simple test
5312 ActivityIterator iterator = new ActivityIterator();
5313 int i;
5314 int N = mHistory.size();
5315 for (i = 0; i < N && iterator.hasNext(); ++i) {
5316 ActivityRecord r1 = mHistory.get(i);
5317 ActivityRecord r2 = iterator.next();
5318 if (r1 != r2) {
5319 break;
5320 }
5321 }
5322 if (i != N || iterator.hasNext()) {
5323 Slog.w(TAG, "verifyActivityRecords mHistory=" + mHistory
5324 + " mTaskHistory=" + iterator + " Callers=" + Debug.getCallers(2));
5325 } */
5326 // Simple test
5327 ActivityIterator iterator = new ActivityIterator();
5328 while (iterator.hasNext()) {
5329 ActivityRecord r = iterator.next();
5330 if (!mHistory.contains(r)) {
5331 break;
5332 }
5333 }
5334 if (iterator.size() != mHistory.size() || iterator.hasNext()) {
5335 Slog.w(TAG, "verifyActivityRecords mHistory=" + mHistory
5336 + " mTaskHistory=" + iterator + " Callers=" + Debug.getCallers(2));
5337 }
5338 }
5339
5340 private TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
5341 boolean toTop) {
5342 TaskRecord oldTask = mTaskIdToTaskRecord.get(taskId);
5343 if (oldTask != null) {
5344 Slog.w(TAG, "createTaskRecord: Reusing taskId=" + taskId + " without removing");
5345 mTaskHistory.remove(oldTask);
5346 }
5347 TaskRecord task = new TaskRecord(taskId, info, intent);
5348 mTaskIdToTaskRecord.put(taskId, task);
5349 if (toTop) {
5350 mTaskHistory.add(task);
5351 } else {
5352 mTaskHistory.add(0, task);
5353 }
5354 return task;
5355 }
5356
5357 class TaskIterator implements Iterator<TaskRecord> {
5358 private int mCur;
5359 private boolean mReverse;
5360
5361 TaskIterator() {
5362 this(FORWARD_ITERATOR);
5363 }
5364
5365 TaskIterator(boolean reverse) {
5366 reset(reverse);
5367 }
5368
5369 public void reset(boolean reverse) {
5370 mReverse = reverse;
5371 mCur = reverse ? mTaskHistory.size() - 1 : 0;
5372 }
5373
5374 @Override
5375 public boolean hasNext() {
5376 if (mReverse) {
5377 return mCur >= 0;
5378 }
5379 return mCur < mTaskHistory.size();
5380 }
5381
5382 @Override
5383 public TaskRecord next() {
5384 if (hasNext()) {
5385 TaskRecord task = mTaskHistory.get(mCur);
5386 mCur += (mReverse ? -1 : 1);
5387 return task;
5388 }
5389 throw new NoSuchElementException();
5390 }
5391
5392 @Override
5393 public void remove() {
5394 throw new IllegalArgumentException();
5395 }
5396 }
5397
5398 class ActivityIterator implements Iterator<ActivityRecord> {
5399 final TaskIterator mIterator;
5400 boolean mReverse;
5401 int mCur;
5402 TaskRecord mTaskRecord;
5403 final boolean mSkipFinishing;
5404
5405 public ActivityIterator() {
5406 this(FORWARD_ITERATOR);
5407 }
5408
5409 public ActivityIterator(boolean reverse) {
5410 this(reverse, false);
5411 }
5412
5413 public ActivityIterator(boolean reverse, boolean skipFinishing) {
5414 mSkipFinishing = skipFinishing;
5415 mIterator = new TaskIterator();
5416 reset(reverse);
5417 }
5418
5419 public void reset(boolean reverse) {
5420 mReverse = reverse;
5421 mIterator.reset(reverse);
5422 getNextTaskRecord();
5423 }
5424
5425 private void getNextTaskRecord() {
5426 if (mIterator.hasNext()) {
5427 mTaskRecord = mIterator.next();
5428 mCur = mReverse ? mTaskRecord.mActivities.size() - 1 : 0;
5429 }
5430 }
5431
5432 @Override
5433 public boolean hasNext() {
5434 if (mTaskRecord == null) {
5435 return false;
5436 }
5437 if (mReverse) {
5438 return mCur >= 0;
5439 }
5440 return mCur < mTaskRecord.mActivities.size();
5441 }
5442
5443 @Override
5444 public ActivityRecord next() {
5445 while (hasNext()) {
5446 ActivityRecord r = mTaskRecord.mActivities.get(mCur);
5447 mCur += mReverse ? -1 : 1;
5448 if (!hasNext()) {
5449 getNextTaskRecord();
5450 }
5451 if (mSkipFinishing && r.finishing) {
5452 continue;
5453 }
5454 return r;
5455 }
5456 throw new NoSuchElementException();
5457 }
5458
5459 @Override
5460 public void remove() {
5461 throw new UnsupportedOperationException();
5462 }
5463
5464 int size() {
5465 int size = 0;
5466 final TaskIterator iterator = new TaskIterator();
5467 while (iterator.hasNext()) {
5468 size += iterator.next().mActivities.size();
5469 }
5470 return size;
5471 }
5472
5473 ActivityRecord peek() {
5474 if (mTaskRecord != null && mCur >= 0 && mCur < mTaskRecord.mActivities.size()) {
5475 return mTaskRecord.mActivities.get(mCur);
5476 }
5477 return null;
5478 }
5479
5480 @Override
5481 public String toString() {
5482 StringBuffer sb = new StringBuffer();
5483 for (int i = 0; i < mTaskHistory.size(); ++i) {
5484 final TaskRecord task = mTaskHistory.get(i);
5485 sb.append("task_").append(i).append("-").append(task.mActivities).append(" ");
5486 }
5487 return sb.toString();
5488 }
5489 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005490}