blob: 437350242695c0286dc356b541d72c35f1644db6 [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;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070057import android.os.Handler;
58import android.os.IBinder;
Zoran Marcetaf958b322012-08-09 20:27:12 +090059import android.os.Looper;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070060import android.os.Message;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070061import android.os.ParcelFileDescriptor;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070062import android.os.PowerManager;
63import android.os.RemoteException;
64import android.os.SystemClock;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -070065import android.os.UserHandle;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070066import android.util.EventLog;
67import android.util.Log;
68import android.util.Slog;
Craig Mautner59c00972012-07-30 12:10:24 -070069import android.view.Display;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070070
Craig Mautnercae015f2013-02-08 14:31:27 -080071import java.io.FileDescriptor;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -070072import java.io.IOException;
Craig Mautnercae015f2013-02-08 14:31:27 -080073import java.io.PrintWriter;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070074import java.lang.ref.WeakReference;
75import java.util.ArrayList;
76import java.util.Iterator;
77import java.util.List;
78
79/**
80 * State and management of a single stack of activities.
81 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -070082final class ActivityStack {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070083 static final String TAG = ActivityManagerService.TAG;
Dianne Hackbornb961cd22011-06-21 12:13:37 -070084 static final boolean localLOGV = ActivityManagerService.localLOGV;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070085 static final boolean DEBUG_SWITCH = ActivityManagerService.DEBUG_SWITCH;
86 static final boolean DEBUG_PAUSE = ActivityManagerService.DEBUG_PAUSE;
87 static final boolean DEBUG_VISBILITY = ActivityManagerService.DEBUG_VISBILITY;
88 static final boolean DEBUG_USER_LEAVING = ActivityManagerService.DEBUG_USER_LEAVING;
89 static final boolean DEBUG_TRANSITION = ActivityManagerService.DEBUG_TRANSITION;
90 static final boolean DEBUG_RESULTS = ActivityManagerService.DEBUG_RESULTS;
91 static final boolean DEBUG_CONFIGURATION = ActivityManagerService.DEBUG_CONFIGURATION;
92 static final boolean DEBUG_TASKS = ActivityManagerService.DEBUG_TASKS;
Dianne Hackborncc5a0552012-10-01 16:32:39 -070093 static final boolean DEBUG_CLEANUP = ActivityManagerService.DEBUG_CLEANUP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -070094
Dianne Hackbornce86ba82011-07-13 19:33:41 -070095 static final boolean DEBUG_STATES = false;
Dianne Hackborn98cfebc2011-10-18 13:17:33 -070096 static final boolean DEBUG_ADD_REMOVE = false;
97 static final boolean DEBUG_SAVED_STATE = false;
Dianne Hackborn07981492013-01-28 11:36:23 -080098 static final boolean DEBUG_APP = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -070099
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700100 static final boolean VALIDATE_TOKENS = ActivityManagerService.VALIDATE_TOKENS;
101
102 // How long we wait until giving up on the last activity telling us it
103 // is idle.
104 static final int IDLE_TIMEOUT = 10*1000;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700105
106 // Ticks during which we check progress while waiting for an app to launch.
107 static final int LAUNCH_TICK = 500;
108
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700109 // How long we wait until giving up on the last activity to pause. This
110 // is short because it directly impacts the responsiveness of starting the
111 // next activity.
112 static final int PAUSE_TIMEOUT = 500;
113
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700114 // How long we wait for the activity to tell us it has stopped before
115 // giving up. This is a good amount of time because we really need this
116 // from the application in order to get its saved state.
117 static final int STOP_TIMEOUT = 10*1000;
118
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800119 // How long we can hold the sleep wake lock before giving up.
120 static final int SLEEP_TIMEOUT = 5*1000;
121
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700122 // How long we can hold the launch wake lock before giving up.
123 static final int LAUNCH_TIMEOUT = 10*1000;
124
125 // How long we wait until giving up on an activity telling us it has
126 // finished destroying itself.
127 static final int DESTROY_TIMEOUT = 10*1000;
128
129 // How long until we reset a task when the user returns to it. Currently
Dianne Hackborn621e17d2010-11-22 15:59:56 -0800130 // disabled.
131 static final long ACTIVITY_INACTIVE_RESET_TIME = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700132
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700133 // How long between activity launches that we consider safe to not warn
134 // the user about an unexpected activity being launched on top.
135 static final long START_WARN_TIME = 5*1000;
136
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700137 // Set to false to disable the preview that is shown while a new activity
138 // is being started.
139 static final boolean SHOW_APP_STARTING_PREVIEW = true;
140
141 enum ActivityState {
142 INITIALIZING,
143 RESUMED,
144 PAUSING,
145 PAUSED,
146 STOPPING,
147 STOPPED,
148 FINISHING,
149 DESTROYING,
150 DESTROYED
151 }
152
153 final ActivityManagerService mService;
154 final boolean mMainStack;
155
156 final Context mContext;
157
158 /**
159 * The back history of all previous (and possibly still
Craig Mautnercae015f2013-02-08 14:31:27 -0800160 * running) activities. It contains #ActivityRecord objects.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700161 */
Craig Mautnercae015f2013-02-08 14:31:27 -0800162 private final ArrayList<ActivityRecord> mHistory = new ArrayList<ActivityRecord>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800163
164 /**
165 * Used for validating app tokens with window manager.
166 */
Craig Mautnerb1fd65c02013-02-05 13:34:57 -0800167 final ArrayList<TaskGroup> mValidateAppTokens = new ArrayList<TaskGroup>();
Dianne Hackbornbe707852011-11-11 14:32:10 -0800168
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700169 /**
170 * List of running activities, sorted by recent usage.
171 * The first entry in the list is the least recently used.
172 * It contains HistoryRecord objects.
173 */
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700174 final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<ActivityRecord>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700175
176 /**
177 * List of activities that are waiting for a new activity
178 * to become visible before completing whatever operation they are
179 * supposed to do.
180 */
181 final ArrayList<ActivityRecord> mWaitingVisibleActivities
182 = new ArrayList<ActivityRecord>();
183
184 /**
185 * List of activities that are ready to be stopped, but waiting
186 * for the next activity to settle down before doing so. It contains
187 * HistoryRecord objects.
188 */
189 final ArrayList<ActivityRecord> mStoppingActivities
190 = new ArrayList<ActivityRecord>();
191
192 /**
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800193 * List of activities that are in the process of going to sleep.
194 */
195 final ArrayList<ActivityRecord> mGoingToSleepActivities
196 = new ArrayList<ActivityRecord>();
197
198 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700199 * Animations that for the current transition have requested not to
200 * be considered for the transition animation.
201 */
202 final ArrayList<ActivityRecord> mNoAnimActivities
203 = new ArrayList<ActivityRecord>();
204
205 /**
206 * List of activities that are ready to be finished, but waiting
207 * for the previous activity to settle down before doing so. It contains
208 * HistoryRecord objects.
209 */
210 final ArrayList<ActivityRecord> mFinishingActivities
211 = new ArrayList<ActivityRecord>();
212
213 /**
214 * List of people waiting to find out about the next launched activity.
215 */
216 final ArrayList<IActivityManager.WaitResult> mWaitingActivityLaunched
217 = new ArrayList<IActivityManager.WaitResult>();
218
219 /**
220 * List of people waiting to find out about the next visible activity.
221 */
222 final ArrayList<IActivityManager.WaitResult> mWaitingActivityVisible
223 = new ArrayList<IActivityManager.WaitResult>();
Dianne Hackborn80a4af22012-08-27 19:18:31 -0700224
225 final ArrayList<UserStartedState> mStartingUsers
226 = new ArrayList<UserStartedState>();
227
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700228 /**
229 * Set when the system is going to sleep, until we have
230 * successfully paused the current activity and released our wake lock.
231 * At that point the system is allowed to actually sleep.
232 */
233 final PowerManager.WakeLock mGoingToSleep;
234
235 /**
236 * We don't want to allow the device to go to sleep while in the process
237 * of launching an activity. This is primarily to allow alarm intent
238 * receivers to launch an activity and get that to run before the device
239 * goes back to sleep.
240 */
241 final PowerManager.WakeLock mLaunchingActivity;
242
243 /**
244 * When we are in the process of pausing an activity, before starting the
245 * next one, this variable holds the activity that is currently being paused.
246 */
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800247 ActivityRecord mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700248
249 /**
250 * This is the last activity that we put into the paused state. This is
251 * used to determine if we need to do an activity transition while sleeping,
252 * when we normally hold the top activity paused.
253 */
254 ActivityRecord mLastPausedActivity = null;
255
256 /**
257 * Current activity that is resumed, or null if there is none.
258 */
259 ActivityRecord mResumedActivity = null;
260
261 /**
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700262 * This is the last activity that has been started. It is only used to
263 * identify when multiple activities are started at once so that the user
264 * can be warned they may not be in the activity they think they are.
265 */
266 ActivityRecord mLastStartedActivity = null;
267
268 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700269 * Set when we know we are going to be calling updateConfiguration()
270 * soon, so want to skip intermediate config checks.
271 */
272 boolean mConfigWillChange;
273
274 /**
275 * Set to indicate whether to issue an onUserLeaving callback when a
276 * newly launched activity is being brought in front of us.
277 */
278 boolean mUserLeaving = false;
279
280 long mInitialStartTime = 0;
281
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800282 /**
283 * Set when we have taken too long waiting to go to sleep.
284 */
285 boolean mSleepTimeout = false;
286
Dianne Hackborn90c52de2011-09-23 12:57:44 -0700287 /**
288 * Dismiss the keyguard after the next activity is displayed?
289 */
290 boolean mDismissKeyguardOnNextActivity = false;
291
Craig Mautnerb12428a2012-12-20 16:07:06 -0800292 /**
293 * Save the most recent screenshot for reuse. This keeps Recents from taking two identical
294 * screenshots, one for the Recents thumbnail and one for the pauseActivity thumbnail.
295 */
296 private ActivityRecord mLastScreenshotActivity = null;
297 private Bitmap mLastScreenshotBitmap = null;
298
Craig Mautnercae015f2013-02-08 14:31:27 -0800299 /**
300 * List of ActivityRecord objects that have been finished and must
301 * still report back to a pending thumbnail receiver.
302 */
303 private final ArrayList<ActivityRecord> mCancelledThumbnails = new ArrayList<ActivityRecord>();
304
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800305 int mThumbnailWidth = -1;
306 int mThumbnailHeight = -1;
307
Amith Yamasani742a6712011-05-04 14:49:28 -0700308 private int mCurrentUser;
309
Dianne Hackborn40c8db52012-02-10 18:59:48 -0800310 static final int SLEEP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG;
311 static final int PAUSE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 1;
312 static final int IDLE_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 2;
313 static final int IDLE_NOW_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 3;
314 static final int LAUNCH_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 4;
315 static final int DESTROY_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 5;
316 static final int RESUME_TOP_ACTIVITY_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 6;
Dianne Hackborn29ba7e62012-03-16 15:03:36 -0700317 static final int LAUNCH_TICK_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 7;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700318 static final int STOP_TIMEOUT_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 8;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700319 static final int DESTROY_ACTIVITIES_MSG = ActivityManagerService.FIRST_ACTIVITY_STACK_MSG + 9;
320
321 static class ScheduleDestroyArgs {
322 final ProcessRecord mOwner;
323 final boolean mOomAdj;
324 final String mReason;
325 ScheduleDestroyArgs(ProcessRecord owner, boolean oomAdj, String reason) {
326 mOwner = owner;
327 mOomAdj = oomAdj;
328 mReason = reason;
329 }
330 }
331
Zoran Marcetaf958b322012-08-09 20:27:12 +0900332 final Handler mHandler;
333
334 final class ActivityStackHandler extends Handler {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700335 //public Handler() {
336 // if (localLOGV) Slog.v(TAG, "Handler started!");
337 //}
Zoran Marcetaf958b322012-08-09 20:27:12 +0900338 public ActivityStackHandler(Looper looper) {
339 super(looper);
340 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700341
Zoran Marcetaf958b322012-08-09 20:27:12 +0900342 @Override
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700343 public void handleMessage(Message msg) {
344 switch (msg.what) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800345 case SLEEP_TIMEOUT_MSG: {
Dianne Hackborn8e8d65f2011-08-11 19:36:18 -0700346 synchronized (mService) {
347 if (mService.isSleeping()) {
348 Slog.w(TAG, "Sleep timeout! Sleeping now.");
349 mSleepTimeout = true;
350 checkReadyForSleepLocked();
351 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800352 }
353 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700354 case PAUSE_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800355 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700356 // We don't at this point know if the activity is fullscreen,
357 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800358 Slog.w(TAG, "Activity pause timeout for " + r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700359 synchronized (mService) {
360 if (r.app != null) {
361 mService.logAppTooSlow(r.app, r.pauseTime,
362 "pausing " + r);
363 }
364 }
365
Dianne Hackbornbe707852011-11-11 14:32:10 -0800366 activityPaused(r != null ? r.appToken : null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700367 } break;
368 case IDLE_TIMEOUT_MSG: {
369 if (mService.mDidDexOpt) {
370 mService.mDidDexOpt = false;
371 Message nmsg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
372 nmsg.obj = msg.obj;
373 mHandler.sendMessageDelayed(nmsg, IDLE_TIMEOUT);
374 return;
375 }
376 // We don't at this point know if the activity is fullscreen,
377 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800378 ActivityRecord r = (ActivityRecord)msg.obj;
379 Slog.w(TAG, "Activity idle timeout for " + r);
380 activityIdleInternal(r != null ? r.appToken : null, true, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700381 } break;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700382 case LAUNCH_TICK_MSG: {
383 ActivityRecord r = (ActivityRecord)msg.obj;
384 synchronized (mService) {
385 if (r.continueLaunchTickingLocked()) {
386 mService.logAppTooSlow(r.app, r.launchTickTime,
387 "launching " + r);
388 }
389 }
390 } break;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700391 case DESTROY_TIMEOUT_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800392 ActivityRecord r = (ActivityRecord)msg.obj;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700393 // We don't at this point know if the activity is fullscreen,
394 // so we need to be conservative and assume it isn't.
Dianne Hackbornbe707852011-11-11 14:32:10 -0800395 Slog.w(TAG, "Activity destroy timeout for " + r);
396 activityDestroyed(r != null ? r.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700397 } break;
398 case IDLE_NOW_MSG: {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800399 ActivityRecord r = (ActivityRecord)msg.obj;
400 activityIdleInternal(r != null ? r.appToken : null, false, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700401 } break;
402 case LAUNCH_TIMEOUT_MSG: {
403 if (mService.mDidDexOpt) {
404 mService.mDidDexOpt = false;
405 Message nmsg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
406 mHandler.sendMessageDelayed(nmsg, LAUNCH_TIMEOUT);
407 return;
408 }
409 synchronized (mService) {
410 if (mLaunchingActivity.isHeld()) {
411 Slog.w(TAG, "Launch timeout has expired, giving up wake lock!");
412 mLaunchingActivity.release();
413 }
414 }
415 } break;
416 case RESUME_TOP_ACTIVITY_MSG: {
417 synchronized (mService) {
418 resumeTopActivityLocked(null);
419 }
420 } break;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -0700421 case STOP_TIMEOUT_MSG: {
422 ActivityRecord r = (ActivityRecord)msg.obj;
423 // We don't at this point know if the activity is fullscreen,
424 // so we need to be conservative and assume it isn't.
425 Slog.w(TAG, "Activity stop timeout for " + r);
426 synchronized (mService) {
427 if (r.isInHistory()) {
428 activityStoppedLocked(r, null, null, null);
429 }
430 }
431 } break;
Dianne Hackborn755c8bf2012-05-07 15:06:09 -0700432 case DESTROY_ACTIVITIES_MSG: {
433 ScheduleDestroyArgs args = (ScheduleDestroyArgs)msg.obj;
434 synchronized (mService) {
435 destroyActivitiesLocked(args.mOwner, args.mOomAdj, args.mReason);
436 }
437 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700438 }
439 }
Craig Mautner4b71aa12012-12-27 17:20:01 -0800440 }
441
Zoran Marcetaf958b322012-08-09 20:27:12 +0900442 ActivityStack(ActivityManagerService service, Context context, boolean mainStack, Looper looper) {
443 mHandler = new ActivityStackHandler(looper);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700444 mService = service;
445 mContext = context;
446 mMainStack = mainStack;
447 PowerManager pm =
448 (PowerManager)context.getSystemService(Context.POWER_SERVICE);
449 mGoingToSleep = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Sleep");
450 mLaunchingActivity = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "ActivityManager-Launch");
451 mLaunchingActivity.setReferenceCounted(false);
452 }
Craig Mautner5962b122012-10-05 14:45:52 -0700453
454 private boolean okToShow(ActivityRecord r) {
455 return r.userId == mCurrentUser
456 || (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0;
457 }
458
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700459 final ActivityRecord topRunningActivityLocked(ActivityRecord notTop) {
460 int i = mHistory.size()-1;
461 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700462 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700463 if (!r.finishing && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700464 return r;
465 }
466 i--;
467 }
468 return null;
469 }
470
471 final ActivityRecord topRunningNonDelayedActivityLocked(ActivityRecord notTop) {
472 int i = mHistory.size()-1;
473 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700474 ActivityRecord r = mHistory.get(i);
Craig Mautner5962b122012-10-05 14:45:52 -0700475 if (!r.finishing && !r.delayedResume && r != notTop && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700476 return r;
477 }
478 i--;
479 }
480 return null;
481 }
482
483 /**
484 * This is a simplified version of topRunningActivityLocked that provides a number of
485 * optional skip-over modes. It is intended for use with the ActivityController hook only.
486 *
487 * @param token If non-null, any history records matching this token will be skipped.
488 * @param taskId If non-zero, we'll attempt to skip over records with the same task ID.
489 *
490 * @return Returns the HistoryRecord of the next activity on the stack.
491 */
492 final ActivityRecord topRunningActivityLocked(IBinder token, int taskId) {
493 int i = mHistory.size()-1;
494 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700495 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700496 // Note: the taskId check depends on real taskId fields being non-zero
Amith Yamasani259d5e52012-08-31 15:11:01 -0700497 if (!r.finishing && (token != r.appToken) && (taskId != r.task.taskId)
Craig Mautner5962b122012-10-05 14:45:52 -0700498 && okToShow(r)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700499 return r;
500 }
501 i--;
502 }
503 return null;
504 }
505
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800506 private final int indexOfTokenLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800507 return mHistory.indexOf(ActivityRecord.forToken(token));
508 }
509
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700510 final ActivityRecord isInStackLocked(IBinder token) {
Dianne Hackbornbe707852011-11-11 14:32:10 -0800511 ActivityRecord r = ActivityRecord.forToken(token);
512 if (mHistory.contains(r)) {
513 return r;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700514 }
515 return null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700516 }
517
Craig Mautnercae015f2013-02-08 14:31:27 -0800518 int getTaskForActivityLocked(IBinder token, boolean onlyRoot) {
519 TaskRecord lastTask = null;
520 final int N = mHistory.size();
521 for (int i = 0; i < N; i++) {
522 ActivityRecord r = mHistory.get(i);
523 if (r.appToken == token) {
524 if (!onlyRoot || lastTask != r.task) {
525 return r.task.taskId;
526 }
527 return -1;
528 }
529 lastTask = r.task;
530 }
531
532 return -1;
533 }
534
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700535 private final boolean updateLRUListLocked(ActivityRecord r) {
536 final boolean hadit = mLRUActivities.remove(r);
537 mLRUActivities.add(r);
538 return hadit;
539 }
540
541 /**
542 * Returns the top activity in any existing task matching the given
543 * Intent. Returns null if no such task is found.
544 */
545 private ActivityRecord findTaskLocked(Intent intent, ActivityInfo info) {
546 ComponentName cls = intent.getComponent();
547 if (info.targetActivity != null) {
548 cls = new ComponentName(info.packageName, info.targetActivity);
549 }
550
551 TaskRecord cp = null;
552
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700553 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700554 final int N = mHistory.size();
555 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700556 ActivityRecord r = mHistory.get(i);
Amith Yamasani742a6712011-05-04 14:49:28 -0700557 if (!r.finishing && r.task != cp && r.userId == userId
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700558 && r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
559 cp = r.task;
560 //Slog.i(TAG, "Comparing existing cls=" + r.task.intent.getComponent().flattenToShortString()
561 // + "/aff=" + r.task.affinity + " to new cls="
562 // + intent.getComponent().flattenToShortString() + "/aff=" + taskAffinity);
563 if (r.task.affinity != null) {
564 if (r.task.affinity.equals(info.taskAffinity)) {
565 //Slog.i(TAG, "Found matching affinity!");
566 return r;
567 }
568 } else if (r.task.intent != null
569 && r.task.intent.getComponent().equals(cls)) {
570 //Slog.i(TAG, "Found matching class!");
571 //dump();
572 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
573 return r;
574 } else if (r.task.affinityIntent != null
575 && r.task.affinityIntent.getComponent().equals(cls)) {
576 //Slog.i(TAG, "Found matching class!");
577 //dump();
578 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
579 return r;
580 }
581 }
582 }
583
584 return null;
585 }
586
587 /**
588 * Returns the first activity (starting from the top of the stack) that
589 * is the same as the given activity. Returns null if no such activity
590 * is found.
591 */
592 private ActivityRecord findActivityLocked(Intent intent, ActivityInfo info) {
593 ComponentName cls = intent.getComponent();
594 if (info.targetActivity != null) {
595 cls = new ComponentName(info.packageName, info.targetActivity);
596 }
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700597 final int userId = UserHandle.getUserId(info.applicationInfo.uid);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700598
599 final int N = mHistory.size();
600 for (int i=(N-1); i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700601 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700602 if (!r.finishing) {
Amith Yamasani742a6712011-05-04 14:49:28 -0700603 if (r.intent.getComponent().equals(cls) && r.userId == userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700604 //Slog.i(TAG, "Found matching class!");
605 //dump();
606 //Slog.i(TAG, "For Intent " + intent + " bringing to top: " + r.intent);
607 return r;
608 }
609 }
610 }
611
612 return null;
613 }
614
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700615 final void showAskCompatModeDialogLocked(ActivityRecord r) {
616 Message msg = Message.obtain();
617 msg.what = ActivityManagerService.SHOW_COMPAT_MODE_DIALOG_MSG;
618 msg.obj = r.task.askedCompatMode ? null : r;
619 mService.mHandler.sendMessage(msg);
620 }
621
Amith Yamasani742a6712011-05-04 14:49:28 -0700622 /*
623 * Move the activities around in the stack to bring a user to the foreground.
624 * @return whether there are any activities for the specified user.
625 */
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700626 final boolean switchUserLocked(int userId, UserStartedState uss) {
627 mCurrentUser = userId;
628 mStartingUsers.add(uss);
Amith Yamasani742a6712011-05-04 14:49:28 -0700629
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700630 // Only one activity? Nothing to do...
631 if (mHistory.size() < 2)
632 return false;
Amith Yamasani742a6712011-05-04 14:49:28 -0700633
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700634 boolean haveActivities = false;
635 // Check if the top activity is from the new user.
636 ActivityRecord top = mHistory.get(mHistory.size() - 1);
637 if (top.userId == userId) return true;
638 // Otherwise, move the user's activities to the top.
639 int N = mHistory.size();
640 int i = 0;
641 while (i < N) {
642 ActivityRecord r = mHistory.get(i);
643 if (r.userId == userId) {
644 ActivityRecord moveToTop = mHistory.remove(i);
645 mHistory.add(moveToTop);
646 // No need to check the top one now
647 N--;
648 haveActivities = true;
649 } else {
650 i++;
Amith Yamasani742a6712011-05-04 14:49:28 -0700651 }
Amith Yamasani742a6712011-05-04 14:49:28 -0700652 }
Dianne Hackborn5dc5a002012-09-15 19:33:48 -0700653 // Transition from the old top to the new top
654 resumeTopActivityLocked(top);
655 return haveActivities;
Amith Yamasani742a6712011-05-04 14:49:28 -0700656 }
657
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700658 final boolean realStartActivityLocked(ActivityRecord r,
659 ProcessRecord app, boolean andResume, boolean checkConfig)
660 throws RemoteException {
661
662 r.startFreezingScreenLocked(app, 0);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800663 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700664
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -0700665 // schedule launch ticks to collect information about slow apps.
666 r.startLaunchTickingLocked();
667
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700668 // Have the window manager re-evaluate the orientation of
669 // the screen based on the new activity order. Note that
670 // as a result of this, it can call back into the activity
671 // manager with a new orientation. We don't care about that,
672 // because the activity is not currently running so we are
673 // just restarting it anyway.
674 if (checkConfig) {
675 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
676 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -0800677 r.mayFreezeScreenLocked(app) ? r.appToken : null);
Dianne Hackborn813075a62011-11-14 17:45:19 -0800678 mService.updateConfigurationLocked(config, r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700679 }
680
681 r.app = app;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700682 app.waitingToKill = null;
Dianne Hackborn07981492013-01-28 11:36:23 -0800683 r.launchCount++;
684 r.lastLaunchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700685
686 if (localLOGV) Slog.v(TAG, "Launching: " + r);
687
688 int idx = app.activities.indexOf(r);
689 if (idx < 0) {
690 app.activities.add(r);
691 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700692 mService.updateLruProcessLocked(app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700693
694 try {
695 if (app.thread == null) {
696 throw new RemoteException();
697 }
698 List<ResultInfo> results = null;
699 List<Intent> newIntents = null;
700 if (andResume) {
701 results = r.results;
702 newIntents = r.newIntents;
703 }
704 if (DEBUG_SWITCH) Slog.v(TAG, "Launching: " + r
705 + " icicle=" + r.icicle
706 + " with results=" + results + " newIntents=" + newIntents
707 + " andResume=" + andResume);
708 if (andResume) {
709 EventLog.writeEvent(EventLogTags.AM_RESTART_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -0700710 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700711 r.task.taskId, r.shortComponentName);
712 }
713 if (r.isHomeActivity) {
714 mService.mHomeProcess = app;
715 }
716 mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName());
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800717 r.sleeping = false;
Dianne Hackborne2515ee2011-04-27 18:52:56 -0400718 r.forceNewConfig = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -0700719 showAskCompatModeDialogLocked(r);
Dianne Hackborn8ea5e1d2011-05-27 16:45:31 -0700720 r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700721 String profileFile = null;
722 ParcelFileDescriptor profileFd = null;
723 boolean profileAutoStop = false;
724 if (mService.mProfileApp != null && mService.mProfileApp.equals(app.processName)) {
725 if (mService.mProfileProc == null || mService.mProfileProc == app) {
726 mService.mProfileProc = app;
727 profileFile = mService.mProfileFile;
728 profileFd = mService.mProfileFd;
729 profileAutoStop = mService.mAutoStopProfiler;
730 }
731 }
Dianne Hackbornf0754f5b2011-07-21 16:02:07 -0700732 app.hasShownUi = true;
Dianne Hackbornc68c9132011-07-29 01:25:18 -0700733 app.pendingUiClean = true;
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700734 if (profileFd != null) {
735 try {
736 profileFd = profileFd.dup();
737 } catch (IOException e) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -0800738 if (profileFd != null) {
739 try {
740 profileFd.close();
741 } catch (IOException o) {
742 }
743 profileFd = null;
744 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700745 }
746 }
Dianne Hackbornbe707852011-11-11 14:32:10 -0800747 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
Dianne Hackborn813075a62011-11-14 17:45:19 -0800748 System.identityHashCode(r), r.info,
749 new Configuration(mService.mConfiguration),
Dianne Hackborn58f42a52011-10-10 13:46:34 -0700750 r.compat, r.icicle, results, newIntents, !andResume,
Dianne Hackborn62f20ec2011-08-15 17:40:28 -0700751 mService.isNextTransitionForward(), profileFile, profileFd,
752 profileAutoStop);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700753
Dianne Hackborn54e570f2010-10-04 18:32:32 -0700754 if ((app.info.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700755 // This may be a heavy-weight process! Note that the package
756 // manager will ensure that only activity can run in the main
757 // process of the .apk, which is the only thing that will be
758 // considered heavy-weight.
759 if (app.processName.equals(app.info.packageName)) {
760 if (mService.mHeavyWeightProcess != null
761 && mService.mHeavyWeightProcess != app) {
762 Log.w(TAG, "Starting new heavy weight process " + app
763 + " when already running "
764 + mService.mHeavyWeightProcess);
765 }
766 mService.mHeavyWeightProcess = app;
767 Message msg = mService.mHandler.obtainMessage(
768 ActivityManagerService.POST_HEAVY_NOTIFICATION_MSG);
769 msg.obj = r;
770 mService.mHandler.sendMessage(msg);
771 }
772 }
773
774 } catch (RemoteException e) {
775 if (r.launchFailed) {
776 // This is the second time we failed -- finish activity
777 // and give up.
778 Slog.e(TAG, "Second failure launching "
779 + r.intent.getComponent().flattenToShortString()
780 + ", giving up", e);
781 mService.appDiedLocked(app, app.pid, app.thread);
Dianne Hackbornbe707852011-11-11 14:32:10 -0800782 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -0700783 "2nd-crash", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700784 return false;
785 }
786
787 // This is the first time we failed -- restart process and
788 // retry.
789 app.activities.remove(r);
790 throw e;
791 }
792
793 r.launchFailed = false;
794 if (updateLRUListLocked(r)) {
795 Slog.w(TAG, "Activity " + r
796 + " being launched, but already in LRU list");
797 }
798
799 if (andResume) {
800 // As part of the process of launching, ActivityThread also performs
801 // a resume.
802 r.state = ActivityState.RESUMED;
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700803 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + r
804 + " (starting new instance)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700805 r.stopped = false;
806 mResumedActivity = r;
807 r.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -0800808 if (mMainStack) {
809 mService.addRecentTaskLocked(r.task);
810 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700811 completeResumeLocked(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800812 checkReadyForSleepLocked();
Dianne Hackborn98cfebc2011-10-18 13:17:33 -0700813 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Launch completed; removing icicle of " + r.icicle);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700814 } else {
815 // This activity is not starting in the resumed state... which
816 // should look like we asked it to pause+stop (but remain visible),
817 // and it has done so and reported back the current icicle and
818 // other state.
Dianne Hackbornce86ba82011-07-13 19:33:41 -0700819 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r
820 + " (starting in stopped state)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700821 r.state = ActivityState.STOPPED;
822 r.stopped = true;
823 }
824
825 // Launch the new version setup screen if needed. We do this -after-
826 // launching the initial activity (that is, home), so that it can have
827 // a chance to initialize itself while in the background, making the
828 // switch back to it faster and look better.
829 if (mMainStack) {
830 mService.startSetupActivityLocked();
831 }
832
833 return true;
834 }
835
836 private final void startSpecificActivityLocked(ActivityRecord r,
837 boolean andResume, boolean checkConfig) {
838 // Is this activity's application already running?
839 ProcessRecord app = mService.getProcessRecordLocked(r.processName,
840 r.info.applicationInfo.uid);
Dianne Hackborn07981492013-01-28 11:36:23 -0800841
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700842 if (r.launchTime == 0) {
843 r.launchTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700844 if (mInitialStartTime == 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -0700845 mInitialStartTime = r.launchTime;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700846 }
847 } else if (mInitialStartTime == 0) {
848 mInitialStartTime = SystemClock.uptimeMillis();
849 }
850
851 if (app != null && app.thread != null) {
852 try {
Dianne Hackborn6c418d52011-06-29 14:05:33 -0700853 app.addPackage(r.info.packageName);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700854 realStartActivityLocked(r, app, andResume, checkConfig);
855 return;
856 } catch (RemoteException e) {
857 Slog.w(TAG, "Exception when starting activity "
858 + r.intent.getComponent().flattenToShortString(), e);
859 }
860
861 // If a dead object exception was thrown -- fall through to
862 // restart the application.
863 }
864
865 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800866 "activity", r.intent.getComponent(), false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700867 }
868
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800869 void stopIfSleepingLocked() {
870 if (mService.isSleeping()) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700871 if (!mGoingToSleep.isHeld()) {
872 mGoingToSleep.acquire();
873 if (mLaunchingActivity.isHeld()) {
874 mLaunchingActivity.release();
875 mService.mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
876 }
877 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800878 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
879 Message msg = mHandler.obtainMessage(SLEEP_TIMEOUT_MSG);
880 mHandler.sendMessageDelayed(msg, SLEEP_TIMEOUT);
881 checkReadyForSleepLocked();
882 }
883 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700884
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800885 void awakeFromSleepingLocked() {
886 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
887 mSleepTimeout = false;
888 if (mGoingToSleep.isHeld()) {
889 mGoingToSleep.release();
890 }
891 // Ensure activities are no longer sleeping.
892 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700893 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800894 r.setSleeping(false);
895 }
896 mGoingToSleepActivities.clear();
897 }
898
899 void activitySleptLocked(ActivityRecord r) {
900 mGoingToSleepActivities.remove(r);
901 checkReadyForSleepLocked();
902 }
903
904 void checkReadyForSleepLocked() {
905 if (!mService.isSleeping()) {
906 // Do not care.
907 return;
908 }
909
910 if (!mSleepTimeout) {
911 if (mResumedActivity != null) {
912 // Still have something resumed; can't sleep until it is paused.
913 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep needs to pause " + mResumedActivity);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700914 if (DEBUG_USER_LEAVING) Slog.v(TAG, "Sleep => pause with userLeaving=false");
915 startPausingLocked(false, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800916 return;
917 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800918 if (mPausingActivity != null) {
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800919 // Still waiting for something to pause; can't sleep yet.
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800920 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still waiting to pause " + mPausingActivity);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800921 return;
922 }
923
924 if (mStoppingActivities.size() > 0) {
925 // Still need to tell some activities to stop; can't sleep yet.
926 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to stop "
927 + mStoppingActivities.size() + " activities");
Dianne Hackborn80a7ac12011-09-22 18:32:52 -0700928 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800929 return;
930 }
931
932 ensureActivitiesVisibleLocked(null, 0);
933
934 // Make sure any stopped but visible activities are now sleeping.
935 // This ensures that the activity's onStop() is called.
936 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -0700937 ActivityRecord r = mHistory.get(i);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800938 if (r.state == ActivityState.STOPPING || r.state == ActivityState.STOPPED) {
939 r.setSleeping(true);
940 }
941 }
942
943 if (mGoingToSleepActivities.size() > 0) {
944 // Still need to tell some activities to sleep; can't sleep yet.
945 if (DEBUG_PAUSE) Slog.v(TAG, "Sleep still need to sleep "
946 + mGoingToSleepActivities.size() + " activities");
947 return;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700948 }
949 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -0800950
951 mHandler.removeMessages(SLEEP_TIMEOUT_MSG);
952
953 if (mGoingToSleep.isHeld()) {
954 mGoingToSleep.release();
955 }
956 if (mService.mShuttingDown) {
957 mService.notifyAll();
958 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700959 }
Craig Mautner59c00972012-07-30 12:10:24 -0700960
Dianne Hackbornd2835932010-12-13 16:28:46 -0800961 public final Bitmap screenshotActivities(ActivityRecord who) {
Dianne Hackbornff801ec2011-01-22 18:05:38 -0800962 if (who.noDisplay) {
963 return null;
964 }
965
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800966 Resources res = mService.mContext.getResources();
967 int w = mThumbnailWidth;
968 int h = mThumbnailHeight;
969 if (w < 0) {
970 mThumbnailWidth = w =
971 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_width);
972 mThumbnailHeight = h =
973 res.getDimensionPixelSize(com.android.internal.R.dimen.thumbnail_height);
974 }
975
976 if (w > 0) {
Craig Mautnerb12428a2012-12-20 16:07:06 -0800977 if (who != mLastScreenshotActivity || mLastScreenshotBitmap == null
978 || mLastScreenshotBitmap.getWidth() != w
979 || mLastScreenshotBitmap.getHeight() != h) {
980 mLastScreenshotActivity = who;
981 mLastScreenshotBitmap = mService.mWindowManager.screenshotApplications(
982 who.appToken, Display.DEFAULT_DISPLAY, w, h);
983 }
984 if (mLastScreenshotBitmap != null) {
985 return mLastScreenshotBitmap.copy(Config.ARGB_8888, true);
986 }
Dianne Hackborn0aae2d42010-12-07 23:51:29 -0800987 }
988 return null;
989 }
990
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700991 private final void startPausingLocked(boolean userLeaving, boolean uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -0800992 if (mPausingActivity != null) {
993 RuntimeException e = new RuntimeException();
994 Slog.e(TAG, "Trying to pause when pause is already pending for "
995 + mPausingActivity, e);
996 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -0700997 ActivityRecord prev = mResumedActivity;
998 if (prev == null) {
999 RuntimeException e = new RuntimeException();
1000 Slog.e(TAG, "Trying to pause when nothing is resumed", e);
1001 resumeTopActivityLocked(null);
1002 return;
1003 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001004 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSING: " + prev);
1005 else if (DEBUG_PAUSE) Slog.v(TAG, "Start pausing: " + prev);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001006 mResumedActivity = null;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001007 mPausingActivity = prev;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001008 mLastPausedActivity = prev;
1009 prev.state = ActivityState.PAUSING;
1010 prev.task.touchActiveTime();
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001011 prev.updateThumbnail(screenshotActivities(prev), null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001012
1013 mService.updateCpuStats();
1014
1015 if (prev.app != null && prev.app.thread != null) {
1016 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending pause: " + prev);
1017 try {
1018 EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001019 prev.userId, System.identityHashCode(prev),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001020 prev.shortComponentName);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001021 prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
1022 userLeaving, prev.configChangeFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001023 if (mMainStack) {
1024 mService.updateUsageStats(prev, false);
1025 }
1026 } catch (Exception e) {
1027 // Ignore exception, if process died other code will cleanup.
1028 Slog.w(TAG, "Exception thrown during pause", e);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001029 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001030 mLastPausedActivity = null;
1031 }
1032 } else {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001033 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001034 mLastPausedActivity = null;
1035 }
1036
1037 // If we are not going to sleep, we want to ensure the device is
1038 // awake until the next activity is started.
1039 if (!mService.mSleeping && !mService.mShuttingDown) {
1040 mLaunchingActivity.acquire();
1041 if (!mHandler.hasMessages(LAUNCH_TIMEOUT_MSG)) {
1042 // To be safe, don't allow the wake lock to be held for too long.
1043 Message msg = mHandler.obtainMessage(LAUNCH_TIMEOUT_MSG);
1044 mHandler.sendMessageDelayed(msg, LAUNCH_TIMEOUT);
1045 }
1046 }
1047
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001048
1049 if (mPausingActivity != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001050 // Have the window manager pause its key dispatching until the new
1051 // activity has started. If we're pausing the activity just because
1052 // the screen is being turned off and the UI is sleeping, don't interrupt
1053 // key dispatch; the same activity will pick it up again on wakeup.
1054 if (!uiSleeping) {
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001055 prev.pauseKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001056 } else {
1057 if (DEBUG_PAUSE) Slog.v(TAG, "Key dispatch not paused for screen off");
1058 }
1059
1060 // Schedule a pause timeout in case the app doesn't respond.
1061 // We don't give it much time because this directly impacts the
1062 // responsiveness seen by the user.
1063 Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG);
1064 msg.obj = prev;
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001065 prev.pauseTime = SystemClock.uptimeMillis();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001066 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT);
1067 if (DEBUG_PAUSE) Slog.v(TAG, "Waiting for pause to complete...");
1068 } else {
1069 // This activity failed to schedule the
1070 // pause, so just treat it as being paused now.
1071 if (DEBUG_PAUSE) Slog.v(TAG, "Activity not running, resuming next.");
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001072 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001073 }
1074 }
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001075
1076 final void activityResumed(IBinder token) {
1077 ActivityRecord r = null;
1078
1079 synchronized (mService) {
1080 int index = indexOfTokenLocked(token);
1081 if (index >= 0) {
1082 r = mHistory.get(index);
1083 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Resumed activity; dropping state of: " + r);
1084 r.icicle = null;
1085 r.haveState = false;
1086 }
1087 }
1088 }
1089
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001090 final void activityPaused(IBinder token, boolean timeout) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001091 if (DEBUG_PAUSE) Slog.v(
Dianne Hackborn0aae2d42010-12-07 23:51:29 -08001092 TAG, "Activity paused: token=" + token + ", timeout=" + timeout);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001093
1094 ActivityRecord r = null;
1095
1096 synchronized (mService) {
1097 int index = indexOfTokenLocked(token);
1098 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001099 r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001100 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001101 if (mPausingActivity == r) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001102 if (DEBUG_STATES) Slog.v(TAG, "Moving to PAUSED: " + r
1103 + (timeout ? " (due to timeout)" : " (pause complete)"));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001104 r.state = ActivityState.PAUSED;
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001105 completePauseLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001106 } else {
1107 EventLog.writeEvent(EventLogTags.AM_FAILED_TO_PAUSE,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001108 r.userId, System.identityHashCode(r), r.shortComponentName,
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001109 mPausingActivity != null
1110 ? mPausingActivity.shortComponentName : "(none)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001111 }
1112 }
1113 }
1114 }
1115
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001116 final void activityStoppedLocked(ActivityRecord r, Bundle icicle, Bitmap thumbnail,
1117 CharSequence description) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07001118 if (r.state != ActivityState.STOPPING) {
1119 Slog.i(TAG, "Activity reported stop, but no longer stopping: " + r);
1120 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1121 return;
1122 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001123 if (DEBUG_SAVED_STATE) Slog.i(TAG, "Saving icicle of " + r + ": " + icicle);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001124 if (icicle != null) {
1125 // If icicle is null, this is happening due to a timeout, so we
1126 // haven't really saved the state.
1127 r.icicle = icicle;
1128 r.haveState = true;
Dianne Hackborn07981492013-01-28 11:36:23 -08001129 r.launchCount = 0;
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001130 r.updateThumbnail(thumbnail, description);
1131 }
1132 if (!r.stopped) {
1133 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPED: " + r + " (stop complete)");
1134 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
1135 r.stopped = true;
1136 r.state = ActivityState.STOPPED;
Dianne Hackborn6e3d6da2012-06-15 12:05:27 -07001137 if (r.finishing) {
1138 r.clearOptionsLocked();
1139 } else {
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07001140 if (r.configDestroy) {
1141 destroyActivityLocked(r, true, false, "stop-config");
1142 resumeTopActivityLocked(null);
1143 } else {
1144 // Now that this process has stopped, we may want to consider
1145 // it to be the previous app to try to keep around in case
1146 // the user wants to return to it.
1147 ProcessRecord fgApp = null;
1148 if (mResumedActivity != null) {
1149 fgApp = mResumedActivity.app;
1150 } else if (mPausingActivity != null) {
1151 fgApp = mPausingActivity.app;
1152 }
1153 if (r.app != null && fgApp != null && r.app != fgApp
1154 && r.lastVisibleTime > mService.mPreviousProcessVisibleTime
1155 && r.app != mService.mHomeProcess) {
1156 mService.mPreviousProcess = r.app;
1157 mService.mPreviousProcessVisibleTime = r.lastVisibleTime;
1158 }
Dianne Hackborn50685602011-12-01 12:23:37 -08001159 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001160 }
1161 }
1162 }
1163
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001164 private final void completePauseLocked() {
1165 ActivityRecord prev = mPausingActivity;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001166 if (DEBUG_PAUSE) Slog.v(TAG, "Complete pause: " + prev);
1167
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001168 if (prev != null) {
1169 if (prev.finishing) {
1170 if (DEBUG_PAUSE) Slog.v(TAG, "Executing finish of activity: " + prev);
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001171 prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001172 } else if (prev.app != null) {
1173 if (DEBUG_PAUSE) Slog.v(TAG, "Enqueueing pending stop: " + prev);
1174 if (prev.waitingVisible) {
1175 prev.waitingVisible = false;
1176 mWaitingVisibleActivities.remove(prev);
1177 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(
1178 TAG, "Complete pause, no longer waiting: " + prev);
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001179 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001180 if (prev.configDestroy) {
1181 // The previous is being paused because the configuration
1182 // is changing, which means it is actually stopping...
1183 // To juggle the fact that we are also starting a new
1184 // instance right now, we need to first completely stop
1185 // the current instance before starting the new one.
1186 if (DEBUG_PAUSE) Slog.v(TAG, "Destroying after pause: " + prev);
1187 destroyActivityLocked(prev, true, false, "pause-config");
1188 } else {
1189 mStoppingActivities.add(prev);
1190 if (mStoppingActivities.size() > 3) {
1191 // If we already have a few activities waiting to stop,
1192 // then give up on things going idle and start clearing
1193 // them out.
1194 if (DEBUG_PAUSE) Slog.v(TAG, "To many pending stops, forcing idle");
1195 scheduleIdleLocked();
1196 } else {
1197 checkReadyForSleepLocked();
1198 }
1199 }
1200 } else {
1201 if (DEBUG_PAUSE) Slog.v(TAG, "App died during pause, not stopping: " + prev);
1202 prev = null;
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001203 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001204 mPausingActivity = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001205 }
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001206
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001207 if (!mService.isSleeping()) {
1208 resumeTopActivityLocked(prev);
1209 } else {
Dianne Hackborncbb722e2012-02-07 18:33:49 -08001210 checkReadyForSleepLocked();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001211 ActivityRecord top = topRunningActivityLocked(null);
1212 if (top == null || (prev != null && top != prev)) {
1213 // If there are no more activities available to run,
1214 // do resume anyway to start something. Also if the top
1215 // activity on the stack is not the just paused activity,
1216 // we need to go ahead and resume it to ensure we complete
1217 // an in-flight app switch.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07001218 resumeTopActivityLocked(null);
1219 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001220 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001221
1222 if (prev != null) {
1223 prev.resumeKeyDispatchingLocked();
1224 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001225
1226 if (prev.app != null && prev.cpuTimeAtResume > 0
1227 && mService.mBatteryStatsService.isOnBattery()) {
1228 long diff = 0;
1229 synchronized (mService.mProcessStatsThread) {
1230 diff = mService.mProcessStats.getCpuTimeForPid(prev.app.pid)
1231 - prev.cpuTimeAtResume;
1232 }
1233 if (diff > 0) {
1234 BatteryStatsImpl bsi = mService.mBatteryStatsService.getActiveStatistics();
1235 synchronized (bsi) {
1236 BatteryStatsImpl.Uid.Proc ps =
1237 bsi.getProcessStatsLocked(prev.info.applicationInfo.uid,
1238 prev.info.packageName);
1239 if (ps != null) {
1240 ps.addForegroundTimeLocked(diff);
1241 }
1242 }
1243 }
1244 }
1245 prev.cpuTimeAtResume = 0; // reset it
1246 }
1247
1248 /**
1249 * Once we know that we have asked an application to put an activity in
1250 * the resumed state (either by launching it or explicitly telling it),
1251 * this function updates the rest of our state to match that fact.
1252 */
1253 private final void completeResumeLocked(ActivityRecord next) {
1254 next.idle = false;
1255 next.results = null;
1256 next.newIntents = null;
1257
1258 // schedule an idle timeout in case the app doesn't do it for us.
1259 Message msg = mHandler.obtainMessage(IDLE_TIMEOUT_MSG);
1260 msg.obj = next;
1261 mHandler.sendMessageDelayed(msg, IDLE_TIMEOUT);
1262
1263 if (false) {
1264 // The activity was never told to pause, so just keep
1265 // things going as-is. To maintain our own state,
1266 // we need to emulate it coming back and saying it is
1267 // idle.
1268 msg = mHandler.obtainMessage(IDLE_NOW_MSG);
1269 msg.obj = next;
1270 mHandler.sendMessage(msg);
1271 }
1272
1273 if (mMainStack) {
1274 mService.reportResumedActivityLocked(next);
1275 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07001276
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001277 if (mMainStack) {
1278 mService.setFocusedActivityLocked(next);
1279 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001280 next.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001281 ensureActivitiesVisibleLocked(null, 0);
1282 mService.mWindowManager.executeAppTransition();
1283 mNoAnimActivities.clear();
1284
1285 // Mark the point when the activity is resuming
1286 // TODO: To be more accurate, the mark should be before the onCreate,
1287 // not after the onResume. But for subsequent starts, onResume is fine.
1288 if (next.app != null) {
1289 synchronized (mService.mProcessStatsThread) {
1290 next.cpuTimeAtResume = mService.mProcessStats.getCpuTimeForPid(next.app.pid);
1291 }
1292 } else {
1293 next.cpuTimeAtResume = 0; // Couldn't get the cpu time of process
1294 }
1295 }
1296
1297 /**
1298 * Make sure that all activities that need to be visible (that is, they
1299 * currently can be seen by the user) actually are.
1300 */
1301 final void ensureActivitiesVisibleLocked(ActivityRecord top,
1302 ActivityRecord starting, String onlyThisProcess, int configChanges) {
1303 if (DEBUG_VISBILITY) Slog.v(
1304 TAG, "ensureActivitiesVisible behind " + top
1305 + " configChanges=0x" + Integer.toHexString(configChanges));
1306
1307 // If the top activity is not fullscreen, then we need to
1308 // make sure any activities under it are now visible.
1309 final int count = mHistory.size();
1310 int i = count-1;
1311 while (mHistory.get(i) != top) {
1312 i--;
1313 }
1314 ActivityRecord r;
1315 boolean behindFullscreen = false;
1316 for (; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001317 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001318 if (DEBUG_VISBILITY) Slog.v(
1319 TAG, "Make visible? " + r + " finishing=" + r.finishing
1320 + " state=" + r.state);
1321 if (r.finishing) {
1322 continue;
1323 }
1324
1325 final boolean doThisProcess = onlyThisProcess == null
1326 || onlyThisProcess.equals(r.processName);
1327
1328 // First: if this is not the current activity being started, make
1329 // sure it matches the current configuration.
1330 if (r != starting && doThisProcess) {
1331 ensureActivityConfigurationLocked(r, 0);
1332 }
1333
1334 if (r.app == null || r.app.thread == null) {
1335 if (onlyThisProcess == null
1336 || onlyThisProcess.equals(r.processName)) {
1337 // This activity needs to be visible, but isn't even
1338 // running... get it started, but don't resume it
1339 // at this point.
1340 if (DEBUG_VISBILITY) Slog.v(
1341 TAG, "Start and freeze screen for " + r);
1342 if (r != starting) {
1343 r.startFreezingScreenLocked(r.app, configChanges);
1344 }
1345 if (!r.visible) {
1346 if (DEBUG_VISBILITY) Slog.v(
1347 TAG, "Starting and making visible: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001348 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001349 }
1350 if (r != starting) {
1351 startSpecificActivityLocked(r, false, false);
1352 }
1353 }
1354
1355 } else if (r.visible) {
1356 // If this activity is already visible, then there is nothing
1357 // else to do here.
1358 if (DEBUG_VISBILITY) Slog.v(
1359 TAG, "Skipping: already visible at " + r);
1360 r.stopFreezingScreenLocked(false);
1361
1362 } else if (onlyThisProcess == null) {
1363 // This activity is not currently visible, but is running.
1364 // Tell it to become visible.
1365 r.visible = true;
1366 if (r.state != ActivityState.RESUMED && r != starting) {
1367 // If this activity is paused, tell it
1368 // to now show its window.
1369 if (DEBUG_VISBILITY) Slog.v(
1370 TAG, "Making visible and scheduling visibility: " + r);
1371 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001372 mService.mWindowManager.setAppVisibility(r.appToken, true);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001373 r.sleeping = false;
Dianne Hackborn905577f2011-09-07 18:31:28 -07001374 r.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001375 r.app.thread.scheduleWindowVisibility(r.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001376 r.stopFreezingScreenLocked(false);
1377 } catch (Exception e) {
1378 // Just skip on any failure; we'll make it
1379 // visible when it next restarts.
1380 Slog.w(TAG, "Exception thrown making visibile: "
1381 + r.intent.getComponent(), e);
1382 }
1383 }
1384 }
1385
1386 // Aggregate current change flags.
1387 configChanges |= r.configChangeFlags;
1388
1389 if (r.fullscreen) {
1390 // At this point, nothing else needs to be shown
1391 if (DEBUG_VISBILITY) Slog.v(
1392 TAG, "Stopping: fullscreen at " + r);
1393 behindFullscreen = true;
1394 i--;
1395 break;
1396 }
1397 }
1398
1399 // Now for any activities that aren't visible to the user, make
1400 // sure they no longer are keeping the screen frozen.
1401 while (i >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001402 r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001403 if (DEBUG_VISBILITY) Slog.v(
1404 TAG, "Make invisible? " + r + " finishing=" + r.finishing
1405 + " state=" + r.state
1406 + " behindFullscreen=" + behindFullscreen);
1407 if (!r.finishing) {
1408 if (behindFullscreen) {
1409 if (r.visible) {
1410 if (DEBUG_VISBILITY) Slog.v(
1411 TAG, "Making invisible: " + r);
1412 r.visible = false;
1413 try {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001414 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001415 if ((r.state == ActivityState.STOPPING
1416 || r.state == ActivityState.STOPPED)
1417 && r.app != null && r.app.thread != null) {
1418 if (DEBUG_VISBILITY) Slog.v(
1419 TAG, "Scheduling invisibility: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001420 r.app.thread.scheduleWindowVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001421 }
1422 } catch (Exception e) {
1423 // Just skip on any failure; we'll make it
1424 // visible when it next restarts.
1425 Slog.w(TAG, "Exception thrown making hidden: "
1426 + r.intent.getComponent(), e);
1427 }
1428 } else {
1429 if (DEBUG_VISBILITY) Slog.v(
1430 TAG, "Already invisible: " + r);
1431 }
1432 } else if (r.fullscreen) {
1433 if (DEBUG_VISBILITY) Slog.v(
1434 TAG, "Now behindFullscreen: " + r);
1435 behindFullscreen = true;
1436 }
1437 }
1438 i--;
1439 }
1440 }
1441
1442 /**
1443 * Version of ensureActivitiesVisible that can easily be called anywhere.
1444 */
1445 final void ensureActivitiesVisibleLocked(ActivityRecord starting,
1446 int configChanges) {
1447 ActivityRecord r = topRunningActivityLocked(null);
1448 if (r != null) {
1449 ensureActivitiesVisibleLocked(r, starting, null, configChanges);
1450 }
1451 }
1452
1453 /**
1454 * Ensure that the top activity in the stack is resumed.
1455 *
1456 * @param prev The previously resumed activity, for when in the process
1457 * of pausing; can be null to call from elsewhere.
1458 *
1459 * @return Returns true if something is being resumed, or false if
1460 * nothing happened.
1461 */
1462 final boolean resumeTopActivityLocked(ActivityRecord prev) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001463 return resumeTopActivityLocked(prev, null);
1464 }
1465
1466 final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001467 // Find the first activity that is not finishing.
1468 ActivityRecord next = topRunningActivityLocked(null);
1469
1470 // Remember how we'll process this pause/resume situation, and ensure
1471 // that the state is reset however we wind up proceeding.
1472 final boolean userLeaving = mUserLeaving;
1473 mUserLeaving = false;
1474
1475 if (next == null) {
1476 // There are no more activities! Let's just start up the
1477 // Launcher...
1478 if (mMainStack) {
Dianne Hackborn84375872012-06-01 19:03:50 -07001479 ActivityOptions.abort(options);
Dianne Hackborn5dc5a002012-09-15 19:33:48 -07001480 return mService.startHomeActivityLocked(mCurrentUser);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001481 }
1482 }
1483
1484 next.delayedResume = false;
1485
1486 // If the top activity is the resumed one, nothing to do.
1487 if (mResumedActivity == next && next.state == ActivityState.RESUMED) {
1488 // Make sure we have executed any pending transitions, since there
1489 // should be nothing left to do at this point.
1490 mService.mWindowManager.executeAppTransition();
1491 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001492 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001493 return false;
1494 }
1495
1496 // If we are sleeping, and there is no resumed activity, and the top
1497 // activity is paused, well that is the state we want.
1498 if ((mService.mSleeping || mService.mShuttingDown)
p13451dbad2872012-04-18 11:39:23 +09001499 && mLastPausedActivity == next
1500 && (next.state == ActivityState.PAUSED
1501 || next.state == ActivityState.STOPPED
1502 || next.state == ActivityState.STOPPING)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001503 // Make sure we have executed any pending transitions, since there
1504 // should be nothing left to do at this point.
1505 mService.mWindowManager.executeAppTransition();
1506 mNoAnimActivities.clear();
Dianne Hackborn84375872012-06-01 19:03:50 -07001507 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001508 return false;
1509 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001510
1511 // Make sure that the user who owns this activity is started. If not,
1512 // we will just leave it as is because someone should be bringing
1513 // another user's activities to the top of the stack.
1514 if (mService.mStartedUsers.get(next.userId) == null) {
1515 Slog.w(TAG, "Skipping resume of top activity " + next
1516 + ": user " + next.userId + " is stopped");
1517 return false;
1518 }
1519
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001520 // The activity may be waiting for stop, but that is no longer
1521 // appropriate for it.
1522 mStoppingActivities.remove(next);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001523 mGoingToSleepActivities.remove(next);
1524 next.sleeping = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001525 mWaitingVisibleActivities.remove(next);
1526
Dianne Hackborn84375872012-06-01 19:03:50 -07001527 next.updateOptionsLocked(options);
1528
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001529 if (DEBUG_SWITCH) Slog.v(TAG, "Resuming " + next);
1530
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001531 // If we are currently pausing an activity, then don't do anything
1532 // until that is done.
1533 if (mPausingActivity != null) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07001534 if (DEBUG_SWITCH || DEBUG_PAUSE) Slog.v(TAG,
1535 "Skip resume: pausing=" + mPausingActivity);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08001536 return false;
1537 }
1538
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001539 // Okay we are now going to start a switch, to 'next'. We may first
1540 // have to pause the current activity, but this is an important point
1541 // where we have decided to go to 'next' so keep track of that.
Dianne Hackborn034093a42010-09-20 22:24:38 -07001542 // XXX "App Redirected" dialog is getting too many false positives
1543 // at this point, so turn off for now.
1544 if (false) {
1545 if (mLastStartedActivity != null && !mLastStartedActivity.finishing) {
1546 long now = SystemClock.uptimeMillis();
1547 final boolean inTime = mLastStartedActivity.startTime != 0
1548 && (mLastStartedActivity.startTime + START_WARN_TIME) >= now;
1549 final int lastUid = mLastStartedActivity.info.applicationInfo.uid;
1550 final int nextUid = next.info.applicationInfo.uid;
1551 if (inTime && lastUid != nextUid
1552 && lastUid != next.launchedFromUid
1553 && mService.checkPermission(
1554 android.Manifest.permission.STOP_APP_SWITCHES,
1555 -1, next.launchedFromUid)
1556 != PackageManager.PERMISSION_GRANTED) {
1557 mService.showLaunchWarningLocked(mLastStartedActivity, next);
1558 } else {
1559 next.startTime = now;
1560 mLastStartedActivity = next;
1561 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001562 } else {
Dianne Hackborn034093a42010-09-20 22:24:38 -07001563 next.startTime = SystemClock.uptimeMillis();
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001564 mLastStartedActivity = next;
1565 }
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001566 }
1567
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001568 // We need to start pausing the current activity so the top one
1569 // can be resumed...
1570 if (mResumedActivity != null) {
1571 if (DEBUG_SWITCH) Slog.v(TAG, "Skip resume: need to start pausing");
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001572 // At this point we want to put the upcoming activity's process
1573 // at the top of the LRU list, since we know we will be needing it
1574 // very soon and it would be a waste to let it get killed if it
1575 // happens to be sitting towards the end.
1576 if (next.app != null && next.app.thread != null) {
1577 // No reason to do full oom adj update here; we'll let that
1578 // happen whenever it needs to later.
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001579 mService.updateLruProcessLocked(next.app, false);
Dianne Hackbornad9b32112012-09-17 15:35:01 -07001580 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001581 startPausingLocked(userLeaving, false);
1582 return true;
1583 }
1584
Christopher Tated3f175c2012-06-14 14:16:54 -07001585 // If the most recent activity was noHistory but was only stopped rather
1586 // than stopped+finished because the device went to sleep, we need to make
1587 // sure to finish it as we're making a new activity topmost.
1588 final ActivityRecord last = mLastPausedActivity;
1589 if (mService.mSleeping && last != null && !last.finishing) {
1590 if ((last.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
1591 || (last.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
1592 if (DEBUG_STATES) {
1593 Slog.d(TAG, "no-history finish of " + last + " on new resume");
1594 }
1595 requestFinishActivityLocked(last.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001596 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07001597 }
1598 }
1599
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001600 if (prev != null && prev != next) {
1601 if (!prev.waitingVisible && next != null && !next.nowVisible) {
1602 prev.waitingVisible = true;
1603 mWaitingVisibleActivities.add(prev);
1604 if (DEBUG_SWITCH) Slog.v(
1605 TAG, "Resuming top, waiting visible to hide: " + prev);
1606 } else {
1607 // The next activity is already visible, so hide the previous
1608 // activity's windows right now so we can show the new one ASAP.
1609 // We only do this if the previous is finishing, which should mean
1610 // it is on top of the one being resumed so hiding it quickly
1611 // is good. Otherwise, we want to do the normal route of allowing
1612 // the resumed activity to be shown so we can decide if the
1613 // previous should actually be hidden depending on whether the
1614 // new one is found to be full-screen or not.
1615 if (prev.finishing) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001616 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001617 if (DEBUG_SWITCH) Slog.v(TAG, "Not waiting for visible to hide: "
1618 + prev + ", waitingVisible="
1619 + (prev != null ? prev.waitingVisible : null)
1620 + ", nowVisible=" + next.nowVisible);
1621 } else {
1622 if (DEBUG_SWITCH) Slog.v(TAG, "Previous already visible but still waiting to hide: "
1623 + prev + ", waitingVisible="
1624 + (prev != null ? prev.waitingVisible : null)
1625 + ", nowVisible=" + next.nowVisible);
1626 }
1627 }
1628 }
1629
Dianne Hackborne7f97212011-02-24 14:40:20 -08001630 // Launching this app's activity, make sure the app is no longer
1631 // considered stopped.
1632 try {
1633 AppGlobals.getPackageManager().setPackageStoppedState(
Amith Yamasani483f3b02012-03-13 16:08:00 -07001634 next.packageName, false, next.userId); /* TODO: Verify if correct userid */
Dianne Hackborne7f97212011-02-24 14:40:20 -08001635 } catch (RemoteException e1) {
Dianne Hackborna925cd42011-03-10 13:18:20 -08001636 } catch (IllegalArgumentException e) {
1637 Slog.w(TAG, "Failed trying to unstop package "
1638 + next.packageName + ": " + e);
Dianne Hackborne7f97212011-02-24 14:40:20 -08001639 }
1640
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001641 // We are starting up the next activity, so tell the window manager
1642 // that the previous one will be hidden soon. This way it can know
1643 // to ignore it when computing the desired screen orientation.
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001644 boolean noAnim = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001645 if (prev != null) {
1646 if (prev.finishing) {
1647 if (DEBUG_TRANSITION) Slog.v(TAG,
1648 "Prepare close transition: prev=" + prev);
1649 if (mNoAnimActivities.contains(prev)) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001650 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001651 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001652 } else {
1653 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001654 ? AppTransition.TRANSIT_ACTIVITY_CLOSE
1655 : AppTransition.TRANSIT_TASK_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001656 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08001657 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1658 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001659 } else {
1660 if (DEBUG_TRANSITION) Slog.v(TAG,
1661 "Prepare open transition: prev=" + prev);
1662 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001663 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001664 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001665 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001666 } else {
1667 mService.mWindowManager.prepareAppTransition(prev.task == next.task
Craig Mautner4b71aa12012-12-27 17:20:01 -08001668 ? AppTransition.TRANSIT_ACTIVITY_OPEN
1669 : AppTransition.TRANSIT_TASK_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001670 }
1671 }
1672 if (false) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001673 mService.mWindowManager.setAppWillBeHidden(prev.appToken);
1674 mService.mWindowManager.setAppVisibility(prev.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001675 }
1676 } else if (mHistory.size() > 1) {
1677 if (DEBUG_TRANSITION) Slog.v(TAG,
1678 "Prepare open transition: no previous");
1679 if (mNoAnimActivities.contains(next)) {
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001680 noAnim = true;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001681 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001682 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001683 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001684 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001685 AppTransition.TRANSIT_ACTIVITY_OPEN, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001686 }
1687 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001688 if (!noAnim) {
1689 next.applyOptionsLocked();
1690 } else {
1691 next.clearOptionsLocked();
1692 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001693
1694 if (next.app != null && next.app.thread != null) {
1695 if (DEBUG_SWITCH) Slog.v(TAG, "Resume running: " + next);
1696
1697 // This activity is now becoming visible.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001698 mService.mWindowManager.setAppVisibility(next.appToken, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001699
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07001700 // schedule launch ticks to collect information about slow apps.
1701 next.startLaunchTickingLocked();
1702
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001703 ActivityRecord lastResumedActivity = mResumedActivity;
1704 ActivityState lastState = next.state;
1705
1706 mService.updateCpuStats();
1707
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001708 if (DEBUG_STATES) Slog.v(TAG, "Moving to RESUMED: " + next + " (in existing)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001709 next.state = ActivityState.RESUMED;
1710 mResumedActivity = next;
1711 next.task.touchActiveTime();
Dianne Hackborn88819b22010-12-21 18:18:02 -08001712 if (mMainStack) {
1713 mService.addRecentTaskLocked(next.task);
1714 }
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001715 mService.updateLruProcessLocked(next.app, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001716 updateLRUListLocked(next);
1717
1718 // Have the window manager re-evaluate the orientation of
1719 // the screen based on the new activity order.
1720 boolean updated = false;
1721 if (mMainStack) {
1722 synchronized (mService) {
1723 Configuration config = mService.mWindowManager.updateOrientationFromAppTokens(
1724 mService.mConfiguration,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001725 next.mayFreezeScreenLocked(next.app) ? next.appToken : null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001726 if (config != null) {
1727 next.frozenBeforeDestroy = true;
1728 }
Dianne Hackborn813075a62011-11-14 17:45:19 -08001729 updated = mService.updateConfigurationLocked(config, next, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001730 }
1731 }
1732 if (!updated) {
1733 // The configuration update wasn't able to keep the existing
1734 // instance of the activity, and instead started a new one.
1735 // We should be all done, but let's just make sure our activity
1736 // is still at the top and schedule another run if something
1737 // weird happened.
1738 ActivityRecord nextNext = topRunningActivityLocked(null);
1739 if (DEBUG_SWITCH) Slog.i(TAG,
1740 "Activity config changed during resume: " + next
1741 + ", new next: " + nextNext);
1742 if (nextNext != next) {
1743 // Do over!
1744 mHandler.sendEmptyMessage(RESUME_TOP_ACTIVITY_MSG);
1745 }
1746 if (mMainStack) {
1747 mService.setFocusedActivityLocked(next);
1748 }
1749 ensureActivitiesVisibleLocked(null, 0);
1750 mService.mWindowManager.executeAppTransition();
1751 mNoAnimActivities.clear();
1752 return true;
1753 }
1754
1755 try {
1756 // Deliver all pending results.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08001757 ArrayList<ResultInfo> a = next.results;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001758 if (a != null) {
1759 final int N = a.size();
1760 if (!next.finishing && N > 0) {
1761 if (DEBUG_RESULTS) Slog.v(
1762 TAG, "Delivering results to " + next
1763 + ": " + a);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001764 next.app.thread.scheduleSendResult(next.appToken, a);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001765 }
1766 }
1767
1768 if (next.newIntents != null) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001769 next.app.thread.scheduleNewIntent(next.newIntents, next.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001770 }
1771
1772 EventLog.writeEvent(EventLogTags.AM_RESUME_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07001773 next.userId, System.identityHashCode(next),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001774 next.task.taskId, next.shortComponentName);
1775
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001776 next.sleeping = false;
Dianne Hackborn36cd41f2011-05-25 21:00:46 -07001777 showAskCompatModeDialogLocked(next);
Dianne Hackborn905577f2011-09-07 18:31:28 -07001778 next.app.pendingUiClean = true;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001779 next.app.thread.scheduleResumeActivity(next.appToken,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001780 mService.isNextTransitionForward());
1781
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08001782 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001783
1784 } catch (Exception e) {
1785 // Whoops, need to restart this activity!
Dianne Hackbornce86ba82011-07-13 19:33:41 -07001786 if (DEBUG_STATES) Slog.v(TAG, "Resume failed; resetting state to "
1787 + lastState + ": " + next);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001788 next.state = lastState;
1789 mResumedActivity = lastResumedActivity;
1790 Slog.i(TAG, "Restarting because process died: " + next);
1791 if (!next.hasBeenLaunched) {
1792 next.hasBeenLaunched = true;
1793 } else {
1794 if (SHOW_APP_STARTING_PREVIEW && mMainStack) {
1795 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001796 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001797 mService.compatibilityInfoForPackageLocked(
1798 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001799 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001800 next.labelRes, next.icon, next.windowFlags,
1801 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001802 }
1803 }
1804 startSpecificActivityLocked(next, true, false);
1805 return true;
1806 }
1807
1808 // From this point on, if something goes wrong there is no way
1809 // to recover the activity.
1810 try {
1811 next.visible = true;
1812 completeResumeLocked(next);
1813 } catch (Exception e) {
1814 // If any exception gets thrown, toss away this
1815 // activity and try the next one.
1816 Slog.w(TAG, "Exception thrown during resume of " + next, e);
Dianne Hackbornbe707852011-11-11 14:32:10 -08001817 requestFinishActivityLocked(next.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07001818 "resume-exception", true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001819 return true;
1820 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001821 next.stopped = false;
1822
1823 } else {
1824 // Whoops, need to restart this activity!
1825 if (!next.hasBeenLaunched) {
1826 next.hasBeenLaunched = true;
1827 } else {
1828 if (SHOW_APP_STARTING_PREVIEW) {
1829 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001830 next.appToken, next.packageName, next.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001831 mService.compatibilityInfoForPackageLocked(
1832 next.info.applicationInfo),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001833 next.nonLocalizedLabel,
Dianne Hackborn7eec10e2010-11-12 18:03:47 -08001834 next.labelRes, next.icon, next.windowFlags,
1835 null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001836 }
1837 if (DEBUG_SWITCH) Slog.v(TAG, "Restarting: " + next);
1838 }
1839 startSpecificActivityLocked(next, true, true);
1840 }
1841
1842 return true;
1843 }
1844
1845 private final void startActivityLocked(ActivityRecord r, boolean newTask,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001846 boolean doResume, boolean keepCurTransition, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001847 final int NH = mHistory.size();
1848
1849 int addPos = -1;
1850
1851 if (!newTask) {
1852 // If starting in an existing task, find where that is...
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001853 boolean startIt = true;
1854 for (int i = NH-1; i >= 0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07001855 ActivityRecord p = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001856 if (p.finishing) {
1857 continue;
1858 }
1859 if (p.task == r.task) {
1860 // Here it is! Now, if this is not yet visible to the
1861 // user, then just add it without starting; it will
1862 // get started when the user navigates back to it.
1863 addPos = i+1;
1864 if (!startIt) {
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001865 if (DEBUG_ADD_REMOVE) {
1866 RuntimeException here = new RuntimeException("here");
1867 here.fillInStackTrace();
1868 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos,
1869 here);
1870 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001871 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001872 r.putInHistory();
Dianne Hackbornbe707852011-11-11 14:32:10 -08001873 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07001874 r.info.screenOrientation, r.fullscreen,
1875 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001876 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001877 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001878 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001879 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001880 return;
1881 }
1882 break;
1883 }
1884 if (p.fullscreen) {
1885 startIt = false;
1886 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001887 }
1888 }
1889
1890 // Place a new activity at top of stack, so it is next to interact
1891 // with the user.
1892 if (addPos < 0) {
Dianne Hackborn0dad3642010-09-09 21:25:35 -07001893 addPos = NH;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001894 }
1895
1896 // If we are not placing the new activity frontmost, we do not want
1897 // to deliver the onUserLeaving callback to the actual frontmost
1898 // activity
1899 if (addPos < NH) {
1900 mUserLeaving = false;
1901 if (DEBUG_USER_LEAVING) Slog.v(TAG, "startActivity() behind front, mUserLeaving=false");
1902 }
1903
1904 // Slot the activity into the history stack and proceed
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07001905 if (DEBUG_ADD_REMOVE) {
1906 RuntimeException here = new RuntimeException("here");
1907 here.fillInStackTrace();
1908 Slog.i(TAG, "Adding activity " + r + " to stack at " + addPos, here);
1909 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001910 mHistory.add(addPos, r);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07001911 r.putInHistory();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001912 r.frontOfTask = newTask;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001913 if (NH > 0) {
1914 // We want to show the starting preview window if we are
1915 // switching to a new task, or the next activity's process is
1916 // not currently running.
1917 boolean showStartingIcon = newTask;
1918 ProcessRecord proc = r.app;
1919 if (proc == null) {
1920 proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid);
1921 }
1922 if (proc == null || proc.thread == null) {
1923 showStartingIcon = true;
1924 }
1925 if (DEBUG_TRANSITION) Slog.v(TAG,
1926 "Prepare open transition: starting " + r);
1927 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08001928 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08001929 AppTransition.TRANSIT_NONE, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001930 mNoAnimActivities.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001931 } else {
1932 mService.mWindowManager.prepareAppTransition(newTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08001933 ? AppTransition.TRANSIT_TASK_OPEN
1934 : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001935 mNoAnimActivities.remove(r);
1936 }
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07001937 r.updateOptionsLocked(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001938 mService.mWindowManager.addAppToken(
Craig Mautner5962b122012-10-05 14:45:52 -07001939 addPos, r.appToken, r.task.taskId, r.info.screenOrientation, r.fullscreen,
1940 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001941 boolean doShow = true;
1942 if (newTask) {
1943 // Even though this activity is starting fresh, we still need
1944 // to reset it to make sure we apply affinities to move any
1945 // existing activities from other tasks in to it.
1946 // If the caller has requested that the target task be
1947 // reset, then do so.
1948 if ((r.intent.getFlags()
1949 &Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
1950 resetTaskIfNeededLocked(r, r);
1951 doShow = topRunningNonDelayedActivityLocked(null) == r;
1952 }
1953 }
1954 if (SHOW_APP_STARTING_PREVIEW && doShow) {
1955 // Figure out if we are transitioning from another activity that is
1956 // "has the same starting icon" as the next one. This allows the
1957 // window manager to keep the previous window it had previously
1958 // created, if it still had one.
1959 ActivityRecord prev = mResumedActivity;
1960 if (prev != null) {
1961 // We don't want to reuse the previous starting preview if:
1962 // (1) The current activity is in a different task.
1963 if (prev.task != r.task) prev = null;
1964 // (2) The current activity is already displayed.
1965 else if (prev.nowVisible) prev = null;
1966 }
1967 mService.mWindowManager.setAppStartingWindow(
Dianne Hackbornbe707852011-11-11 14:32:10 -08001968 r.appToken, r.packageName, r.theme,
Dianne Hackborn2f0b1752011-05-31 17:59:49 -07001969 mService.compatibilityInfoForPackageLocked(
1970 r.info.applicationInfo), r.nonLocalizedLabel,
Dianne Hackbornbe707852011-11-11 14:32:10 -08001971 r.labelRes, r.icon, r.windowFlags,
1972 prev != null ? prev.appToken : null, showStartingIcon);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001973 }
1974 } else {
1975 // If this is the first activity, don't do any fancy animations,
1976 // because there is nothing for it to animate on top of.
Dianne Hackbornbe707852011-11-11 14:32:10 -08001977 mService.mWindowManager.addAppToken(addPos, r.appToken, r.task.taskId,
Craig Mautner5962b122012-10-05 14:45:52 -07001978 r.info.screenOrientation, r.fullscreen,
1979 (r.info.flags & ActivityInfo.FLAG_SHOW_ON_LOCK_SCREEN) != 0);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07001980 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001981 }
1982 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08001983 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07001984 }
1985
1986 if (doResume) {
1987 resumeTopActivityLocked(null);
1988 }
1989 }
1990
Dianne Hackbornbe707852011-11-11 14:32:10 -08001991 final void validateAppTokensLocked() {
1992 mValidateAppTokens.clear();
1993 mValidateAppTokens.ensureCapacity(mHistory.size());
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08001994 int taskId = Integer.MIN_VALUE;
1995 TaskGroup task = null;
Dianne Hackbornbe707852011-11-11 14:32:10 -08001996 for (int i=0; i<mHistory.size(); i++) {
Craig Mautnerb1fd65c02013-02-05 13:34:57 -08001997 final ActivityRecord r = mHistory.get(i);
1998 if (taskId != r.task.taskId) {
1999 taskId = r.task.taskId;
2000 task = new TaskGroup();
2001 task.taskId = taskId;
2002 mValidateAppTokens.add(task);
2003 }
2004 task.tokens.add(r.appToken);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002005 }
2006 mService.mWindowManager.validateAppTokens(mValidateAppTokens);
2007 }
2008
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002009 /**
2010 * Perform a reset of the given task, if needed as part of launching it.
2011 * Returns the new HistoryRecord at the top of the task.
2012 */
2013 private final ActivityRecord resetTaskIfNeededLocked(ActivityRecord taskTop,
2014 ActivityRecord newActivity) {
2015 boolean forceReset = (newActivity.info.flags
2016 &ActivityInfo.FLAG_CLEAR_TASK_ON_LAUNCH) != 0;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002017 if (ACTIVITY_INACTIVE_RESET_TIME > 0
2018 && taskTop.task.getInactiveDuration() > ACTIVITY_INACTIVE_RESET_TIME) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002019 if ((newActivity.info.flags
2020 &ActivityInfo.FLAG_ALWAYS_RETAIN_TASK_STATE) == 0) {
2021 forceReset = true;
2022 }
2023 }
2024
2025 final TaskRecord task = taskTop.task;
2026
2027 // We are going to move through the history list so that we can look
2028 // at each activity 'target' with 'below' either the interesting
2029 // activity immediately below it in the stack or null.
2030 ActivityRecord target = null;
2031 int targetI = 0;
2032 int taskTopI = -1;
2033 int replyChainEnd = -1;
2034 int lastReparentPos = -1;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002035 ActivityOptions topOptions = null;
2036 boolean canMoveOptions = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002037 for (int i=mHistory.size()-1; i>=-1; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002038 ActivityRecord below = i >= 0 ? mHistory.get(i) : null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002039
2040 if (below != null && below.finishing) {
2041 continue;
2042 }
Amith Yamasani04e0d262012-02-14 11:50:53 -08002043 // Don't check any lower in the stack if we're crossing a user boundary.
2044 if (below != null && below.userId != taskTop.userId) {
2045 break;
2046 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002047 if (target == null) {
2048 target = below;
2049 targetI = i;
2050 // If we were in the middle of a reply chain before this
2051 // task, it doesn't appear like the root of the chain wants
2052 // anything interesting, so drop it.
2053 replyChainEnd = -1;
2054 continue;
2055 }
2056
2057 final int flags = target.info.flags;
2058
2059 final boolean finishOnTaskLaunch =
2060 (flags&ActivityInfo.FLAG_FINISH_ON_TASK_LAUNCH) != 0;
2061 final boolean allowTaskReparenting =
2062 (flags&ActivityInfo.FLAG_ALLOW_TASK_REPARENTING) != 0;
2063
2064 if (target.task == task) {
2065 // We are inside of the task being reset... we'll either
2066 // finish this activity, push it out for another task,
2067 // or leave it as-is. We only do this
2068 // for activities that are not the root of the task (since
2069 // if we finish the root, we may no longer have the task!).
2070 if (taskTopI < 0) {
2071 taskTopI = targetI;
2072 }
2073 if (below != null && below.task == task) {
2074 final boolean clearWhenTaskReset =
2075 (target.intent.getFlags()
2076 &Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0;
2077 if (!finishOnTaskLaunch && !clearWhenTaskReset && target.resultTo != null) {
2078 // If this activity is sending a reply to a previous
2079 // activity, we can't do anything with it now until
2080 // we reach the start of the reply chain.
2081 // XXX note that we are assuming the result is always
2082 // to the previous activity, which is almost always
2083 // the case but we really shouldn't count on.
2084 if (replyChainEnd < 0) {
2085 replyChainEnd = targetI;
2086 }
2087 } else if (!finishOnTaskLaunch && !clearWhenTaskReset && allowTaskReparenting
2088 && target.taskAffinity != null
2089 && !target.taskAffinity.equals(task.affinity)) {
2090 // If this activity has an affinity for another
2091 // task, then we need to move it out of here. We will
2092 // move it as far out of the way as possible, to the
2093 // bottom of the activity stack. This also keeps it
2094 // correctly ordered with any activities we previously
2095 // moved.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002096 ActivityRecord p = mHistory.get(0);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002097 if (target.taskAffinity != null
2098 && target.taskAffinity.equals(p.task.affinity)) {
2099 // If the activity currently at the bottom has the
2100 // same task affinity as the one we are moving,
2101 // then merge it into the same task.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002102 target.setTask(p.task, p.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002103 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2104 + " out to bottom task " + p.task);
2105 } else {
2106 mService.mCurTask++;
2107 if (mService.mCurTask <= 0) {
2108 mService.mCurTask = 1;
2109 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002110 target.setTask(new TaskRecord(mService.mCurTask, target.info, null),
2111 null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002112 target.task.affinityIntent = target.intent;
2113 if (DEBUG_TASKS) Slog.v(TAG, "Start pushing activity " + target
2114 + " out to new task " + target.task);
2115 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08002116 mService.mWindowManager.setAppGroupId(target.appToken, task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002117 if (replyChainEnd < 0) {
2118 replyChainEnd = targetI;
2119 }
2120 int dstPos = 0;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002121 ThumbnailHolder curThumbHolder = target.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002122 boolean gotOptions = !canMoveOptions;
Craig Mautner30e2d722013-02-12 11:30:16 -08002123 final int taskId = target.task.taskId;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002124 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002125 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002126 if (p.finishing) {
2127 continue;
2128 }
2129 if (DEBUG_TASKS) Slog.v(TAG, "Pushing next activity " + p
2130 + " out to target's task " + target.task);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002131 p.setTask(target.task, curThumbHolder, false);
2132 curThumbHolder = p.thumbHolder;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002133 canMoveOptions = false;
2134 if (!gotOptions && topOptions == null) {
2135 topOptions = p.takeOptionsLocked();
2136 if (topOptions != null) {
2137 gotOptions = true;
2138 }
2139 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002140 if (DEBUG_ADD_REMOVE) {
2141 RuntimeException here = new RuntimeException("here");
2142 here.fillInStackTrace();
2143 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2144 + dstPos, here);
2145 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002146 mHistory.remove(srcPos);
2147 mHistory.add(dstPos, p);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002148 mService.mWindowManager.moveAppToken(dstPos, p.appToken);
Craig Mautner30e2d722013-02-12 11:30:16 -08002149 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002150 dstPos++;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002151 i++;
2152 }
Craig Mautner30e2d722013-02-12 11:30:16 -08002153 mService.mWindowManager.moveTaskToBottom(taskId);
2154 if (VALIDATE_TOKENS) {
2155 validateAppTokensLocked();
2156 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002157 if (taskTop == p) {
2158 taskTop = below;
2159 }
2160 if (taskTopI == replyChainEnd) {
2161 taskTopI = -1;
2162 }
2163 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002164 } else if (forceReset || finishOnTaskLaunch
2165 || clearWhenTaskReset) {
2166 // If the activity should just be removed -- either
2167 // because it asks for it, or the task should be
2168 // cleared -- then finish it and anything that is
2169 // part of its reply chain.
2170 if (clearWhenTaskReset) {
2171 // In this case, we want to finish this activity
2172 // and everything above it, so be sneaky and pretend
2173 // like these are all in the reply chain.
2174 replyChainEnd = targetI+1;
2175 while (replyChainEnd < mHistory.size() &&
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002176 (mHistory.get(
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002177 replyChainEnd)).task == task) {
2178 replyChainEnd++;
2179 }
2180 replyChainEnd--;
2181 } else if (replyChainEnd < 0) {
2182 replyChainEnd = targetI;
2183 }
2184 ActivityRecord p = null;
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002185 boolean gotOptions = !canMoveOptions;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002186 for (int srcPos=targetI; srcPos<=replyChainEnd; srcPos++) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002187 p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002188 if (p.finishing) {
2189 continue;
2190 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002191 canMoveOptions = false;
2192 if (!gotOptions && topOptions == null) {
2193 topOptions = p.takeOptionsLocked();
2194 if (topOptions != null) {
2195 gotOptions = true;
2196 }
2197 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002198 if (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002199 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002200 replyChainEnd--;
2201 srcPos--;
2202 }
2203 }
2204 if (taskTop == p) {
2205 taskTop = below;
2206 }
2207 if (taskTopI == replyChainEnd) {
2208 taskTopI = -1;
2209 }
2210 replyChainEnd = -1;
2211 } else {
2212 // If we were in the middle of a chain, well the
2213 // activity that started it all doesn't want anything
2214 // special, so leave it all as-is.
2215 replyChainEnd = -1;
2216 }
2217 } else {
2218 // Reached the bottom of the task -- any reply chain
2219 // should be left as-is.
2220 replyChainEnd = -1;
2221 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002222
2223 } else if (target.resultTo != null && (below == null
2224 || below.task == target.task)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002225 // If this activity is sending a reply to a previous
2226 // activity, we can't do anything with it now until
2227 // we reach the start of the reply chain.
2228 // XXX note that we are assuming the result is always
2229 // to the previous activity, which is almost always
2230 // the case but we really shouldn't count on.
2231 if (replyChainEnd < 0) {
2232 replyChainEnd = targetI;
2233 }
2234
2235 } else if (taskTopI >= 0 && allowTaskReparenting
2236 && task.affinity != null
2237 && task.affinity.equals(target.taskAffinity)) {
2238 // We are inside of another task... if this activity has
2239 // an affinity for our task, then either remove it if we are
2240 // clearing or move it over to our task. Note that
2241 // we currently punt on the case where we are resetting a
2242 // task that is not at the top but who has activities above
2243 // with an affinity to it... this is really not a normal
2244 // case, and we will need to later pull that task to the front
2245 // and usually at that point we will do the reset and pick
2246 // up those remaining activities. (This only happens if
2247 // someone starts an activity in a new task from an activity
2248 // in a task that is not currently on top.)
2249 if (forceReset || finishOnTaskLaunch) {
2250 if (replyChainEnd < 0) {
2251 replyChainEnd = targetI;
2252 }
2253 ActivityRecord p = null;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002254 if (DEBUG_TASKS) Slog.v(TAG, "Finishing task at index "
2255 + targetI + " to " + replyChainEnd);
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 (finishActivityLocked(p, srcPos,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002262 Activity.RESULT_CANCELED, null, "reset", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002263 taskTopI--;
2264 lastReparentPos--;
2265 replyChainEnd--;
2266 srcPos--;
2267 }
2268 }
2269 replyChainEnd = -1;
2270 } else {
2271 if (replyChainEnd < 0) {
2272 replyChainEnd = targetI;
2273 }
Craig Mautner30e2d722013-02-12 11:30:16 -08002274 final int taskId = task.taskId;
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002275 if (DEBUG_TASKS) Slog.v(TAG, "Reparenting task at index "
2276 + targetI + " to " + replyChainEnd);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002277 for (int srcPos=replyChainEnd; srcPos>=targetI; srcPos--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002278 ActivityRecord p = mHistory.get(srcPos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002279 if (p.finishing) {
2280 continue;
2281 }
2282 if (lastReparentPos < 0) {
2283 lastReparentPos = taskTopI;
2284 taskTop = p;
2285 } else {
2286 lastReparentPos--;
2287 }
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002288 if (DEBUG_ADD_REMOVE) {
2289 RuntimeException here = new RuntimeException("here");
2290 here.fillInStackTrace();
2291 Slog.i(TAG, "Removing and adding activity " + p + " to stack at "
2292 + lastReparentPos, here);
2293 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002294 mHistory.remove(srcPos);
Dianne Hackbornf26fd992011-04-08 18:14:09 -07002295 p.setTask(task, null, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002296 mHistory.add(lastReparentPos, p);
2297 if (DEBUG_TASKS) Slog.v(TAG, "Pulling activity " + p
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002298 + " from " + srcPos + " to " + lastReparentPos
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002299 + " in to resetting task " + task);
Dianne Hackbornbe707852011-11-11 14:32:10 -08002300 mService.mWindowManager.moveAppToken(lastReparentPos, p.appToken);
Craig Mautner30e2d722013-02-12 11:30:16 -08002301 mService.mWindowManager.setAppGroupId(p.appToken, taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002302 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002303 // TODO: This is wrong because it doesn't take lastReparentPos into account.
Craig Mautner30e2d722013-02-12 11:30:16 -08002304 mService.mWindowManager.moveTaskToTop(taskId);
2305 if (VALIDATE_TOKENS) {
2306 validateAppTokensLocked();
2307 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002308 replyChainEnd = -1;
2309
2310 // Now we've moved it in to place... but what if this is
2311 // a singleTop activity and we have put it on top of another
2312 // instance of the same activity? Then we drop the instance
2313 // below so it remains singleTop.
2314 if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) {
2315 for (int j=lastReparentPos-1; j>=0; j--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002316 ActivityRecord p = mHistory.get(j);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002317 if (p.finishing) {
2318 continue;
2319 }
2320 if (p.intent.getComponent().equals(target.intent.getComponent())) {
2321 if (finishActivityLocked(p, j,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002322 Activity.RESULT_CANCELED, null, "replace", false)) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002323 taskTopI--;
2324 lastReparentPos--;
2325 }
2326 }
2327 }
2328 }
2329 }
Dianne Hackbornae0a0a82011-12-07 14:03:01 -08002330
2331 } else if (below != null && below.task != target.task) {
2332 // We hit the botton of a task; the reply chain can't
2333 // pass through it.
2334 replyChainEnd = -1;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002335 }
2336
2337 target = below;
2338 targetI = i;
2339 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002340
2341 if (topOptions != null) {
2342 // If we got some ActivityOptions from an activity on top that
2343 // was removed from the task, propagate them to the new real top.
2344 if (taskTop != null) {
2345 taskTop.updateOptionsLocked(topOptions);
2346 } else {
2347 topOptions.abort();
2348 }
2349 }
2350
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002351 return taskTop;
2352 }
2353
2354 /**
2355 * Perform clear operation as requested by
2356 * {@link Intent#FLAG_ACTIVITY_CLEAR_TOP}: search from the top of the
2357 * stack to the given task, then look for
2358 * an instance of that activity in the stack and, if found, finish all
2359 * activities on top of it and return the instance.
2360 *
2361 * @param newR Description of the new activity being started.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002362 * @return Returns the old activity that should be continued to be used,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002363 * or null if none was found.
2364 */
2365 private final ActivityRecord performClearTaskLocked(int taskId,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002366 ActivityRecord newR, int launchFlags) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002367 int i = mHistory.size();
2368
2369 // First find the requested task.
2370 while (i > 0) {
2371 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002372 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002373 if (r.task.taskId == taskId) {
2374 i++;
2375 break;
2376 }
2377 }
2378
2379 // Now clear it.
2380 while (i > 0) {
2381 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002382 ActivityRecord r = mHistory.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002383 if (r.finishing) {
2384 continue;
2385 }
2386 if (r.task.taskId != taskId) {
2387 return null;
2388 }
2389 if (r.realActivity.equals(newR.realActivity)) {
2390 // Here it is! Now finish everything in front...
2391 ActivityRecord ret = r;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002392 while (i < (mHistory.size()-1)) {
2393 i++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002394 r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002395 if (r.task.taskId != taskId) {
2396 break;
2397 }
2398 if (r.finishing) {
2399 continue;
2400 }
Dianne Hackborn9622ca42012-10-23 18:56:33 -07002401 ActivityOptions opts = r.takeOptionsLocked();
2402 if (opts != null) {
2403 ret.updateOptionsLocked(opts);
2404 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002405 if (finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002406 null, "clear", false)) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002407 i--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002408 }
2409 }
2410
2411 // Finally, if this is a normal launch mode (that is, not
2412 // expecting onNewIntent()), then we will finish the current
2413 // instance of the activity so a new fresh one can be started.
2414 if (ret.launchMode == ActivityInfo.LAUNCH_MULTIPLE
2415 && (launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) == 0) {
2416 if (!ret.finishing) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08002417 int index = mHistory.indexOf(ret);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002418 if (index >= 0) {
2419 finishActivityLocked(ret, index, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002420 null, "clear", false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002421 }
2422 return null;
2423 }
2424 }
2425
2426 return ret;
2427 }
2428 }
2429
2430 return null;
2431 }
2432
2433 /**
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002434 * Completely remove all activities associated with an existing
2435 * task starting at a specified index.
2436 */
2437 private final void performClearTaskAtIndexLocked(int taskId, int i) {
Dianne Hackborneabd3282011-10-13 16:26:49 -07002438 while (i < mHistory.size()) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002439 ActivityRecord r = mHistory.get(i);
2440 if (r.task.taskId != taskId) {
2441 // Whoops hit the end.
2442 return;
2443 }
2444 if (r.finishing) {
2445 i++;
2446 continue;
2447 }
2448 if (!finishActivityLocked(r, i, Activity.RESULT_CANCELED,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07002449 null, "clear", false)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002450 i++;
2451 }
2452 }
2453 }
2454
2455 /**
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002456 * Completely remove all activities associated with an existing task.
2457 */
2458 private final void performClearTaskLocked(int taskId) {
2459 int i = mHistory.size();
2460
2461 // First find the requested task.
2462 while (i > 0) {
2463 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002464 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002465 if (r.task.taskId == taskId) {
2466 i++;
2467 break;
2468 }
2469 }
2470
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002471 // Now find the start and clear it.
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002472 while (i > 0) {
2473 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002474 ActivityRecord r = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002475 if (r.finishing) {
2476 continue;
2477 }
2478 if (r.task.taskId != taskId) {
2479 // We hit the bottom. Now finish it all...
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002480 performClearTaskAtIndexLocked(taskId, i+1);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002481 return;
2482 }
2483 }
2484 }
2485
2486 /**
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002487 * Find the activity in the history stack within the given task. Returns
2488 * the index within the history at which it's found, or < 0 if not found.
2489 */
2490 private final int findActivityInHistoryLocked(ActivityRecord r, int task) {
2491 int i = mHistory.size();
2492 while (i > 0) {
2493 i--;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002494 ActivityRecord candidate = mHistory.get(i);
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07002495 if (candidate.finishing) {
2496 continue;
2497 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002498 if (candidate.task.taskId != task) {
2499 break;
2500 }
2501 if (candidate.realActivity.equals(r.realActivity)) {
2502 return i;
2503 }
2504 }
2505
2506 return -1;
2507 }
2508
2509 /**
2510 * Reorder the history stack so that the activity at the given index is
2511 * brought to the front.
2512 */
2513 private final ActivityRecord moveActivityToFrontLocked(int where) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002514 ActivityRecord newTop = mHistory.remove(where);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002515 int top = mHistory.size();
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002516 ActivityRecord oldTop = mHistory.get(top-1);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002517 if (DEBUG_ADD_REMOVE) {
2518 RuntimeException here = new RuntimeException("here");
2519 here.fillInStackTrace();
2520 Slog.i(TAG, "Removing and adding activity " + newTop + " to stack at "
2521 + top, here);
2522 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002523 mHistory.add(top, newTop);
2524 oldTop.frontOfTask = false;
2525 newTop.frontOfTask = true;
2526 return newTop;
2527 }
2528
2529 final int startActivityLocked(IApplicationThread caller,
Dianne Hackborna4972e92012-03-14 10:38:05 -07002530 Intent intent, String resolvedType, ActivityInfo aInfo, IBinder resultTo,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002531 String resultWho, int requestCode,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002532 int callingPid, int callingUid, String callingPackage, int startFlags, Bundle options,
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002533 boolean componentSpecified, ActivityRecord[] outActivity) {
Dianne Hackbornefb58102010-10-14 16:47:34 -07002534
Dianne Hackborna4972e92012-03-14 10:38:05 -07002535 int err = ActivityManager.START_SUCCESS;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002536
2537 ProcessRecord callerApp = null;
2538 if (caller != null) {
2539 callerApp = mService.getRecordForAppLocked(caller);
2540 if (callerApp != null) {
2541 callingPid = callerApp.pid;
2542 callingUid = callerApp.info.uid;
2543 } else {
2544 Slog.w(TAG, "Unable to find app for caller " + caller
2545 + " (pid=" + callingPid + ") when starting: "
2546 + intent.toString());
Dianne Hackborna4972e92012-03-14 10:38:05 -07002547 err = ActivityManager.START_PERMISSION_DENIED;
Dianne Hackbornefb58102010-10-14 16:47:34 -07002548 }
2549 }
2550
Dianne Hackborna4972e92012-03-14 10:38:05 -07002551 if (err == ActivityManager.START_SUCCESS) {
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002552 final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
Dianne Hackborn5fe7e2a2012-10-04 11:58:16 -07002553 Slog.i(TAG, "START u" + userId + " {" + intent.toShortString(true, true, true, false)
2554 + "} from pid " + (callerApp != null ? callerApp.pid : callingPid));
Dianne Hackbornefb58102010-10-14 16:47:34 -07002555 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002556
2557 ActivityRecord sourceRecord = null;
2558 ActivityRecord resultRecord = null;
2559 if (resultTo != null) {
2560 int index = indexOfTokenLocked(resultTo);
2561 if (DEBUG_RESULTS) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07002562 TAG, "Will send result to " + resultTo + " (index " + index + ")");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002563 if (index >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07002564 sourceRecord = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002565 if (requestCode >= 0 && !sourceRecord.finishing) {
2566 resultRecord = sourceRecord;
2567 }
2568 }
2569 }
2570
2571 int launchFlags = intent.getFlags();
2572
2573 if ((launchFlags&Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0
2574 && sourceRecord != null) {
2575 // Transfer the result target from the source activity to the new
2576 // one being started, including any failures.
2577 if (requestCode >= 0) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002578 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002579 return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002580 }
2581 resultRecord = sourceRecord.resultTo;
2582 resultWho = sourceRecord.resultWho;
2583 requestCode = sourceRecord.requestCode;
2584 sourceRecord.resultTo = null;
2585 if (resultRecord != null) {
2586 resultRecord.removeResultsLocked(
2587 sourceRecord, resultWho, requestCode);
2588 }
2589 }
2590
Dianne Hackborna4972e92012-03-14 10:38:05 -07002591 if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002592 // We couldn't find a class that can handle the given Intent.
2593 // That's the end of that!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002594 err = ActivityManager.START_INTENT_NOT_RESOLVED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002595 }
2596
Dianne Hackborna4972e92012-03-14 10:38:05 -07002597 if (err == ActivityManager.START_SUCCESS && aInfo == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002598 // We couldn't find the specific class specified in the Intent.
2599 // Also the end of the line.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002600 err = ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002601 }
2602
Dianne Hackborna4972e92012-03-14 10:38:05 -07002603 if (err != ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002604 if (resultRecord != null) {
2605 sendActivityResultLocked(-1,
2606 resultRecord, resultWho, requestCode,
2607 Activity.RESULT_CANCELED, null);
2608 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002609 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002610 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002611 return err;
2612 }
2613
Jeff Sharkey35be7562012-04-18 19:16:15 -07002614 final int startAnyPerm = mService.checkPermission(
2615 START_ANY_ACTIVITY, callingPid, callingUid);
2616 final int componentPerm = mService.checkComponentPermission(aInfo.permission, callingPid,
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002617 callingUid, aInfo.applicationInfo.uid, aInfo.exported);
Jeff Sharkey35be7562012-04-18 19:16:15 -07002618 if (startAnyPerm != PERMISSION_GRANTED && componentPerm != PERMISSION_GRANTED) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002619 if (resultRecord != null) {
2620 sendActivityResultLocked(-1,
2621 resultRecord, resultWho, requestCode,
2622 Activity.RESULT_CANCELED, null);
2623 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002624 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn6c2c5fc2011-01-18 17:02:33 -08002625 String msg;
2626 if (!aInfo.exported) {
2627 msg = "Permission Denial: starting " + intent.toString()
2628 + " from " + callerApp + " (pid=" + callingPid
2629 + ", uid=" + callingUid + ")"
2630 + " not exported from uid " + aInfo.applicationInfo.uid;
2631 } else {
2632 msg = "Permission Denial: starting " + intent.toString()
2633 + " from " + callerApp + " (pid=" + callingPid
2634 + ", uid=" + callingUid + ")"
2635 + " requires " + aInfo.permission;
2636 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002637 Slog.w(TAG, msg);
2638 throw new SecurityException(msg);
2639 }
2640
2641 if (mMainStack) {
2642 if (mService.mController != null) {
2643 boolean abort = false;
2644 try {
2645 // The Intent we give to the watcher has the extra data
2646 // stripped off, since it can contain private information.
2647 Intent watchIntent = intent.cloneFilter();
2648 abort = !mService.mController.activityStarting(watchIntent,
2649 aInfo.applicationInfo.packageName);
2650 } catch (RemoteException e) {
2651 mService.mController = null;
2652 }
2653
2654 if (abort) {
2655 if (resultRecord != null) {
2656 sendActivityResultLocked(-1,
2657 resultRecord, resultWho, requestCode,
2658 Activity.RESULT_CANCELED, null);
2659 }
2660 // We pretend to the caller that it was really started, but
2661 // they will just get a cancel result.
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002662 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002663 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002664 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002665 }
2666 }
2667 }
Amith Yamasani742a6712011-05-04 14:49:28 -07002668
Dianne Hackbornf265ea92013-01-31 15:00:51 -08002669 ActivityRecord r = new ActivityRecord(mService, this, callerApp, callingUid, callingPackage,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002670 intent, resolvedType, aInfo, mService.mConfiguration,
2671 resultRecord, resultWho, requestCode, componentSpecified);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002672 if (outActivity != null) {
2673 outActivity[0] = r;
2674 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002675
2676 if (mMainStack) {
2677 if (mResumedActivity == null
2678 || mResumedActivity.info.applicationInfo.uid != callingUid) {
2679 if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, "Activity start")) {
2680 PendingActivityLaunch pal = new PendingActivityLaunch();
2681 pal.r = r;
2682 pal.sourceRecord = sourceRecord;
Dianne Hackborna4972e92012-03-14 10:38:05 -07002683 pal.startFlags = startFlags;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002684 mService.mPendingActivityLaunches.add(pal);
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002685 mDismissKeyguardOnNextActivity = false;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002686 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002687 return ActivityManager.START_SWITCHES_CANCELED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002688 }
2689 }
2690
2691 if (mService.mDidAppSwitch) {
2692 // This is the second allowed switch since we stopped switches,
2693 // so now just generally allow switches. Use case: user presses
2694 // home (switches disabled, switch to home, mDidAppSwitch now true);
2695 // user taps a home icon (coming from home so allowed, we hit here
2696 // and now allow anyone to switch again).
2697 mService.mAppSwitchesAllowedTime = 0;
2698 } else {
2699 mService.mDidAppSwitch = true;
2700 }
2701
2702 mService.doPendingActivityLaunchesLocked(false);
2703 }
2704
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002705 err = startActivityUncheckedLocked(r, sourceRecord,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002706 startFlags, true, options);
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08002707 if (mDismissKeyguardOnNextActivity && mPausingActivity == null) {
Dianne Hackborn90c52de2011-09-23 12:57:44 -07002708 // Someone asked to have the keyguard dismissed on the next
2709 // activity start, but we are not actually doing an activity
2710 // switch... just dismiss the keyguard now, because we
2711 // probably want to see whatever is behind it.
2712 mDismissKeyguardOnNextActivity = false;
2713 mService.mWindowManager.dismissKeyguard();
2714 }
2715 return err;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002716 }
2717
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002718 final void moveHomeToFrontFromLaunchLocked(int launchFlags) {
2719 if ((launchFlags &
2720 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME))
2721 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_TASK_ON_HOME)) {
2722 // Caller wants to appear on home activity, so before starting
2723 // their own activity we will bring home to the front.
2724 moveHomeToFrontLocked();
2725 }
2726 }
2727
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002728 final int startActivityUncheckedLocked(ActivityRecord r,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07002729 ActivityRecord sourceRecord, int startFlags, boolean doResume,
2730 Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002731 final Intent intent = r.intent;
2732 final int callingUid = r.launchedFromUid;
Amith Yamasani742a6712011-05-04 14:49:28 -07002733
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002734 int launchFlags = intent.getFlags();
2735
2736 // We'll invoke onUserLeaving before onPause only if the launching
2737 // activity did not explicitly state that this is an automated launch.
2738 mUserLeaving = (launchFlags&Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0;
2739 if (DEBUG_USER_LEAVING) Slog.v(TAG,
2740 "startActivity() => mUserLeaving=" + mUserLeaving);
2741
2742 // If the caller has asked not to resume at this point, we make note
2743 // of this in the record so that we can skip it when trying to find
2744 // the top running activity.
2745 if (!doResume) {
2746 r.delayedResume = true;
2747 }
2748
2749 ActivityRecord notTop = (launchFlags&Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP)
2750 != 0 ? r : null;
2751
2752 // If the onlyIfNeeded flag is set, then we can do this if the activity
2753 // being launched is the same as the one making the call... or, as
2754 // a special case, if we do not know the caller then we count the
2755 // current top activity as the caller.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002756 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002757 ActivityRecord checkedCaller = sourceRecord;
2758 if (checkedCaller == null) {
2759 checkedCaller = topRunningNonDelayedActivityLocked(notTop);
2760 }
2761 if (!checkedCaller.realActivity.equals(r.realActivity)) {
2762 // Caller is not the same as launcher, so always needed.
Dianne Hackborna4972e92012-03-14 10:38:05 -07002763 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002764 }
2765 }
2766
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002767 if (sourceRecord == null) {
2768 // This activity is not being started from another... in this
2769 // case we -always- start a new task.
2770 if ((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) == 0) {
2771 Slog.w(TAG, "startActivity called from non-Activity context; forcing Intent.FLAG_ACTIVITY_NEW_TASK for: "
2772 + intent);
2773 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2774 }
2775 } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2776 // The original activity who is starting us is running as a single
2777 // instance... this new activity it is starting must go on its
2778 // own task.
2779 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2780 } else if (r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE
2781 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2782 // The activity being started is a single instance... it always
2783 // gets launched into its own task.
2784 launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK;
2785 }
2786
2787 if (r.resultTo != null && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
2788 // For whatever reason this activity is being launched into a new
2789 // task... yet the caller has requested a result back. Well, that
2790 // is pretty messed up, so instead immediately send back a cancel
2791 // and let the new task continue launched as normal without a
2792 // dependency on its originator.
2793 Slog.w(TAG, "Activity is launching as a new task, so cancelling activity result.");
2794 sendActivityResultLocked(-1,
2795 r.resultTo, r.resultWho, r.requestCode,
2796 Activity.RESULT_CANCELED, null);
2797 r.resultTo = null;
2798 }
2799
2800 boolean addingToTask = false;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002801 boolean movedHome = false;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002802 TaskRecord reuseTask = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002803 if (((launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0 &&
2804 (launchFlags&Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
2805 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2806 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2807 // If bring to front is requested, and no result is requested, and
2808 // we can find a task that was started with this same
2809 // component, then instead of launching bring that one to the front.
2810 if (r.resultTo == null) {
2811 // See if there is a task to bring to the front. If this is
2812 // a SINGLE_INSTANCE activity, there can be one and only one
2813 // instance of it in the history, and it is always in its own
2814 // unique task, so we do a special search.
2815 ActivityRecord taskTop = r.launchMode != ActivityInfo.LAUNCH_SINGLE_INSTANCE
2816 ? findTaskLocked(intent, r.info)
2817 : findActivityLocked(intent, r.info);
2818 if (taskTop != null) {
2819 if (taskTop.task.intent == null) {
2820 // This task was started because of movement of
2821 // the activity based on affinity... now that we
2822 // are actually launching it, we can assign the
2823 // base intent.
2824 taskTop.task.setIntent(intent, r.info);
2825 }
2826 // If the target task is not in the front, then we need
2827 // to bring it to the front... except... well, with
2828 // SINGLE_TASK_LAUNCH it's not entirely clear. We'd like
2829 // to have the same behavior as if a new instance was
2830 // being started, which means not bringing it to the front
2831 // if the caller is not itself in the front.
2832 ActivityRecord curTop = topRunningNonDelayedActivityLocked(notTop);
Jean-Baptiste Queru66a5d692010-10-25 17:27:16 -07002833 if (curTop != null && curTop.task != taskTop.task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002834 r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
2835 boolean callerAtFront = sourceRecord == null
2836 || curTop.task == sourceRecord.task;
2837 if (callerAtFront) {
2838 // We really do want to push this one into the
2839 // user's face, right now.
Dianne Hackborn03fcc332012-05-15 12:49:40 -07002840 movedHome = true;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002841 moveHomeToFrontFromLaunchLocked(launchFlags);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002842 moveTaskToFrontLocked(taskTop.task, r, options);
Dianne Hackborn84375872012-06-01 19:03:50 -07002843 options = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002844 }
2845 }
2846 // If the caller has requested that the target task be
2847 // reset, then do so.
2848 if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
2849 taskTop = resetTaskIfNeededLocked(taskTop, r);
2850 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002851 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002852 // We don't need to start a new activity, and
2853 // the client said not to do anything if that
2854 // is the case, so this is it! And for paranoia, make
2855 // sure we have correctly resumed the top activity.
2856 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002857 resumeTopActivityLocked(null, options);
2858 } else {
2859 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002860 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002861 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002862 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002863 if ((launchFlags &
2864 (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK))
2865 == (Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
2866 // The caller has requested to completely replace any
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08002867 // existing task with its new activity. Well that should
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002868 // not be too hard...
2869 reuseTask = taskTop.task;
2870 performClearTaskLocked(taskTop.task.taskId);
2871 reuseTask.setIntent(r.intent, r.info);
2872 } else if ((launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002873 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK
2874 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) {
2875 // In this situation we want to remove all activities
2876 // from the task up to the one being started. In most
2877 // cases this means we are resetting the task to its
2878 // initial state.
2879 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002880 taskTop.task.taskId, r, launchFlags);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002881 if (top != null) {
2882 if (top.frontOfTask) {
2883 // Activity aliases may mean we use different
2884 // intents for the top activity, so make sure
2885 // the task now has the identity of the new
2886 // intent.
2887 top.task.setIntent(r.intent, r.info);
2888 }
2889 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07002890 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002891 } else {
2892 // A special case: we need to
2893 // start the activity because it is not currently
2894 // running, and the caller has asked to clear the
2895 // current task to have this activity at the top.
2896 addingToTask = true;
2897 // Now pretend like this activity is being started
2898 // by the top of its task, so it is put in the
2899 // right place.
2900 sourceRecord = taskTop;
2901 }
2902 } else if (r.realActivity.equals(taskTop.task.realActivity)) {
2903 // In this case the top activity on the task is the
2904 // same as the one being launched, so we take that
2905 // as a request to bring the task to the foreground.
2906 // If the top activity in the task is the root
2907 // activity, deliver this new intent to it if it
2908 // desires.
Johan Viktorssonf363dfd2012-02-16 17:05:16 +01002909 if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2910 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP)
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002911 && taskTop.realActivity.equals(r.realActivity)) {
2912 logStartActivity(EventLogTags.AM_NEW_INTENT, r, taskTop.task);
2913 if (taskTop.frontOfTask) {
2914 taskTop.task.setIntent(r.intent, r.info);
2915 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002916 taskTop.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002917 } else if (!r.intent.filterEquals(taskTop.task.intent)) {
2918 // In this case we are launching the root activity
2919 // of the task, but with a different intent. We
2920 // should start a new instance on top.
2921 addingToTask = true;
2922 sourceRecord = taskTop;
2923 }
2924 } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) {
2925 // In this case an activity is being launched in to an
2926 // existing task, without resetting that task. This
2927 // is typically the situation of launching an activity
2928 // from a notification or shortcut. We want to place
2929 // the new activity on top of the current task.
2930 addingToTask = true;
2931 sourceRecord = taskTop;
2932 } else if (!taskTop.task.rootWasReset) {
2933 // In this case we are launching in to an existing task
2934 // that has not yet been started from its front door.
2935 // The current task has been brought to the front.
2936 // Ideally, we'd probably like to place this new task
2937 // at the bottom of its stack, but that's a little hard
2938 // to do with the current organization of the code so
2939 // for now we'll just drop it.
2940 taskTop.task.setIntent(r.intent, r.info);
2941 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08002942 if (!addingToTask && reuseTask == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002943 // We didn't do anything... but it was needed (a.k.a., client
2944 // don't use that intent!) And for paranoia, make
2945 // sure we have correctly resumed the top activity.
2946 if (doResume) {
Dianne Hackborn84375872012-06-01 19:03:50 -07002947 resumeTopActivityLocked(null, options);
2948 } else {
2949 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002950 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07002951 return ActivityManager.START_TASK_TO_FRONT;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002952 }
2953 }
2954 }
2955 }
2956
2957 //String uri = r.intent.toURI();
2958 //Intent intent2 = new Intent(uri);
2959 //Slog.i(TAG, "Given intent: " + r.intent);
2960 //Slog.i(TAG, "URI is: " + uri);
2961 //Slog.i(TAG, "To intent: " + intent2);
2962
2963 if (r.packageName != null) {
2964 // If the activity being launched is the same as the one currently
2965 // at the top, then we need to check if it should only be launched
2966 // once.
2967 ActivityRecord top = topRunningNonDelayedActivityLocked(notTop);
2968 if (top != null && r.resultTo == null) {
Amith Yamasani742a6712011-05-04 14:49:28 -07002969 if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002970 if (top.app != null && top.app.thread != null) {
2971 if ((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0
2972 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP
2973 || r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK) {
2974 logStartActivity(EventLogTags.AM_NEW_INTENT, top, top.task);
2975 // For paranoia, make sure we have correctly
2976 // resumed the top activity.
2977 if (doResume) {
2978 resumeTopActivityLocked(null);
2979 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07002980 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002981 if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002982 // We don't need to start a new activity, and
2983 // the client said not to do anything if that
2984 // is the case, so this is it!
Dianne Hackborna4972e92012-03-14 10:38:05 -07002985 return ActivityManager.START_RETURN_INTENT_TO_CALLER;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002986 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07002987 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborna4972e92012-03-14 10:38:05 -07002988 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07002989 }
2990 }
2991 }
2992 }
2993
2994 } else {
2995 if (r.resultTo != null) {
2996 sendActivityResultLocked(-1,
2997 r.resultTo, r.resultWho, r.requestCode,
2998 Activity.RESULT_CANCELED, null);
2999 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003000 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003001 return ActivityManager.START_CLASS_NOT_FOUND;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003002 }
3003
3004 boolean newTask = false;
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003005 boolean keepCurTransition = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003006
3007 // Should this be considered a new task?
3008 if (r.resultTo == null && !addingToTask
3009 && (launchFlags&Intent.FLAG_ACTIVITY_NEW_TASK) != 0) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003010 if (reuseTask == null) {
3011 // todo: should do better management of integers.
3012 mService.mCurTask++;
3013 if (mService.mCurTask <= 0) {
3014 mService.mCurTask = 1;
3015 }
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003016 r.setTask(new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003017 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3018 + " in new task " + r.task);
3019 } else {
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003020 r.setTask(reuseTask, reuseTask, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003021 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003022 newTask = true;
Dianne Hackborn03fcc332012-05-15 12:49:40 -07003023 if (!movedHome) {
3024 moveHomeToFrontFromLaunchLocked(launchFlags);
3025 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003026
3027 } else if (sourceRecord != null) {
3028 if (!addingToTask &&
3029 (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
3030 // In this case, we are adding the activity to an existing
3031 // task, but the caller has asked to clear that task if the
3032 // activity is already running.
3033 ActivityRecord top = performClearTaskLocked(
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003034 sourceRecord.task.taskId, r, launchFlags);
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08003035 keepCurTransition = true;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003036 if (top != null) {
3037 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003038 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003039 // For paranoia, make sure we have correctly
3040 // resumed the top activity.
3041 if (doResume) {
3042 resumeTopActivityLocked(null);
3043 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003044 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003045 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003046 }
3047 } else if (!addingToTask &&
3048 (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
3049 // In this case, we are launching an activity in our own task
3050 // that may already be running somewhere in the history, and
3051 // we want to shuffle it to the front of the stack if so.
3052 int where = findActivityInHistoryLocked(r, sourceRecord.task.taskId);
3053 if (where >= 0) {
3054 ActivityRecord top = moveActivityToFrontLocked(where);
3055 logStartActivity(EventLogTags.AM_NEW_INTENT, r, top.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003056 top.updateOptionsLocked(options);
Dianne Hackborn39792d22010-08-19 18:01:52 -07003057 top.deliverNewIntentLocked(callingUid, r.intent);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003058 if (doResume) {
3059 resumeTopActivityLocked(null);
3060 }
Dianne Hackborna4972e92012-03-14 10:38:05 -07003061 return ActivityManager.START_DELIVERED_TO_TOP;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003062 }
3063 }
3064 // An existing activity is starting this new activity, so we want
3065 // to keep the new one in the same task as the one that is starting
3066 // it.
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003067 r.setTask(sourceRecord.task, sourceRecord.thumbHolder, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003068 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3069 + " in existing task " + r.task);
3070
3071 } else {
3072 // This not being started from an existing activity, and not part
3073 // of a new task... just put it in the top task, though these days
3074 // this case should never happen.
3075 final int N = mHistory.size();
3076 ActivityRecord prev =
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003077 N > 0 ? mHistory.get(N-1) : null;
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003078 r.setTask(prev != null
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003079 ? prev.task
Dianne Hackbornf26fd992011-04-08 18:14:09 -07003080 : new TaskRecord(mService.mCurTask, r.info, intent), null, true);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003081 if (DEBUG_TASKS) Slog.v(TAG, "Starting new activity " + r
3082 + " in new guessed " + r.task);
3083 }
Dianne Hackborn39792d22010-08-19 18:01:52 -07003084
Dianne Hackborn39792d22010-08-19 18:01:52 -07003085 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003086 intent, r.getUriPermissionsLocked());
Dianne Hackborn39792d22010-08-19 18:01:52 -07003087
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003088 if (newTask) {
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003089 EventLog.writeEvent(EventLogTags.AM_CREATE_TASK, r.userId, r.task.taskId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003090 }
3091 logStartActivity(EventLogTags.AM_CREATE_ACTIVITY, r, r.task);
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003092 startActivityLocked(r, newTask, doResume, keepCurTransition, options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003093 return ActivityManager.START_SUCCESS;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003094 }
3095
Dianne Hackborna4972e92012-03-14 10:38:05 -07003096 ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003097 String profileFile, ParcelFileDescriptor profileFd, int userId) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003098 // Collect information about the target of the Intent.
3099 ActivityInfo aInfo;
3100 try {
3101 ResolveInfo rInfo =
3102 AppGlobals.getPackageManager().resolveIntent(
3103 intent, resolvedType,
3104 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003105 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003106 aInfo = rInfo != null ? rInfo.activityInfo : null;
3107 } catch (RemoteException e) {
3108 aInfo = null;
3109 }
3110
3111 if (aInfo != null) {
3112 // Store the found target back into the intent, because now that
3113 // we have it we never want to do this again. For example, if the
3114 // user navigates back to this point in the history, we should
3115 // always restart the exact same activity.
3116 intent.setComponent(new ComponentName(
3117 aInfo.applicationInfo.packageName, aInfo.name));
3118
3119 // Don't debug things in the system process
Dianne Hackborna4972e92012-03-14 10:38:05 -07003120 if ((startFlags&ActivityManager.START_FLAG_DEBUG) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003121 if (!aInfo.processName.equals("system")) {
3122 mService.setDebugApp(aInfo.processName, true, false);
3123 }
3124 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003125
Dianne Hackborna4972e92012-03-14 10:38:05 -07003126 if ((startFlags&ActivityManager.START_FLAG_OPENGL_TRACES) != 0) {
Siva Velusamy92a8b222012-03-09 16:24:04 -08003127 if (!aInfo.processName.equals("system")) {
3128 mService.setOpenGlTraceApp(aInfo.applicationInfo, aInfo.processName);
3129 }
3130 }
3131
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003132 if (profileFile != null) {
3133 if (!aInfo.processName.equals("system")) {
3134 mService.setProfileApp(aInfo.applicationInfo, aInfo.processName,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003135 profileFile, profileFd,
3136 (startFlags&ActivityManager.START_FLAG_AUTO_STOP_PROFILER) != 0);
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003137 }
3138 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003139 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003140 return aInfo;
3141 }
3142
3143 final int startActivityMayWait(IApplicationThread caller, int callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003144 String callingPackage, Intent intent, String resolvedType, IBinder resultTo,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003145 String resultWho, int requestCode, int startFlags, String profileFile,
3146 ParcelFileDescriptor profileFd, WaitResult outResult, Configuration config,
3147 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003148 // Refuse possible leaked file descriptors
3149 if (intent != null && intent.hasFileDescriptors()) {
3150 throw new IllegalArgumentException("File descriptors passed in Intent");
3151 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003152 boolean componentSpecified = intent.getComponent() != null;
3153
3154 // Don't modify the client's object!
3155 intent = new Intent(intent);
3156
3157 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003158 ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags,
Amith Yamasani483f3b02012-03-13 16:08:00 -07003159 profileFile, profileFd, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003160
3161 synchronized (mService) {
3162 int callingPid;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003163 if (callingUid >= 0) {
3164 callingPid = -1;
3165 } else if (caller == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003166 callingPid = Binder.getCallingPid();
3167 callingUid = Binder.getCallingUid();
3168 } else {
3169 callingPid = callingUid = -1;
3170 }
3171
3172 mConfigWillChange = config != null
3173 && mService.mConfiguration.diff(config) != 0;
3174 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3175 "Starting activity when config will change = " + mConfigWillChange);
3176
3177 final long origId = Binder.clearCallingIdentity();
3178
3179 if (mMainStack && aInfo != null &&
Dianne Hackborn54e570f2010-10-04 18:32:32 -07003180 (aInfo.applicationInfo.flags&ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003181 // This may be a heavy-weight process! Check to see if we already
3182 // have another, different heavy-weight process running.
3183 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) {
3184 if (mService.mHeavyWeightProcess != null &&
3185 (mService.mHeavyWeightProcess.info.uid != aInfo.applicationInfo.uid ||
3186 !mService.mHeavyWeightProcess.processName.equals(aInfo.processName))) {
3187 int realCallingPid = callingPid;
3188 int realCallingUid = callingUid;
3189 if (caller != null) {
3190 ProcessRecord callerApp = mService.getRecordForAppLocked(caller);
3191 if (callerApp != null) {
3192 realCallingPid = callerApp.pid;
3193 realCallingUid = callerApp.info.uid;
3194 } else {
3195 Slog.w(TAG, "Unable to find app for caller " + caller
3196 + " (pid=" + realCallingPid + ") when starting: "
3197 + intent.toString());
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003198 ActivityOptions.abort(options);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003199 return ActivityManager.START_PERMISSION_DENIED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003200 }
3201 }
3202
3203 IIntentSender target = mService.getIntentSenderLocked(
Dianne Hackborna4972e92012-03-14 10:38:05 -07003204 ActivityManager.INTENT_SENDER_ACTIVITY, "android",
Dianne Hackborn41203752012-08-31 14:05:51 -07003205 realCallingUid, userId, null, null, 0, new Intent[] { intent },
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003206 new String[] { resolvedType }, PendingIntent.FLAG_CANCEL_CURRENT
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003207 | PendingIntent.FLAG_ONE_SHOT, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003208
3209 Intent newIntent = new Intent();
3210 if (requestCode >= 0) {
3211 // Caller is requesting a result.
3212 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
3213 }
3214 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT,
3215 new IntentSender(target));
3216 if (mService.mHeavyWeightProcess.activities.size() > 0) {
3217 ActivityRecord hist = mService.mHeavyWeightProcess.activities.get(0);
3218 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_APP,
3219 hist.packageName);
3220 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_CUR_TASK,
3221 hist.task.taskId);
3222 }
3223 newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
3224 aInfo.packageName);
3225 newIntent.setFlags(intent.getFlags());
3226 newIntent.setClassName("android",
3227 HeavyWeightSwitcherActivity.class.getName());
3228 intent = newIntent;
3229 resolvedType = null;
3230 caller = null;
3231 callingUid = Binder.getCallingUid();
3232 callingPid = Binder.getCallingPid();
3233 componentSpecified = true;
3234 try {
3235 ResolveInfo rInfo =
3236 AppGlobals.getPackageManager().resolveIntent(
3237 intent, null,
3238 PackageManager.MATCH_DEFAULT_ONLY
Amith Yamasani483f3b02012-03-13 16:08:00 -07003239 | ActivityManagerService.STOCK_PM_FLAGS, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003240 aInfo = rInfo != null ? rInfo.activityInfo : null;
Amith Yamasani742a6712011-05-04 14:49:28 -07003241 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003242 } catch (RemoteException e) {
3243 aInfo = null;
3244 }
3245 }
3246 }
3247 }
3248
3249 int res = startActivityLocked(caller, intent, resolvedType,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003250 aInfo, resultTo, resultWho, requestCode, callingPid, callingUid,
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003251 callingPackage, startFlags, options, componentSpecified, null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003252
3253 if (mConfigWillChange && mMainStack) {
3254 // If the caller also wants to switch to a new configuration,
3255 // do so now. This allows a clean switch, as we are waiting
3256 // for the current activity to pause (so we will not destroy
3257 // it), and have not yet started the next activity.
3258 mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
3259 "updateConfiguration()");
3260 mConfigWillChange = false;
3261 if (DEBUG_CONFIGURATION) Slog.v(TAG,
3262 "Updating to new configuration after starting activity.");
Dianne Hackborn813075a62011-11-14 17:45:19 -08003263 mService.updateConfigurationLocked(config, null, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003264 }
3265
3266 Binder.restoreCallingIdentity(origId);
3267
3268 if (outResult != null) {
3269 outResult.result = res;
Dianne Hackborna4972e92012-03-14 10:38:05 -07003270 if (res == ActivityManager.START_SUCCESS) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003271 mWaitingActivityLaunched.add(outResult);
3272 do {
3273 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003274 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003275 } catch (InterruptedException e) {
3276 }
3277 } while (!outResult.timeout && outResult.who == null);
Dianne Hackborna4972e92012-03-14 10:38:05 -07003278 } else if (res == ActivityManager.START_TASK_TO_FRONT) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003279 ActivityRecord r = this.topRunningActivityLocked(null);
3280 if (r.nowVisible) {
3281 outResult.timeout = false;
3282 outResult.who = new ComponentName(r.info.packageName, r.info.name);
3283 outResult.totalTime = 0;
3284 outResult.thisTime = 0;
3285 } else {
3286 outResult.thisTime = SystemClock.uptimeMillis();
3287 mWaitingActivityVisible.add(outResult);
3288 do {
3289 try {
Dianne Hackbornba0492d2010-10-12 19:01:46 -07003290 mService.wait();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003291 } catch (InterruptedException e) {
3292 }
3293 } while (!outResult.timeout && outResult.who == null);
3294 }
3295 }
3296 }
3297
3298 return res;
3299 }
3300 }
3301
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003302 final int startActivities(IApplicationThread caller, int callingUid, String callingPackage,
Dianne Hackborna4972e92012-03-14 10:38:05 -07003303 Intent[] intents, String[] resolvedTypes, IBinder resultTo,
3304 Bundle options, int userId) {
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003305 if (intents == null) {
3306 throw new NullPointerException("intents is null");
3307 }
3308 if (resolvedTypes == null) {
3309 throw new NullPointerException("resolvedTypes is null");
3310 }
3311 if (intents.length != resolvedTypes.length) {
3312 throw new IllegalArgumentException("intents are length different than resolvedTypes");
3313 }
3314
3315 ActivityRecord[] outActivity = new ActivityRecord[1];
3316
3317 int callingPid;
3318 if (callingUid >= 0) {
3319 callingPid = -1;
3320 } else if (caller == null) {
3321 callingPid = Binder.getCallingPid();
3322 callingUid = Binder.getCallingUid();
3323 } else {
3324 callingPid = callingUid = -1;
3325 }
3326 final long origId = Binder.clearCallingIdentity();
3327 try {
3328 synchronized (mService) {
3329
3330 for (int i=0; i<intents.length; i++) {
3331 Intent intent = intents[i];
3332 if (intent == null) {
3333 continue;
3334 }
3335
3336 // Refuse possible leaked file descriptors
3337 if (intent != null && intent.hasFileDescriptors()) {
3338 throw new IllegalArgumentException("File descriptors passed in Intent");
3339 }
3340
3341 boolean componentSpecified = intent.getComponent() != null;
3342
3343 // Don't modify the client's object!
3344 intent = new Intent(intent);
3345
3346 // Collect information about the target of the Intent.
Dianne Hackborna4972e92012-03-14 10:38:05 -07003347 ActivityInfo aInfo = resolveActivity(intent, resolvedTypes[i],
Amith Yamasani483f3b02012-03-13 16:08:00 -07003348 0, null, null, userId);
Amith Yamasani742a6712011-05-04 14:49:28 -07003349 // TODO: New, check if this is correct
3350 aInfo = mService.getActivityInfoForUser(aInfo, userId);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003351
3352 if (mMainStack && aInfo != null && (aInfo.applicationInfo.flags
3353 & ApplicationInfo.FLAG_CANT_SAVE_STATE) != 0) {
3354 throw new IllegalArgumentException(
3355 "FLAG_CANT_SAVE_STATE not supported here");
3356 }
3357
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003358 Bundle theseOptions;
3359 if (options != null && i == intents.length-1) {
3360 theseOptions = options;
3361 } else {
3362 theseOptions = null;
3363 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003364 int res = startActivityLocked(caller, intent, resolvedTypes[i],
Dianne Hackbornf265ea92013-01-31 15:00:51 -08003365 aInfo, resultTo, null, -1, callingPid, callingUid, callingPackage,
Dianne Hackborn7a2195c2012-03-19 17:38:00 -07003366 0, theseOptions, componentSpecified, outActivity);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003367 if (res < 0) {
3368 return res;
3369 }
3370
Dianne Hackbornbe707852011-11-11 14:32:10 -08003371 resultTo = outActivity[0] != null ? outActivity[0].appToken : null;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003372 }
3373 }
3374 } finally {
3375 Binder.restoreCallingIdentity(origId);
3376 }
3377
Dianne Hackborna4972e92012-03-14 10:38:05 -07003378 return ActivityManager.START_SUCCESS;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08003379 }
3380
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003381 void reportActivityLaunchedLocked(boolean timeout, ActivityRecord r,
3382 long thisTime, long totalTime) {
3383 for (int i=mWaitingActivityLaunched.size()-1; i>=0; i--) {
3384 WaitResult w = mWaitingActivityLaunched.get(i);
3385 w.timeout = timeout;
3386 if (r != null) {
3387 w.who = new ComponentName(r.info.packageName, r.info.name);
3388 }
3389 w.thisTime = thisTime;
3390 w.totalTime = totalTime;
3391 }
3392 mService.notifyAll();
3393 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003394
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003395 void reportActivityVisibleLocked(ActivityRecord r) {
3396 for (int i=mWaitingActivityVisible.size()-1; i>=0; i--) {
3397 WaitResult w = mWaitingActivityVisible.get(i);
3398 w.timeout = false;
3399 if (r != null) {
3400 w.who = new ComponentName(r.info.packageName, r.info.name);
3401 }
3402 w.totalTime = SystemClock.uptimeMillis() - w.thisTime;
3403 w.thisTime = w.totalTime;
3404 }
3405 mService.notifyAll();
Dianne Hackborn90c52de2011-09-23 12:57:44 -07003406
3407 if (mDismissKeyguardOnNextActivity) {
3408 mDismissKeyguardOnNextActivity = false;
3409 mService.mWindowManager.dismissKeyguard();
3410 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003411 }
3412
3413 void sendActivityResultLocked(int callingUid, ActivityRecord r,
3414 String resultWho, int requestCode, int resultCode, Intent data) {
3415
3416 if (callingUid > 0) {
3417 mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName,
Dianne Hackborn7e269642010-08-25 19:50:20 -07003418 data, r.getUriPermissionsLocked());
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003419 }
3420
3421 if (DEBUG_RESULTS) Slog.v(TAG, "Send activity result to " + r
3422 + " : who=" + resultWho + " req=" + requestCode
3423 + " res=" + resultCode + " data=" + data);
3424 if (mResumedActivity == r && r.app != null && r.app.thread != null) {
3425 try {
3426 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3427 list.add(new ResultInfo(resultWho, requestCode,
3428 resultCode, data));
Dianne Hackbornbe707852011-11-11 14:32:10 -08003429 r.app.thread.scheduleSendResult(r.appToken, list);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003430 return;
3431 } catch (Exception e) {
3432 Slog.w(TAG, "Exception thrown sending result to " + r, e);
3433 }
3434 }
3435
3436 r.addResultLocked(null, resultWho, requestCode, resultCode, data);
3437 }
3438
3439 private final void stopActivityLocked(ActivityRecord r) {
3440 if (DEBUG_SWITCH) Slog.d(TAG, "Stopping: " + r);
3441 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
3442 || (r.info.flags&ActivityInfo.FLAG_NO_HISTORY) != 0) {
3443 if (!r.finishing) {
Christopher Tated3f175c2012-06-14 14:16:54 -07003444 if (!mService.mSleeping) {
3445 if (DEBUG_STATES) {
3446 Slog.d(TAG, "no-history finish of " + r);
3447 }
3448 requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003449 "no-history", false);
Christopher Tated3f175c2012-06-14 14:16:54 -07003450 } else {
3451 if (DEBUG_STATES) Slog.d(TAG, "Not finishing noHistory " + r
3452 + " on stop because we're just sleeping");
3453 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003454 }
Christopher Tate5007ddd2012-06-12 13:08:18 -07003455 }
3456
3457 if (r.app != null && r.app.thread != null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003458 if (mMainStack) {
3459 if (mService.mFocusedActivity == r) {
3460 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3461 }
3462 }
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003463 r.resumeKeyDispatchingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003464 try {
3465 r.stopped = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003466 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3467 + " (stop requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003468 r.state = ActivityState.STOPPING;
3469 if (DEBUG_VISBILITY) Slog.v(
3470 TAG, "Stopping visible=" + r.visible + " for " + r);
3471 if (!r.visible) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003472 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003473 }
Dianne Hackbornbe707852011-11-11 14:32:10 -08003474 r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003475 if (mService.isSleeping()) {
3476 r.setSleeping(true);
3477 }
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07003478 Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG);
3479 msg.obj = r;
3480 mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003481 } catch (Exception e) {
3482 // Maybe just ignore exceptions here... if the process
3483 // has crashed, our death notification will clean things
3484 // up.
3485 Slog.w(TAG, "Exception thrown during pause", e);
3486 // Just in case, assume it to be stopped.
3487 r.stopped = true;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003488 if (DEBUG_STATES) Slog.v(TAG, "Stop failed; moving to STOPPED: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003489 r.state = ActivityState.STOPPED;
3490 if (r.configDestroy) {
Dianne Hackborn28695e02011-11-02 21:59:51 -07003491 destroyActivityLocked(r, true, false, "stop-except");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003492 }
3493 }
3494 }
3495 }
3496
3497 final ArrayList<ActivityRecord> processStoppingActivitiesLocked(
3498 boolean remove) {
3499 int N = mStoppingActivities.size();
3500 if (N <= 0) return null;
3501
3502 ArrayList<ActivityRecord> stops = null;
3503
3504 final boolean nowVisible = mResumedActivity != null
3505 && mResumedActivity.nowVisible
3506 && !mResumedActivity.waitingVisible;
3507 for (int i=0; i<N; i++) {
3508 ActivityRecord s = mStoppingActivities.get(i);
3509 if (localLOGV) Slog.v(TAG, "Stopping " + s + ": nowVisible="
3510 + nowVisible + " waitingVisible=" + s.waitingVisible
3511 + " finishing=" + s.finishing);
3512 if (s.waitingVisible && nowVisible) {
3513 mWaitingVisibleActivities.remove(s);
3514 s.waitingVisible = false;
3515 if (s.finishing) {
3516 // If this activity is finishing, it is sitting on top of
3517 // everyone else but we now know it is no longer needed...
3518 // so get rid of it. Otherwise, we need to go through the
3519 // normal flow and hide it once we determine that it is
3520 // hidden by the activities in front of it.
3521 if (localLOGV) Slog.v(TAG, "Before stopping, can hide: " + s);
Dianne Hackbornbe707852011-11-11 14:32:10 -08003522 mService.mWindowManager.setAppVisibility(s.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003523 }
3524 }
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003525 if ((!s.waitingVisible || mService.isSleeping()) && remove) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003526 if (localLOGV) Slog.v(TAG, "Ready to stop: " + s);
3527 if (stops == null) {
3528 stops = new ArrayList<ActivityRecord>();
3529 }
3530 stops.add(s);
3531 mStoppingActivities.remove(i);
3532 N--;
3533 i--;
3534 }
3535 }
3536
3537 return stops;
3538 }
3539
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003540 final void scheduleIdleLocked() {
3541 Message msg = Message.obtain();
3542 msg.what = IDLE_NOW_MSG;
3543 mHandler.sendMessage(msg);
3544 }
3545
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003546 final ActivityRecord activityIdleInternal(IBinder token, boolean fromTimeout,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003547 Configuration config) {
3548 if (localLOGV) Slog.v(TAG, "Activity idle: " + token);
3549
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003550 ActivityRecord res = null;
3551
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003552 ArrayList<ActivityRecord> stops = null;
3553 ArrayList<ActivityRecord> finishes = null;
3554 ArrayList<ActivityRecord> thumbnails = null;
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003555 ArrayList<UserStartedState> startingUsers = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003556 int NS = 0;
3557 int NF = 0;
3558 int NT = 0;
3559 IApplicationThread sendThumbnail = null;
3560 boolean booting = false;
3561 boolean enableScreen = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003562 boolean activityRemoved = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003563
3564 synchronized (mService) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08003565 ActivityRecord r = ActivityRecord.forToken(token);
3566 if (r != null) {
3567 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07003568 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003569 }
3570
3571 // Get the activity record.
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003572 int index = mHistory.indexOf(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003573 if (index >= 0) {
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003574 res = r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003575
3576 if (fromTimeout) {
3577 reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
3578 }
3579
3580 // This is a hack to semi-deal with a race condition
3581 // in the client where it can be constructed with a
3582 // newer configuration from when we asked it to launch.
3583 // We'll update with whatever configuration it now says
3584 // it used to launch.
3585 if (config != null) {
3586 r.configuration = config;
3587 }
3588
3589 // No longer need to keep the device awake.
3590 if (mResumedActivity == r && mLaunchingActivity.isHeld()) {
3591 mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
3592 mLaunchingActivity.release();
3593 }
3594
3595 // We are now idle. If someone is waiting for a thumbnail from
3596 // us, we can now deliver.
3597 r.idle = true;
3598 mService.scheduleAppGcsLocked();
3599 if (r.thumbnailNeeded && r.app != null && r.app.thread != null) {
3600 sendThumbnail = r.app.thread;
3601 r.thumbnailNeeded = false;
3602 }
3603
3604 // If this activity is fullscreen, set up to hide those under it.
3605
3606 if (DEBUG_VISBILITY) Slog.v(TAG, "Idle activity for " + r);
3607 ensureActivitiesVisibleLocked(null, 0);
3608
3609 //Slog.i(TAG, "IDLE: mBooted=" + mBooted + ", fromTimeout=" + fromTimeout);
3610 if (mMainStack) {
Dianne Hackborn29aae6f2011-08-18 18:30:09 -07003611 if (!mService.mBooted) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003612 mService.mBooted = true;
3613 enableScreen = true;
3614 }
3615 }
3616
3617 } else if (fromTimeout) {
3618 reportActivityLaunchedLocked(fromTimeout, null, -1, -1);
3619 }
3620
3621 // Atomically retrieve all of the other things to do.
3622 stops = processStoppingActivitiesLocked(true);
3623 NS = stops != null ? stops.size() : 0;
3624 if ((NF=mFinishingActivities.size()) > 0) {
3625 finishes = new ArrayList<ActivityRecord>(mFinishingActivities);
3626 mFinishingActivities.clear();
3627 }
Craig Mautnercae015f2013-02-08 14:31:27 -08003628 if ((NT=mCancelledThumbnails.size()) > 0) {
3629 thumbnails = new ArrayList<ActivityRecord>(mCancelledThumbnails);
3630 mCancelledThumbnails.clear();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003631 }
3632
3633 if (mMainStack) {
3634 booting = mService.mBooting;
3635 mService.mBooting = false;
3636 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003637 if (mStartingUsers.size() > 0) {
3638 startingUsers = new ArrayList<UserStartedState>(mStartingUsers);
3639 mStartingUsers.clear();
3640 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003641 }
3642
3643 int i;
3644
3645 // Send thumbnail if requested.
3646 if (sendThumbnail != null) {
3647 try {
3648 sendThumbnail.requestThumbnail(token);
3649 } catch (Exception e) {
3650 Slog.w(TAG, "Exception thrown when requesting thumbnail", e);
3651 mService.sendPendingThumbnail(null, token, null, null, true);
3652 }
3653 }
3654
3655 // Stop any activities that are scheduled to do so but have been
3656 // waiting for the next one to start.
3657 for (i=0; i<NS; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003658 ActivityRecord r = stops.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003659 synchronized (mService) {
3660 if (r.finishing) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003661 finishCurrentActivityLocked(r, FINISH_IMMEDIATELY, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003662 } else {
3663 stopActivityLocked(r);
3664 }
3665 }
3666 }
3667
3668 // Finish any activities that are scheduled to do so but have been
3669 // waiting for the next one to start.
3670 for (i=0; i<NF; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003671 ActivityRecord r = finishes.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003672 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003673 activityRemoved = destroyActivityLocked(r, true, false, "finish-idle");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003674 }
3675 }
3676
3677 // Report back to any thumbnail receivers.
3678 for (i=0; i<NT; i++) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003679 ActivityRecord r = thumbnails.get(i);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003680 mService.sendPendingThumbnail(r, null, null, null, true);
3681 }
3682
3683 if (booting) {
3684 mService.finishBooting();
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003685 } else if (startingUsers != null) {
3686 for (i=0; i<startingUsers.size(); i++) {
3687 mService.finishUserSwitch(startingUsers.get(i));
3688 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003689 }
3690
3691 mService.trimApplications();
3692 //dump();
3693 //mWindowManager.dump();
3694
3695 if (enableScreen) {
3696 mService.enableScreenAfterBoot();
3697 }
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003698
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003699 if (activityRemoved) {
3700 resumeTopActivityLocked(null);
3701 }
3702
Dianne Hackborn62f20ec2011-08-15 17:40:28 -07003703 return res;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003704 }
3705
3706 /**
3707 * @return Returns true if the activity is being finished, false if for
3708 * some reason it is being left as-is.
3709 */
3710 final boolean requestFinishActivityLocked(IBinder token, int resultCode,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003711 Intent resultData, String reason, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003712 int index = indexOfTokenLocked(token);
Christopher Tated3f175c2012-06-14 14:16:54 -07003713 if (DEBUG_RESULTS || DEBUG_STATES) Slog.v(
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07003714 TAG, "Finishing activity @" + index + ": token=" + token
Christopher Tated3f175c2012-06-14 14:16:54 -07003715 + ", result=" + resultCode + ", data=" + resultData
3716 + ", reason=" + reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003717 if (index < 0) {
3718 return false;
3719 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003720 ActivityRecord r = mHistory.get(index);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003721
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003722 finishActivityLocked(r, index, resultCode, resultData, reason, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003723 return true;
3724 }
3725
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003726 final void finishSubActivityLocked(IBinder token, String resultWho, int requestCode) {
3727 ActivityRecord self = isInStackLocked(token);
3728 if (self == null) {
3729 return;
3730 }
3731
3732 int i;
3733 for (i=mHistory.size()-1; i>=0; i--) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003734 ActivityRecord r = mHistory.get(i);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003735 if (r.resultTo == self && r.requestCode == requestCode) {
3736 if ((r.resultWho == null && resultWho == null) ||
3737 (r.resultWho != null && r.resultWho.equals(resultWho))) {
3738 finishActivityLocked(r, i,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003739 Activity.RESULT_CANCELED, null, "request-sub", false);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003740 }
3741 }
3742 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003743 mService.updateOomAdjLocked();
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003744 }
3745
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003746 final void finishTopRunningActivityLocked(ProcessRecord app) {
3747 ActivityRecord r = topRunningActivityLocked(null);
3748 if (r != null && r.app == app) {
3749 // If the top running activity is from this crashing
3750 // process, then terminate it to avoid getting in a loop.
3751 Slog.w(TAG, " Force finishing activity "
3752 + r.intent.getComponent().flattenToShortString());
3753 int index = mHistory.indexOf(r);
3754 r.stack.finishActivityLocked(r, index,
3755 Activity.RESULT_CANCELED, null, "crashed", false);
3756 // Also terminate any activities below it that aren't yet
3757 // stopped, to avoid a situation where one will get
3758 // re-start our crashing activity once it gets resumed again.
3759 index--;
3760 if (index >= 0) {
3761 r = mHistory.get(index);
3762 if (r.state == ActivityState.RESUMED
3763 || r.state == ActivityState.PAUSING
3764 || r.state == ActivityState.PAUSED) {
3765 if (!r.isHomeActivity || mService.mHomeProcess != r.app) {
3766 Slog.w(TAG, " Force finishing activity "
3767 + r.intent.getComponent().flattenToShortString());
3768 r.stack.finishActivityLocked(r, index,
3769 Activity.RESULT_CANCELED, null, "crashed", false);
3770 }
3771 }
3772 }
3773 }
3774 }
3775
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003776 final boolean finishActivityAffinityLocked(IBinder token) {
3777 int index = indexOfTokenLocked(token);
3778 if (DEBUG_RESULTS) Slog.v(
3779 TAG, "Finishing activity affinity @" + index + ": token=" + token);
3780 if (index < 0) {
3781 return false;
3782 }
3783 ActivityRecord r = mHistory.get(index);
3784
Amith Yamasanibfc1be12012-05-15 11:12:17 -07003785 while (index >= 0) {
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003786 ActivityRecord cur = mHistory.get(index);
3787 if (cur.task != r.task) {
3788 break;
3789 }
3790 if (cur.taskAffinity == null && r.taskAffinity != null) {
3791 break;
3792 }
3793 if (cur.taskAffinity != null && !cur.taskAffinity.equals(r.taskAffinity)) {
3794 break;
3795 }
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003796 finishActivityLocked(cur, index, Activity.RESULT_CANCELED, null,
3797 "request-affinity", true);
Dianne Hackbornecc5a9c2012-04-26 18:56:09 -07003798 index--;
3799 }
3800 return true;
3801 }
3802
Dianne Hackborn5c607432012-02-28 14:44:19 -08003803 final void finishActivityResultsLocked(ActivityRecord r, int resultCode, Intent resultData) {
3804 // send the result
3805 ActivityRecord resultTo = r.resultTo;
3806 if (resultTo != null) {
3807 if (DEBUG_RESULTS) Slog.v(TAG, "Adding result to " + resultTo
3808 + " who=" + r.resultWho + " req=" + r.requestCode
3809 + " res=" + resultCode + " data=" + resultData);
3810 if (r.info.applicationInfo.uid > 0) {
3811 mService.grantUriPermissionFromIntentLocked(r.info.applicationInfo.uid,
3812 resultTo.packageName, resultData,
3813 resultTo.getUriPermissionsLocked());
3814 }
3815 resultTo.addResultLocked(r, r.resultWho, r.requestCode, resultCode,
3816 resultData);
3817 r.resultTo = null;
3818 }
3819 else if (DEBUG_RESULTS) Slog.v(TAG, "No result destination from " + r);
3820
3821 // Make sure this HistoryRecord is not holding on to other resources,
3822 // because clients have remote IPC references to this object so we
3823 // can't assume that will go away and want to avoid circular IPC refs.
3824 r.results = null;
3825 r.pendingResults = null;
3826 r.newIntents = null;
3827 r.icicle = null;
3828 }
3829
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003830 /**
3831 * @return Returns true if this activity has been removed from the history
3832 * list, or false if it is still in the list and will be removed later.
3833 */
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003834 final boolean finishActivityLocked(ActivityRecord r,
3835 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3836 int index = mHistory.indexOf(r);
3837 if (index >= 0) {
3838 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
3839 }
3840 return false;
3841 }
3842
3843 /**
3844 * @return Returns true if this activity has been removed from the history
3845 * list, or false if it is still in the list and will be removed later.
3846 */
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003847 final boolean finishActivityLocked(ActivityRecord r, int index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003848 int resultCode, Intent resultData, String reason, boolean oomAdj) {
3849 return finishActivityLocked(r, index, resultCode, resultData, reason, false, oomAdj);
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003850 }
3851
3852 /**
3853 * @return Returns true if this activity has been removed from the history
3854 * list, or false if it is still in the list and will be removed later.
3855 */
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003856 final boolean finishActivityLocked(ActivityRecord r, int index, int resultCode,
3857 Intent resultData, String reason, boolean immediate, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003858 if (r.finishing) {
3859 Slog.w(TAG, "Duplicate finish request for " + r);
3860 return false;
3861 }
3862
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08003863 r.makeFinishing();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003864 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07003865 r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003866 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003867 if (index < (mHistory.size()-1)) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003868 ActivityRecord next = mHistory.get(index+1);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003869 if (next.task == r.task) {
3870 if (r.frontOfTask) {
3871 // The next activity is now the front of the task.
3872 next.frontOfTask = true;
3873 }
3874 if ((r.intent.getFlags()&Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) {
3875 // If the caller asked that this activity (and all above it)
3876 // be cleared when the task is reset, don't lose that information,
3877 // but propagate it up to the next activity.
3878 next.intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
3879 }
3880 }
3881 }
3882
3883 r.pauseKeyDispatchingLocked();
3884 if (mMainStack) {
3885 if (mService.mFocusedActivity == r) {
3886 mService.setFocusedActivityLocked(topRunningActivityLocked(null));
3887 }
3888 }
3889
Dianne Hackborn5c607432012-02-28 14:44:19 -08003890 finishActivityResultsLocked(r, resultCode, resultData);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003891
3892 if (mService.mPendingThumbnails.size() > 0) {
3893 // There are clients waiting to receive thumbnails so, in case
3894 // this is an activity that someone is waiting for, add it
3895 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08003896 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003897 }
3898
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003899 if (immediate) {
3900 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003901 FINISH_IMMEDIATELY, oomAdj) == null;
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07003902 } else if (mResumedActivity == r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003903 boolean endTask = index <= 0
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07003904 || (mHistory.get(index-1)).task != r.task;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003905 if (DEBUG_TRANSITION) Slog.v(TAG,
3906 "Prepare close transition: finishing " + r);
3907 mService.mWindowManager.prepareAppTransition(endTask
Craig Mautner4b71aa12012-12-27 17:20:01 -08003908 ? AppTransition.TRANSIT_TASK_CLOSE
3909 : AppTransition.TRANSIT_ACTIVITY_CLOSE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003910
3911 // Tell window manager to prepare for this one to be removed.
Dianne Hackbornbe707852011-11-11 14:32:10 -08003912 mService.mWindowManager.setAppVisibility(r.appToken, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003913
Dianne Hackborn621e2fe2012-02-16 17:07:33 -08003914 if (mPausingActivity == null) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003915 if (DEBUG_PAUSE) Slog.v(TAG, "Finish needs to pause: " + r);
3916 if (DEBUG_USER_LEAVING) Slog.v(TAG, "finish() => pause with userLeaving=false");
3917 startPausingLocked(false, false);
3918 }
3919
3920 } else if (r.state != ActivityState.PAUSING) {
3921 // If the activity is PAUSING, we will complete the finish once
3922 // it is done pausing; else we can just directly finish it here.
3923 if (DEBUG_PAUSE) Slog.v(TAG, "Finish not pausing: " + r);
3924 return finishCurrentActivityLocked(r, index,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003925 FINISH_AFTER_PAUSE, oomAdj) == null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003926 } else {
3927 if (DEBUG_PAUSE) Slog.v(TAG, "Finish waiting for pause of: " + r);
3928 }
3929
3930 return false;
3931 }
3932
3933 private static final int FINISH_IMMEDIATELY = 0;
3934 private static final int FINISH_AFTER_PAUSE = 1;
3935 private static final int FINISH_AFTER_VISIBLE = 2;
3936
3937 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003938 int mode, boolean oomAdj) {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003939 final int index = mHistory.indexOf(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003940 if (index < 0) {
3941 return null;
3942 }
3943
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003944 return finishCurrentActivityLocked(r, index, mode, oomAdj);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003945 }
3946
3947 private final ActivityRecord finishCurrentActivityLocked(ActivityRecord r,
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003948 int index, int mode, boolean oomAdj) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003949 // First things first: if this activity is currently visible,
3950 // and the resumed activity is not yet visible, then hold off on
3951 // finishing until the resumed one becomes visible.
3952 if (mode == FINISH_AFTER_VISIBLE && r.nowVisible) {
3953 if (!mStoppingActivities.contains(r)) {
3954 mStoppingActivities.add(r);
3955 if (mStoppingActivities.size() > 3) {
3956 // If we already have a few activities waiting to stop,
3957 // then give up on things going idle and start clearing
3958 // them out.
Dianne Hackborn80a7ac12011-09-22 18:32:52 -07003959 scheduleIdleLocked();
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003960 } else {
3961 checkReadyForSleepLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003962 }
3963 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003964 if (DEBUG_STATES) Slog.v(TAG, "Moving to STOPPING: " + r
3965 + " (finish requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003966 r.state = ActivityState.STOPPING;
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003967 if (oomAdj) {
3968 mService.updateOomAdjLocked();
3969 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003970 return r;
3971 }
3972
3973 // make sure the record is cleaned out of other places.
3974 mStoppingActivities.remove(r);
Dianne Hackborn4eba96b2011-01-21 13:34:36 -08003975 mGoingToSleepActivities.remove(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003976 mWaitingVisibleActivities.remove(r);
3977 if (mResumedActivity == r) {
3978 mResumedActivity = null;
3979 }
3980 final ActivityState prevState = r.state;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07003981 if (DEBUG_STATES) Slog.v(TAG, "Moving to FINISHING: " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003982 r.state = ActivityState.FINISHING;
3983
3984 if (mode == FINISH_IMMEDIATELY
3985 || prevState == ActivityState.STOPPED
3986 || prevState == ActivityState.INITIALIZING) {
3987 // If this activity is already stopped, we can just finish
3988 // it right now.
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07003989 boolean activityRemoved = destroyActivityLocked(r, true,
3990 oomAdj, "finish-imm");
Dianne Hackborn42e620c2012-06-24 13:20:51 -07003991 if (activityRemoved) {
3992 resumeTopActivityLocked(null);
3993 }
3994 return activityRemoved ? null : r;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07003995 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08003996
3997 // Need to go through the full pause cycle to get this
3998 // activity into the stopped state and then finish it.
3999 if (localLOGV) Slog.v(TAG, "Enqueueing pending finish: " + r);
4000 mFinishingActivities.add(r);
4001 resumeTopActivityLocked(null);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004002 return r;
4003 }
4004
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004005 final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode,
4006 Intent resultData) {
4007 final int start = mHistory.indexOf(srec);
4008 if (start < 0) {
4009 // Current activity is not in history stack; do nothing.
4010 return false;
4011 }
4012 int finishTo = start - 1;
4013 ActivityRecord parent = null;
4014 boolean foundParentInTask = false;
4015 ComponentName dest = destIntent.getComponent();
4016 if (dest != null) {
4017 TaskRecord tr = srec.task;
4018 for (int i = start - 1; i >= 0; i--) {
4019 ActivityRecord r = mHistory.get(i);
4020 if (tr != r.task) {
4021 // Couldn't find parent in the same task; stop at the one above this.
4022 // (Root of current task; in-app "home" behavior)
4023 // Always at least finish the current activity.
4024 finishTo = Math.min(start - 1, i + 1);
4025 parent = mHistory.get(finishTo);
4026 break;
4027 } else if (r.info.packageName.equals(dest.getPackageName()) &&
4028 r.info.name.equals(dest.getClassName())) {
4029 finishTo = i;
4030 parent = r;
4031 foundParentInTask = true;
4032 break;
4033 }
4034 }
4035 }
4036
4037 IActivityController controller = mService.mController;
4038 if (controller != null) {
4039 ActivityRecord next = topRunningActivityLocked(srec.appToken, 0);
4040 if (next != null) {
4041 // ask watcher if this is allowed
4042 boolean resumeOK = true;
4043 try {
4044 resumeOK = controller.activityResuming(next.packageName);
4045 } catch (RemoteException e) {
4046 mService.mController = null;
4047 }
4048
4049 if (!resumeOK) {
4050 return false;
4051 }
4052 }
4053 }
4054 final long origId = Binder.clearCallingIdentity();
4055 for (int i = start; i > finishTo; i--) {
4056 ActivityRecord r = mHistory.get(i);
4057 requestFinishActivityLocked(r.appToken, resultCode, resultData,
4058 "navigate-up", true);
4059 // Only return the supplied result for the first activity finished
4060 resultCode = Activity.RESULT_CANCELED;
4061 resultData = null;
4062 }
4063
4064 if (parent != null && foundParentInTask) {
4065 final int parentLaunchMode = parent.info.launchMode;
4066 final int destIntentFlags = destIntent.getFlags();
4067 if (parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE ||
4068 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TASK ||
4069 parentLaunchMode == ActivityInfo.LAUNCH_SINGLE_TOP ||
4070 (destIntentFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
4071 parent.deliverNewIntentLocked(srec.info.applicationInfo.uid, destIntent);
4072 } else {
4073 try {
4074 ActivityInfo aInfo = AppGlobals.getPackageManager().getActivityInfo(
4075 destIntent.getComponent(), 0, srec.userId);
4076 int res = startActivityLocked(srec.app.thread, destIntent,
4077 null, aInfo, parent.appToken, null,
4078 0, -1, parent.launchedFromUid, parent.launchedFromPackage,
4079 0, null, true, null);
4080 foundParentInTask = res == ActivityManager.START_SUCCESS;
4081 } catch (RemoteException e) {
4082 foundParentInTask = false;
4083 }
4084 requestFinishActivityLocked(parent.appToken, resultCode,
4085 resultData, "navigate-up", true);
4086 }
4087 }
4088 Binder.restoreCallingIdentity(origId);
4089 return foundParentInTask;
4090 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004091 /**
4092 * Perform the common clean-up of an activity record. This is called both
4093 * as part of destroyActivityLocked() (when destroying the client-side
4094 * representation) and cleaning things up as a result of its hosting
4095 * processing going away, in which case there is no remaining client-side
4096 * state to destroy so only the cleanup here is needed.
4097 */
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004098 final void cleanUpActivityLocked(ActivityRecord r, boolean cleanServices,
4099 boolean setState) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004100 if (mResumedActivity == r) {
4101 mResumedActivity = null;
4102 }
4103 if (mService.mFocusedActivity == r) {
4104 mService.mFocusedActivity = null;
4105 }
4106
4107 r.configDestroy = false;
4108 r.frozenBeforeDestroy = false;
4109
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004110 if (setState) {
4111 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r + " (cleaning up)");
4112 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004113 if (DEBUG_APP) Slog.v(TAG, "Clearing app during cleanUp for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004114 r.app = null;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004115 }
4116
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004117 // Make sure this record is no longer in the pending finishes list.
4118 // This could happen, for example, if we are trimming activities
4119 // down to the max limit while they are still waiting to finish.
4120 mFinishingActivities.remove(r);
4121 mWaitingVisibleActivities.remove(r);
4122
4123 // Remove any pending results.
4124 if (r.finishing && r.pendingResults != null) {
4125 for (WeakReference<PendingIntentRecord> apr : r.pendingResults) {
4126 PendingIntentRecord rec = apr.get();
4127 if (rec != null) {
4128 mService.cancelIntentSenderLocked(rec, false);
4129 }
4130 }
4131 r.pendingResults = null;
4132 }
4133
4134 if (cleanServices) {
4135 cleanUpActivityServicesLocked(r);
4136 }
4137
4138 if (mService.mPendingThumbnails.size() > 0) {
4139 // There are clients waiting to receive thumbnails so, in case
4140 // this is an activity that someone is waiting for, add it
4141 // to the pending list so we can correctly update the clients.
Craig Mautnercae015f2013-02-08 14:31:27 -08004142 mCancelledThumbnails.add(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004143 }
4144
4145 // Get rid of any pending idle timeouts.
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004146 removeTimeoutsForActivityLocked(r);
4147 }
4148
4149 private void removeTimeoutsForActivityLocked(ActivityRecord r) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004150 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
Dianne Hackborn162bc0e2012-04-09 14:06:16 -07004151 mHandler.removeMessages(STOP_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004152 mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004153 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn2a29b3a2012-03-15 15:48:38 -07004154 r.finishLaunchTickingLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004155 }
4156
Dianne Hackborn5c607432012-02-28 14:44:19 -08004157 final void removeActivityFromHistoryLocked(ActivityRecord r) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004158 finishActivityResultsLocked(r, Activity.RESULT_CANCELED, null);
4159 r.makeFinishing();
4160 if (DEBUG_ADD_REMOVE) {
4161 RuntimeException here = new RuntimeException("here");
4162 here.fillInStackTrace();
4163 Slog.i(TAG, "Removing activity " + r + " from stack");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004164 }
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004165 mHistory.remove(r);
4166 r.takeFromHistory();
4167 removeTimeoutsForActivityLocked(r);
4168 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4169 + " (removed from history)");
4170 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004171 if (DEBUG_APP) Slog.v(TAG, "Clearing app during remove for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004172 r.app = null;
4173 mService.mWindowManager.removeAppToken(r.appToken);
4174 if (VALIDATE_TOKENS) {
4175 validateAppTokensLocked();
4176 }
4177 cleanUpActivityServicesLocked(r);
4178 r.removeUriPermissionsLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004179 }
4180
4181 /**
4182 * Perform clean-up of service connections in an activity record.
4183 */
4184 final void cleanUpActivityServicesLocked(ActivityRecord r) {
4185 // Throw away any services that have been bound by this activity.
4186 if (r.connections != null) {
4187 Iterator<ConnectionRecord> it = r.connections.iterator();
4188 while (it.hasNext()) {
4189 ConnectionRecord c = it.next();
Dianne Hackborn599db5c2012-08-03 19:28:48 -07004190 mService.mServices.removeConnectionLocked(c, null, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004191 }
4192 r.connections = null;
4193 }
4194 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004195
4196 final void scheduleDestroyActivities(ProcessRecord owner, boolean oomAdj, String reason) {
4197 Message msg = mHandler.obtainMessage(DESTROY_ACTIVITIES_MSG);
4198 msg.obj = new ScheduleDestroyArgs(owner, oomAdj, reason);
4199 mHandler.sendMessage(msg);
4200 }
4201
Dianne Hackborn28695e02011-11-02 21:59:51 -07004202 final void destroyActivitiesLocked(ProcessRecord owner, boolean oomAdj, String reason) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004203 boolean lastIsOpaque = false;
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004204 boolean activityRemoved = false;
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004205 for (int i=mHistory.size()-1; i>=0; i--) {
4206 ActivityRecord r = mHistory.get(i);
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004207 if (r.finishing) {
4208 continue;
4209 }
4210 if (r.fullscreen) {
4211 lastIsOpaque = true;
4212 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004213 if (owner != null && r.app != owner) {
4214 continue;
4215 }
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004216 if (!lastIsOpaque) {
4217 continue;
4218 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004219 // We can destroy this one if we have its icicle saved and
4220 // it is not in the process of pausing/stopping/finishing.
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004221 if (r.app != null && r != mResumedActivity && r != mPausingActivity
4222 && r.haveState && !r.visible && r.stopped
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004223 && r.state != ActivityState.DESTROYING
4224 && r.state != ActivityState.DESTROYED) {
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004225 if (DEBUG_SWITCH) Slog.v(TAG, "Destroying " + r + " in state " + r.state
4226 + " resumed=" + mResumedActivity
4227 + " pausing=" + mPausingActivity);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004228 if (destroyActivityLocked(r, true, oomAdj, reason)) {
4229 activityRemoved = true;
4230 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004231 }
4232 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004233 if (activityRemoved) {
4234 resumeTopActivityLocked(null);
4235 }
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004236 }
4237
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004238 /**
4239 * Destroy the current CLIENT SIDE instance of an activity. This may be
4240 * called both when actually finishing an activity, or when performing
4241 * a configuration switch where we destroy the current client-side object
4242 * but then create a new client-side object for this same HistoryRecord.
4243 */
4244 final boolean destroyActivityLocked(ActivityRecord r,
Dianne Hackborn28695e02011-11-02 21:59:51 -07004245 boolean removeFromApp, boolean oomAdj, String reason) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004246 if (DEBUG_SWITCH || DEBUG_CLEANUP) Slog.v(
Dianne Hackborn755c8bf2012-05-07 15:06:09 -07004247 TAG, "Removing activity from " + reason + ": token=" + r
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004248 + ", app=" + (r.app != null ? r.app.processName : "(null)"));
4249 EventLog.writeEvent(EventLogTags.AM_DESTROY_ACTIVITY,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004250 r.userId, System.identityHashCode(r),
Dianne Hackborn28695e02011-11-02 21:59:51 -07004251 r.task.taskId, r.shortComponentName, reason);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004252
4253 boolean removedFromHistory = false;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004254
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004255 cleanUpActivityLocked(r, false, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004256
4257 final boolean hadApp = r.app != null;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004258
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004259 if (hadApp) {
4260 if (removeFromApp) {
4261 int idx = r.app.activities.indexOf(r);
4262 if (idx >= 0) {
4263 r.app.activities.remove(idx);
4264 }
4265 if (mService.mHeavyWeightProcess == r.app && r.app.activities.size() <= 0) {
4266 mService.mHeavyWeightProcess = null;
4267 mService.mHandler.sendEmptyMessage(
4268 ActivityManagerService.CANCEL_HEAVY_NOTIFICATION_MSG);
4269 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004270 if (r.app.activities.size() == 0) {
Dianne Hackborn2d1b3782012-09-09 17:49:39 -07004271 // No longer have activities, so update oom adj.
4272 mService.updateOomAdjLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004273 }
4274 }
4275
4276 boolean skipDestroy = false;
4277
4278 try {
4279 if (DEBUG_SWITCH) Slog.i(TAG, "Destroying: " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004280 r.app.thread.scheduleDestroyActivity(r.appToken, r.finishing,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004281 r.configChangeFlags);
4282 } catch (Exception e) {
4283 // We can just ignore exceptions here... if the process
4284 // has crashed, our death notification will clean things
4285 // up.
4286 //Slog.w(TAG, "Exception thrown during finish", e);
4287 if (r.finishing) {
4288 removeActivityFromHistoryLocked(r);
4289 removedFromHistory = true;
4290 skipDestroy = true;
4291 }
4292 }
4293
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004294 r.nowVisible = false;
4295
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004296 // If the activity is finishing, we need to wait on removing it
4297 // from the list to give it a chance to do its cleanup. During
4298 // that time it may make calls back with its token so we need to
4299 // be able to find it on the list and so we don't want to remove
4300 // it from the list yet. Otherwise, we can just immediately put
4301 // it in the destroyed state since we are not removing it from the
4302 // list.
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004303 if (r.finishing && !skipDestroy) {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004304 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYING: " + r
4305 + " (destroy requested)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004306 r.state = ActivityState.DESTROYING;
4307 Message msg = mHandler.obtainMessage(DESTROY_TIMEOUT_MSG);
4308 msg.obj = r;
4309 mHandler.sendMessageDelayed(msg, DESTROY_TIMEOUT);
4310 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004311 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4312 + " (destroy skipped)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004313 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004314 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004315 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004316 }
4317 } else {
4318 // remove this record from the history.
4319 if (r.finishing) {
4320 removeActivityFromHistoryLocked(r);
4321 removedFromHistory = true;
4322 } else {
Dianne Hackbornce86ba82011-07-13 19:33:41 -07004323 if (DEBUG_STATES) Slog.v(TAG, "Moving to DESTROYED: " + r
4324 + " (no app)");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004325 r.state = ActivityState.DESTROYED;
Dianne Hackborn07981492013-01-28 11:36:23 -08004326 if (DEBUG_APP) Slog.v(TAG, "Clearing app during destroy for activity " + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004327 r.app = null;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004328 }
4329 }
4330
4331 r.configChangeFlags = 0;
4332
4333 if (!mLRUActivities.remove(r) && hadApp) {
4334 Slog.w(TAG, "Activity " + r + " being finished, but not in LRU list");
4335 }
4336
4337 return removedFromHistory;
4338 }
4339
4340 final void activityDestroyed(IBinder token) {
4341 synchronized (mService) {
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004342 final long origId = Binder.clearCallingIdentity();
4343 try {
4344 ActivityRecord r = ActivityRecord.forToken(token);
4345 if (r != null) {
4346 mHandler.removeMessages(DESTROY_TIMEOUT_MSG, r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004347 }
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004348
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004349 int index = mHistory.indexOf(r);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004350 if (index >= 0) {
4351 if (r.state == ActivityState.DESTROYING) {
Dianne Hackborn45a25bc2012-06-28 13:49:17 -07004352 cleanUpActivityLocked(r, true, false);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004353 removeActivityFromHistoryLocked(r);
4354 }
4355 }
4356 resumeTopActivityLocked(null);
4357 } finally {
4358 Binder.restoreCallingIdentity(origId);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004359 }
4360 }
4361 }
4362
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004363 private void removeHistoryRecordsForAppLocked(ArrayList<ActivityRecord> list,
4364 ProcessRecord app, String listName) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004365 int i = list.size();
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004366 if (DEBUG_CLEANUP) Slog.v(
4367 TAG, "Removing app " + app + " from list " + listName
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004368 + " with " + i + " entries");
4369 while (i > 0) {
4370 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004371 ActivityRecord r = list.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004372 if (DEBUG_CLEANUP) Slog.v(TAG, "Record #" + i + " " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004373 if (r.app == app) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004374 if (DEBUG_CLEANUP) Slog.v(TAG, "---> REMOVING this entry!");
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004375 list.remove(i);
Dianne Hackborn42e620c2012-06-24 13:20:51 -07004376 removeTimeoutsForActivityLocked(r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004377 }
4378 }
4379 }
4380
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004381 boolean removeHistoryRecordsForAppLocked(ProcessRecord app) {
4382 removeHistoryRecordsForAppLocked(mLRUActivities, app, "mLRUActivities");
4383 removeHistoryRecordsForAppLocked(mStoppingActivities, app, "mStoppingActivities");
4384 removeHistoryRecordsForAppLocked(mGoingToSleepActivities, app, "mGoingToSleepActivities");
4385 removeHistoryRecordsForAppLocked(mWaitingVisibleActivities, app,
4386 "mWaitingVisibleActivities");
4387 removeHistoryRecordsForAppLocked(mFinishingActivities, app, "mFinishingActivities");
4388
4389 boolean hasVisibleActivities = false;
4390
4391 // Clean out the history list.
4392 int i = mHistory.size();
4393 if (DEBUG_CLEANUP) Slog.v(
4394 TAG, "Removing app " + app + " from history with " + i + " entries");
4395 while (i > 0) {
4396 i--;
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004397 ActivityRecord r = mHistory.get(i);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004398 if (DEBUG_CLEANUP) Slog.v(
4399 TAG, "Record #" + i + " " + r + ": app=" + r.app);
4400 if (r.app == app) {
Dianne Hackborn07981492013-01-28 11:36:23 -08004401 boolean remove;
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004402 if ((!r.haveState && !r.stateNotNeeded) || r.finishing) {
Dianne Hackborn07981492013-01-28 11:36:23 -08004403 // Don't currently have state for the activity, or
4404 // it is finishing -- always remove it.
4405 remove = true;
4406 } else if (r.launchCount > 2 &&
4407 r.lastLaunchTime > (SystemClock.uptimeMillis()-60000)) {
4408 // We have launched this activity too many times since it was
4409 // able to run, so give up and remove it.
4410 remove = true;
4411 } else {
4412 // The process may be gone, but the activity lives on!
4413 remove = false;
4414 }
4415 if (remove) {
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004416 if (ActivityStack.DEBUG_ADD_REMOVE || DEBUG_CLEANUP) {
4417 RuntimeException here = new RuntimeException("here");
4418 here.fillInStackTrace();
4419 Slog.i(TAG, "Removing activity " + r + " from stack at " + i
4420 + ": haveState=" + r.haveState
4421 + " stateNotNeeded=" + r.stateNotNeeded
4422 + " finishing=" + r.finishing
4423 + " state=" + r.state, here);
4424 }
4425 if (!r.finishing) {
4426 Slog.w(TAG, "Force removing " + r + ": app died, no saved state");
4427 EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY,
4428 r.userId, System.identityHashCode(r),
4429 r.task.taskId, r.shortComponentName,
4430 "proc died without state saved");
4431 }
4432 removeActivityFromHistoryLocked(r);
4433
4434 } else {
4435 // We have the current state for this activity, so
4436 // it can be restarted later when needed.
4437 if (localLOGV) Slog.v(
4438 TAG, "Keeping entry, setting app to null");
4439 if (r.visible) {
4440 hasVisibleActivities = true;
4441 }
Dianne Hackborn07981492013-01-28 11:36:23 -08004442 if (DEBUG_APP) Slog.v(TAG, "Clearing app during removeHistory for activity "
4443 + r);
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004444 r.app = null;
4445 r.nowVisible = false;
4446 if (!r.haveState) {
4447 if (ActivityStack.DEBUG_SAVED_STATE) Slog.i(TAG,
4448 "App died, clearing saved state of " + r);
4449 r.icicle = null;
4450 }
4451 }
4452
4453 r.stack.cleanUpActivityLocked(r, true, true);
4454 }
4455 }
4456
4457 return hasVisibleActivities;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004458 }
4459
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004460 /**
4461 * Move the current home activity's task (if one exists) to the front
4462 * of the stack.
4463 */
4464 final void moveHomeToFrontLocked() {
4465 TaskRecord homeTask = null;
4466 for (int i=mHistory.size()-1; i>=0; i--) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004467 ActivityRecord hr = mHistory.get(i);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004468 if (hr.isHomeActivity) {
4469 homeTask = hr.task;
Dianne Hackborn94cb2eb2011-01-13 21:09:44 -08004470 break;
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004471 }
4472 }
4473 if (homeTask != null) {
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004474 moveTaskToFrontLocked(homeTask, null, null);
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004475 }
4476 }
4477
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004478 final void updateTransitLocked(int transit, Bundle options) {
4479 if (options != null) {
4480 ActivityRecord r = topRunningActivityLocked(null);
4481 if (r != null && r.state != ActivityState.RESUMED) {
4482 r.updateOptionsLocked(options);
4483 } else {
4484 ActivityOptions.abort(options);
4485 }
4486 }
4487 mService.mWindowManager.prepareAppTransition(transit, false);
4488 }
Dianne Hackborn621e17d2010-11-22 15:59:56 -08004489
Craig Mautnercae015f2013-02-08 14:31:27 -08004490 final boolean findTaskToMoveToFrontLocked(int taskId, int flags, Bundle options) {
4491 for (int i = mHistory.size() - 1; i >= 0; i--) {
4492 ActivityRecord hr = mHistory.get(i);
4493 if (hr.task.taskId == taskId) {
4494 if ((flags & ActivityManager.MOVE_TASK_NO_USER_ACTION) == 0) {
4495 mUserLeaving = true;
4496 }
4497 if ((flags & ActivityManager.MOVE_TASK_WITH_HOME) != 0) {
4498 // Caller wants the home activity moved with it. To accomplish this,
4499 // we'll just move the home task to the top first.
4500 moveHomeToFrontLocked();
4501 }
4502 moveTaskToFrontLocked(hr.task, null, options);
4503 return true;
4504 }
4505 }
4506 return false;
4507 }
4508
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004509 final void moveTaskToFrontLocked(TaskRecord tr, ActivityRecord reason, Bundle options) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004510 if (DEBUG_SWITCH) Slog.v(TAG, "moveTaskToFront: " + tr);
4511
4512 final int task = tr.taskId;
4513 int top = mHistory.size()-1;
4514
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004515 if (top < 0 || (mHistory.get(top)).task.taskId == task) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004516 // nothing to do!
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004517 if (reason != null &&
4518 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
4519 ActivityOptions.abort(options);
4520 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004521 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn7f58b952012-04-18 12:59:29 -07004522 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004523 return;
4524 }
4525
Dianne Hackbornbe707852011-11-11 14:32:10 -08004526 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004527
4528 // Applying the affinities may have removed entries from the history,
4529 // so get the size again.
4530 top = mHistory.size()-1;
4531 int pos = top;
4532
4533 // Shift all activities with this task up to the top
4534 // of the stack, keeping them in the same internal order.
4535 while (pos >= 0) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004536 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004537 if (localLOGV) Slog.v(
4538 TAG, "At " + pos + " ckp " + r.task + ": " + r);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004539 if (r.task.taskId == task) {
4540 if (localLOGV) Slog.v(TAG, "Removing and adding at " + top);
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004541 if (DEBUG_ADD_REMOVE) {
4542 RuntimeException here = new RuntimeException("here");
4543 here.fillInStackTrace();
4544 Slog.i(TAG, "Removing and adding activity " + r + " to stack at " + top, here);
4545 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004546 mHistory.remove(pos);
4547 mHistory.add(top, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004548 moved.add(0, r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004549 top--;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004550 }
4551 pos--;
4552 }
4553
4554 if (DEBUG_TRANSITION) Slog.v(TAG,
4555 "Prepare to front transition: task=" + tr);
4556 if (reason != null &&
4557 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004558 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004559 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004560 ActivityRecord r = topRunningActivityLocked(null);
4561 if (r != null) {
4562 mNoAnimActivities.add(r);
4563 }
Dianne Hackborn8078d8c2012-03-20 11:11:26 -07004564 ActivityOptions.abort(options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004565 } else {
Craig Mautner4b71aa12012-12-27 17:20:01 -08004566 updateTransitLocked(AppTransition.TRANSIT_TASK_TO_FRONT, options);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004567 }
Craig Mautner30e2d722013-02-12 11:30:16 -08004568
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004569 mService.mWindowManager.moveAppTokensToTop(moved);
Craig Mautner30e2d722013-02-12 11:30:16 -08004570 mService.mWindowManager.moveTaskToTop(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004571 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004572 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004573 }
4574
4575 finishTaskMoveLocked(task);
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004576 EventLog.writeEvent(EventLogTags.AM_TASK_TO_FRONT, tr.userId, task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004577 }
4578
4579 private final void finishTaskMoveLocked(int task) {
4580 resumeTopActivityLocked(null);
4581 }
4582
4583 /**
4584 * Worker method for rearranging history stack. Implements the function of moving all
4585 * activities for a specific task (gathering them if disjoint) into a single group at the
4586 * bottom of the stack.
4587 *
4588 * If a watcher is installed, the action is preflighted and the watcher has an opportunity
4589 * to premeptively cancel the move.
4590 *
4591 * @param task The taskId to collect and move to the bottom.
4592 * @return Returns true if the move completed, false if not.
4593 */
4594 final boolean moveTaskToBackLocked(int task, ActivityRecord reason) {
4595 Slog.i(TAG, "moveTaskToBack: " + task);
4596
4597 // If we have a watcher, preflight the move before committing to it. First check
4598 // for *other* available tasks, but if none are available, then try again allowing the
4599 // current task to be selected.
4600 if (mMainStack && mService.mController != null) {
4601 ActivityRecord next = topRunningActivityLocked(null, task);
4602 if (next == null) {
4603 next = topRunningActivityLocked(null, 0);
4604 }
4605 if (next != null) {
4606 // ask watcher if this is allowed
4607 boolean moveOK = true;
4608 try {
4609 moveOK = mService.mController.activityResuming(next.packageName);
4610 } catch (RemoteException e) {
4611 mService.mController = null;
4612 }
4613 if (!moveOK) {
4614 return false;
4615 }
4616 }
4617 }
4618
Dianne Hackbornbe707852011-11-11 14:32:10 -08004619 ArrayList<IBinder> moved = new ArrayList<IBinder>();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004620
4621 if (DEBUG_TRANSITION) Slog.v(TAG,
4622 "Prepare to back transition: task=" + task);
4623
4624 final int N = mHistory.size();
4625 int bottom = 0;
4626 int pos = 0;
4627
4628 // Shift all activities with this task down to the bottom
4629 // of the stack, keeping them in the same internal order.
4630 while (pos < N) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004631 ActivityRecord r = mHistory.get(pos);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004632 if (localLOGV) Slog.v(
4633 TAG, "At " + pos + " ckp " + r.task + ": " + r);
4634 if (r.task.taskId == task) {
4635 if (localLOGV) Slog.v(TAG, "Removing and adding at " + (N-1));
Dianne Hackborn98cfebc2011-10-18 13:17:33 -07004636 if (DEBUG_ADD_REMOVE) {
4637 RuntimeException here = new RuntimeException("here");
4638 here.fillInStackTrace();
4639 Slog.i(TAG, "Removing and adding activity " + r + " to stack at "
4640 + bottom, here);
4641 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004642 mHistory.remove(pos);
4643 mHistory.add(bottom, r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004644 moved.add(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004645 bottom++;
4646 }
4647 pos++;
4648 }
4649
4650 if (reason != null &&
4651 (reason.intent.getFlags()&Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004652 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004653 AppTransition.TRANSIT_NONE, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004654 ActivityRecord r = topRunningActivityLocked(null);
4655 if (r != null) {
4656 mNoAnimActivities.add(r);
4657 }
4658 } else {
Dianne Hackborn7da6ac32010-12-09 19:22:04 -08004659 mService.mWindowManager.prepareAppTransition(
Craig Mautner4b71aa12012-12-27 17:20:01 -08004660 AppTransition.TRANSIT_TASK_TO_BACK, false);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004661 }
4662 mService.mWindowManager.moveAppTokensToBottom(moved);
Craig Mautner30e2d722013-02-12 11:30:16 -08004663 mService.mWindowManager.moveTaskToBottom(task);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004664 if (VALIDATE_TOKENS) {
Dianne Hackbornbe707852011-11-11 14:32:10 -08004665 validateAppTokensLocked();
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004666 }
4667
4668 finishTaskMoveLocked(task);
4669 return true;
4670 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004671
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004672 public ActivityManager.TaskThumbnails getTaskThumbnailsLocked(TaskRecord tr) {
4673 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4674 ActivityRecord resumed = mResumedActivity;
4675 if (resumed != null && resumed.thumbHolder == tr) {
4676 info.mainThumbnail = resumed.stack.screenshotActivities(resumed);
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004677 }
Dianne Hackborn6a864952012-09-21 18:46:11 -07004678 if (info.mainThumbnail == null) {
4679 info.mainThumbnail = tr.lastThumbnail;
4680 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004681 return info;
4682 }
4683
Dianne Hackborn15491c62012-09-19 10:59:14 -07004684 public Bitmap getTaskTopThumbnailLocked(TaskRecord tr) {
4685 ActivityRecord resumed = mResumedActivity;
4686 if (resumed != null && resumed.task == tr) {
4687 // This task is the current resumed task, we just need to take
4688 // a screenshot of it and return that.
4689 return resumed.stack.screenshotActivities(resumed);
4690 }
4691 // Return the information about the task, to figure out the top
4692 // thumbnail to return.
4693 TaskAccessInfo info = getTaskAccessInfoLocked(tr.taskId, true);
4694 if (info.numSubThumbbails <= 0) {
Dianne Hackborn6a864952012-09-21 18:46:11 -07004695 return info.mainThumbnail != null ? info.mainThumbnail : tr.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004696 }
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004697 return info.subtasks.get(info.numSubThumbbails-1).holder.lastThumbnail;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004698 }
4699
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004700 public ActivityRecord removeTaskActivitiesLocked(int taskId, int subTaskIndex,
4701 boolean taskRequired) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004702 TaskAccessInfo info = getTaskAccessInfoLocked(taskId, false);
4703 if (info.root == null) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004704 if (taskRequired) {
4705 Slog.w(TAG, "removeTaskLocked: unknown taskId " + taskId);
4706 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004707 return null;
4708 }
4709
4710 if (subTaskIndex < 0) {
4711 // Just remove the entire task.
4712 performClearTaskAtIndexLocked(taskId, info.rootIndex);
4713 return info.root;
4714 }
4715
4716 if (subTaskIndex >= info.subtasks.size()) {
Dianne Hackborn9da2d402012-03-15 13:43:08 -07004717 if (taskRequired) {
4718 Slog.w(TAG, "removeTaskLocked: unknown subTaskIndex " + subTaskIndex);
4719 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004720 return null;
4721 }
4722
Dianne Hackborncc5a0552012-10-01 16:32:39 -07004723 // Remove all of this task's activities starting at the sub task.
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004724 TaskAccessInfo.SubTask subtask = info.subtasks.get(subTaskIndex);
4725 performClearTaskAtIndexLocked(taskId, subtask.index);
4726 return subtask.activity;
4727 }
4728
4729 public TaskAccessInfo getTaskAccessInfoLocked(int taskId, boolean inclThumbs) {
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004730 final TaskAccessInfo thumbs = new TaskAccessInfo();
4731 // How many different sub-thumbnails?
4732 final int NA = mHistory.size();
4733 int j = 0;
4734 ThumbnailHolder holder = null;
4735 while (j < NA) {
4736 ActivityRecord ar = mHistory.get(j);
4737 if (!ar.finishing && ar.task.taskId == taskId) {
Dianne Hackborn8da429e2012-09-23 12:52:19 -07004738 thumbs.root = ar;
4739 thumbs.rootIndex = j;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004740 holder = ar.thumbHolder;
Dianne Hackborn15491c62012-09-19 10:59:14 -07004741 if (holder != null) {
4742 thumbs.mainThumbnail = holder.lastThumbnail;
4743 }
4744 j++;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004745 break;
4746 }
4747 j++;
4748 }
4749
4750 if (j >= NA) {
4751 return thumbs;
4752 }
4753
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004754 ArrayList<TaskAccessInfo.SubTask> subtasks = new ArrayList<TaskAccessInfo.SubTask>();
4755 thumbs.subtasks = subtasks;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004756 while (j < NA) {
4757 ActivityRecord ar = mHistory.get(j);
4758 j++;
4759 if (ar.finishing) {
4760 continue;
4761 }
4762 if (ar.task.taskId != taskId) {
4763 break;
4764 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004765 if (ar.thumbHolder != holder && holder != null) {
4766 thumbs.numSubThumbbails++;
4767 holder = ar.thumbHolder;
4768 TaskAccessInfo.SubTask sub = new TaskAccessInfo.SubTask();
Dianne Hackborn15491c62012-09-19 10:59:14 -07004769 sub.holder = holder;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004770 sub.activity = ar;
4771 sub.index = j-1;
4772 subtasks.add(sub);
4773 }
4774 }
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004775 if (thumbs.numSubThumbbails > 0) {
4776 thumbs.retriever = new IThumbnailRetriever.Stub() {
Craig Mautner05d6272ba2013-02-11 09:39:27 -08004777 @Override
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004778 public Bitmap getThumbnail(int index) {
4779 if (index < 0 || index >= thumbs.subtasks.size()) {
4780 return null;
4781 }
Dianne Hackborn15491c62012-09-19 10:59:14 -07004782 TaskAccessInfo.SubTask sub = thumbs.subtasks.get(index);
4783 ActivityRecord resumed = mResumedActivity;
4784 if (resumed != null && resumed.thumbHolder == sub.holder) {
4785 return resumed.stack.screenshotActivities(resumed);
4786 }
4787 return sub.holder.lastThumbnail;
Dianne Hackborn0c5001d2011-04-12 18:16:08 -07004788 }
4789 };
4790 }
4791 return thumbs;
4792 }
4793
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004794 private final void logStartActivity(int tag, ActivityRecord r,
4795 TaskRecord task) {
4796 EventLog.writeEvent(tag,
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004797 r.userId, System.identityHashCode(r), task.taskId,
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004798 r.shortComponentName, r.intent.getAction(),
4799 r.intent.getType(), r.intent.getDataString(),
4800 r.intent.getFlags());
4801 }
4802
4803 /**
4804 * Make sure the given activity matches the current configuration. Returns
4805 * false if the activity had to be destroyed. Returns true if the
4806 * configuration is the same, or the activity will remain running as-is
4807 * for whatever reason. Ensures the HistoryRecord is updated with the
4808 * correct configuration and all other bookkeeping is handled.
4809 */
4810 final boolean ensureActivityConfigurationLocked(ActivityRecord r,
4811 int globalChanges) {
4812 if (mConfigWillChange) {
4813 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4814 "Skipping config check (will change): " + r);
4815 return true;
4816 }
4817
4818 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4819 "Ensuring correct configuration: " + r);
4820
4821 // Short circuit: if the two configurations are the exact same
4822 // object (the common case), then there is nothing to do.
4823 Configuration newConfig = mService.mConfiguration;
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004824 if (r.configuration == newConfig && !r.forceNewConfig) {
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004825 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4826 "Configuration unchanged in " + r);
4827 return true;
4828 }
4829
4830 // We don't worry about activities that are finishing.
4831 if (r.finishing) {
4832 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4833 "Configuration doesn't matter in finishing " + r);
4834 r.stopFreezingScreenLocked(false);
4835 return true;
4836 }
4837
4838 // Okay we now are going to make this activity have the new config.
4839 // But then we need to figure out how it needs to deal with that.
4840 Configuration oldConfig = r.configuration;
4841 r.configuration = newConfig;
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004842
4843 // Determine what has changed. May be nothing, if this is a config
4844 // that has come back from the app after going idle. In that case
4845 // we just want to leave the official config object now in the
4846 // activity and do nothing else.
4847 final int changes = oldConfig.diff(newConfig);
4848 if (changes == 0 && !r.forceNewConfig) {
4849 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4850 "Configuration no differences in " + r);
4851 return true;
4852 }
4853
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004854 // If the activity isn't currently running, just leave the new
4855 // configuration and it will pick that up next time it starts.
4856 if (r.app == null || r.app.thread == null) {
4857 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
4858 "Configuration doesn't matter not running " + r);
4859 r.stopFreezingScreenLocked(false);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004860 r.forceNewConfig = false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004861 return true;
4862 }
4863
Dianne Hackborn58f42a52011-10-10 13:46:34 -07004864 // Figure out how to handle the changes between the configurations.
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004865 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) {
4866 Slog.v(TAG, "Checking to restart " + r.info.name + ": changed=0x"
4867 + Integer.toHexString(changes) + ", handles=0x"
Dianne Hackborne6676352011-06-01 16:51:20 -07004868 + Integer.toHexString(r.info.getRealConfigChanged())
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004869 + ", newConfig=" + newConfig);
4870 }
Dianne Hackborne6676352011-06-01 16:51:20 -07004871 if ((changes&(~r.info.getRealConfigChanged())) != 0 || r.forceNewConfig) {
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004872 // Aha, the activity isn't handling the change, so DIE DIE DIE.
4873 r.configChangeFlags |= changes;
4874 r.startFreezingScreenLocked(r.app, globalChanges);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004875 r.forceNewConfig = false;
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004876 if (r.app == null || r.app.thread == null) {
4877 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004878 "Config is destroying non-running " + r);
Dianne Hackborn28695e02011-11-02 21:59:51 -07004879 destroyActivityLocked(r, true, false, "config");
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004880 } else if (r.state == ActivityState.PAUSING) {
4881 // A little annoying: we are waiting for this activity to
4882 // finish pausing. Let's not do anything now, but just
4883 // flag that it needs to be restarted when done pausing.
4884 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004885 "Config is skipping already pausing " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004886 r.configDestroy = true;
4887 return true;
4888 } else if (r.state == ActivityState.RESUMED) {
4889 // Try to optimize this case: the configuration is changing
4890 // and we need to restart the top, resumed activity.
4891 // Instead of doing the normal handshaking, just say
4892 // "restart!".
4893 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004894 "Config is relaunching resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004895 relaunchActivityLocked(r, r.configChangeFlags, true);
4896 r.configChangeFlags = 0;
4897 } else {
4898 if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG,
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004899 "Config is relaunching non-resumed " + r);
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004900 relaunchActivityLocked(r, r.configChangeFlags, false);
4901 r.configChangeFlags = 0;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004902 }
Dianne Hackborn3c4c2b72010-10-05 18:07:54 -07004903
4904 // All done... tell the caller we weren't able to keep this
4905 // activity around.
4906 return false;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004907 }
4908
4909 // Default case: the activity can handle this new configuration, so
4910 // hand it over. Note that we don't need to give it the new
4911 // configuration, since we always send configuration changes to all
4912 // process when they happen so it can just use whatever configuration
4913 // it last got.
4914 if (r.app != null && r.app.thread != null) {
4915 try {
4916 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Sending new config to " + r);
Dianne Hackbornbe707852011-11-11 14:32:10 -08004917 r.app.thread.scheduleActivityConfigurationChanged(r.appToken);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004918 } catch (RemoteException e) {
4919 // If process died, whatever.
4920 }
4921 }
4922 r.stopFreezingScreenLocked(false);
4923
4924 return true;
4925 }
4926
4927 private final boolean relaunchActivityLocked(ActivityRecord r,
4928 int changes, boolean andResume) {
4929 List<ResultInfo> results = null;
4930 List<Intent> newIntents = null;
4931 if (andResume) {
4932 results = r.results;
4933 newIntents = r.newIntents;
4934 }
4935 if (DEBUG_SWITCH) Slog.v(TAG, "Relaunching: " + r
4936 + " with results=" + results + " newIntents=" + newIntents
4937 + " andResume=" + andResume);
4938 EventLog.writeEvent(andResume ? EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY
Dianne Hackbornb12e1352012-09-26 11:39:20 -07004939 : EventLogTags.AM_RELAUNCH_ACTIVITY, r.userId, System.identityHashCode(r),
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004940 r.task.taskId, r.shortComponentName);
4941
4942 r.startFreezingScreenLocked(r.app, 0);
4943
4944 try {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004945 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG,
4946 (andResume ? "Relaunching to RESUMED " : "Relaunching to PAUSED ")
4947 + r);
Dianne Hackborne2515ee2011-04-27 18:52:56 -04004948 r.forceNewConfig = false;
Dianne Hackbornbe707852011-11-11 14:32:10 -08004949 r.app.thread.scheduleRelaunchActivity(r.appToken, results, newIntents,
Dianne Hackborn813075a62011-11-14 17:45:19 -08004950 changes, !andResume, new Configuration(mService.mConfiguration));
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004951 // Note: don't need to call pauseIfSleepingLocked() here, because
4952 // the caller will only pass in 'andResume' if this activity is
4953 // currently resumed, which implies we aren't sleeping.
4954 } catch (RemoteException e) {
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004955 if (DEBUG_SWITCH || DEBUG_STATES) Slog.i(TAG, "Relaunch failed", e);
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004956 }
4957
4958 if (andResume) {
4959 r.results = null;
4960 r.newIntents = null;
4961 if (mMainStack) {
4962 mService.reportResumedActivityLocked(r);
4963 }
Dianne Hackbornb61a0262012-05-14 17:19:18 -07004964 r.state = ActivityState.RESUMED;
4965 } else {
4966 mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
4967 r.state = ActivityState.PAUSED;
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07004968 }
4969
4970 return true;
4971 }
Dianne Hackborn90c52de2011-09-23 12:57:44 -07004972
4973 public void dismissKeyguardOnNextActivityLocked() {
4974 mDismissKeyguardOnNextActivity = true;
4975 }
Craig Mautnercae015f2013-02-08 14:31:27 -08004976
4977 boolean willActivityBeVisibleLocked(IBinder token) {
4978 int i;
4979 for (i = mHistory.size() - 1; i >= 0; i--) {
4980 ActivityRecord r = mHistory.get(i);
4981 if (r.appToken == token) {
4982 return true;
4983 }
4984 if (r.fullscreen && !r.finishing) {
4985 return false;
4986 }
4987 }
4988 return true;
4989 }
4990
4991 void closeSystemDialogsLocked() {
4992 for (int i = mHistory.size() - 1; i >= 0; i--) {
4993 ActivityRecord r = mHistory.get(i);
4994 if ((r.info.flags&ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS) != 0) {
4995 r.stack.finishActivityLocked(r, i,
4996 Activity.RESULT_CANCELED, null, "close-sys", true);
4997 }
4998 }
4999 }
5000
5001 boolean forceStopPackageLocked(String name, boolean doit, boolean evenPersistent, int userId) {
5002 boolean didSomething = false;
5003 TaskRecord lastTask = null;
5004 final int N = mHistory.size();
5005 for (int i = 0; i < N; i++) {
5006 ActivityRecord r = mHistory.get(i);
5007 final boolean samePackage = r.packageName.equals(name)
5008 || (name == null && r.userId == userId);
5009 if ((userId == UserHandle.USER_ALL || r.userId == userId)
5010 && (samePackage || r.task == lastTask)
5011 && (r.app == null || evenPersistent || !r.app.persistent)) {
5012 if (!doit) {
5013 if (r.finishing) {
5014 // If this activity is just finishing, then it is not
5015 // interesting as far as something to stop.
5016 continue;
5017 }
5018 return true;
5019 }
5020 didSomething = true;
5021 Slog.i(TAG, " Force finishing activity " + r);
5022 if (samePackage) {
5023 if (r.app != null) {
5024 r.app.removed = true;
5025 }
5026 r.app = null;
5027 }
5028 lastTask = r.task;
5029 if (r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
5030 null, "force-stop", true)) {
5031 i--;
5032 }
5033 }
5034 }
5035 return didSomething;
5036 }
5037
5038 ActivityRecord getTasksLocked(int maxNum, IThumbnailReceiver receiver,
5039 PendingThumbnailsRecord pending, List<RunningTaskInfo> list) {
5040 ActivityRecord topRecord = null;
5041 int pos = mHistory.size() - 1;
5042 ActivityRecord next = pos >= 0 ? mHistory.get(pos) : null;
5043 ActivityRecord top = null;
5044 TaskRecord curTask = null;
5045 int numActivities = 0;
5046 int numRunning = 0;
5047 while (pos >= 0 && maxNum > 0) {
5048 final ActivityRecord r = next;
5049 pos--;
5050 next = pos >= 0 ? mHistory.get(pos) : null;
5051
5052 // Initialize state for next task if needed.
5053 if (top == null || (top.state == ActivityState.INITIALIZING && top.task == r.task)) {
5054 top = r;
5055 curTask = r.task;
5056 numActivities = numRunning = 0;
5057 }
5058
5059 // Add 'r' into the current task.
5060 numActivities++;
5061 if (r.app != null && r.app.thread != null) {
5062 numRunning++;
5063 }
5064
5065 if (localLOGV) Slog.v(
5066 TAG, r.intent.getComponent().flattenToShortString()
5067 + ": task=" + r.task);
5068
5069 // If the next one is a different task, generate a new
5070 // TaskInfo entry for what we have.
5071 if (next == null || next.task != curTask) {
5072 RunningTaskInfo ci = new RunningTaskInfo();
5073 ci.id = curTask.taskId;
5074 ci.baseActivity = r.intent.getComponent();
5075 ci.topActivity = top.intent.getComponent();
5076 if (top.thumbHolder != null) {
5077 ci.description = top.thumbHolder.lastDescription;
5078 }
5079 ci.numActivities = numActivities;
5080 ci.numRunning = numRunning;
5081 //System.out.println(
5082 // "#" + maxNum + ": " + " descr=" + ci.description);
5083 if (receiver != null) {
5084 if (localLOGV) Slog.v(
5085 TAG, "State=" + top.state + "Idle=" + top.idle
5086 + " app=" + top.app
5087 + " thr=" + (top.app != null ? top.app.thread : null));
5088 if (top.state == ActivityState.RESUMED || top.state == ActivityState.PAUSING) {
5089 if (top.idle && top.app != null && top.app.thread != null) {
5090 topRecord = top;
5091 } else {
5092 top.thumbnailNeeded = true;
5093 }
5094 }
5095 pending.pendingRecords.add(top);
5096 }
5097 list.add(ci);
5098 maxNum--;
5099 top = null;
5100 }
5101 }
5102 return topRecord;
5103 }
5104
5105 public void unhandledBackLocked() {
5106 int top = mHistory.size() - 1;
5107 if (DEBUG_SWITCH) Slog.d(
5108 TAG, "Performing unhandledBack(): top activity at " + top);
5109 if (top > 0) {
5110 finishActivityLocked(mHistory.get(top),
5111 top, Activity.RESULT_CANCELED, null, "unhandled-back", true);
5112 }
5113 }
5114
5115 void handleAppCrashLocked(ProcessRecord app) {
5116 for (int i = mHistory.size() - 1; i >= 0; i--) {
5117 ActivityRecord r = mHistory.get(i);
5118 if (r.app == app) {
5119 Slog.w(TAG, " Force finishing activity "
5120 + r.intent.getComponent().flattenToShortString());
5121 r.stack.finishActivityLocked(r, i, Activity.RESULT_CANCELED,
5122 null, "crashed", false);
5123 }
5124 }
5125 }
5126
5127 void dumpActivitiesLocked(FileDescriptor fd, PrintWriter pw, boolean dumpAll,
5128 boolean dumpClient, String dumpPackage) {
5129 ActivityManagerService.dumpHistoryList(fd, pw, mHistory, " ", "Hist", true, !dumpAll,
5130 dumpClient, dumpPackage);
5131 }
5132
5133 ArrayList<ActivityRecord> getDumpActivitiesLocked(String name) {
5134 ArrayList<ActivityRecord> activities = new ArrayList<ActivityRecord>();
5135
5136 if ("all".equals(name)) {
5137 for (ActivityRecord r1 : mHistory) {
5138 activities.add(r1);
5139 }
5140 } else if ("top".equals(name)) {
5141 final int N = mHistory.size();
5142 if (N > 0) {
5143 activities.add(mHistory.get(N-1));
5144 }
5145 } else {
5146 ItemMatcher matcher = new ItemMatcher();
5147 matcher.build(name);
5148
5149 for (ActivityRecord r1 : mHistory) {
5150 if (matcher.match(r1, r1.intent.getComponent())) {
5151 activities.add(r1);
5152 }
5153 }
5154 }
5155
5156 return activities;
5157 }
5158
5159 ActivityRecord restartPackage(String packageName) {
5160 ActivityRecord starting = topRunningActivityLocked(null);
5161
5162 // All activities that came from the package must be
5163 // restarted as if there was a config change.
5164 for (int i = mHistory.size() - 1; i >= 0; i--) {
5165 ActivityRecord a = mHistory.get(i);
5166 if (a.info.packageName.equals(packageName)) {
5167 a.forceNewConfig = true;
5168 if (starting != null && a == starting && a.visible) {
5169 a.startFreezingScreenLocked(starting.app, ActivityInfo.CONFIG_SCREEN_LAYOUT);
5170 }
5171 }
5172 }
5173
5174 return starting;
5175 }
Dianne Hackborn50dc3bc2010-06-25 10:05:59 -07005176}